Beginner trying to learn python [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
When I run my code and guess the right number, the code doesn't work and says try again.
How do I fix it?
import random
number = random.randint(1,10)
print("Please enter your number down below")
yourguess = input()
if number == yourguess:
print("You guessed it")
else:
print("Try again")

You either need to compare strings, or compare numbers. I suggest turning the input into an integer like this:
import random
number = random.randint(1,10)
yourguess = int(input("Please enter your number: "))
if number == yourguess:
print("You guessed it")
else:
print("Try again")

Input defaults to string, you need to change it to int to be comparable. Other than that your code is fine.
import random
number = random.randint(1,10)
print("Please enter your number down below")
yourguess = input()
yourguess = int(yourguess)
if number == yourguess:
print("You guessed it")
else:
print("Try again")

Related

How to make an input part of a random variable? [duplicate]

This question already has answers here:
Generate random integers between 0 and 9
(22 answers)
Closed 1 year ago.
So I am coding a simple guessing game in python. I want to make it that you can choose up to what number you want the computer to guess. Starting from one. How do I make it so that the user input of an integer is the last number the computer will guess to? This is the code:
import random
while True:
print("Welcome to odds on. Up to what number would you like to go to?")
num = int(input())
print("Welcome to odds on. Make your choice:")
choice = int(input())
cc = [1, num]
print()
computerchoice = random.choice(cc)
importing python builtin module
import random
let's say
num = 10
random.randint(1,num)
the retuerned integer will be between 1, 10
I hope you had something like this in mind. A guessing game that takes two inputs. Maximum integer and the users number choice and outputs if the user is correct or not. Game doesn't end because of the while-loop.
Working Code:
import random
while True:
try:
print("Welcome to GUESS THE NUMBER. Up to what number would you like to go to?")
maxNum = int(input())
if maxNum <= 1:
print('Number has to be greater than 0')
break
print("Guess the number:")
choice = int(input())
if choice <= 1:
print('Your Choice has to be greater than 0')
break
correctNumber = random.randint(0,maxNum)
if choice == correctNumber:
print('CORRECT')
break
else:
print('WRONG')
except:
ValueError
print('Enter a number, not something else you idiot')
And here the same code but the user only has 3 retries: (The indentations can be wrong if you copy paste my code)
import random
retry = 3
while retry != 0:
try:
print("Welcome to GUESS THE NUMBER. Up to what number would you like to go to?")
maxNum = int(input())
if maxNum <= 1:
print('Number has to be greater than 0')
break
print("Guess the number:")
choice = int(input())
if choice <= 1:
print('Your Choice has to be greater than 0')
break
correctNumber = random.randint(0,maxNum)
if choice == correctNumber:
print('CORRECT')
break
else:
print('WRONG')
retry -= 1
except:
ValueError
print('Enter a number, not something else you idiot')
if retry == 0:
print('You LOOSER')

How do I prevent a user from entering a previous guess in my python guessing game? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I want to store a list of guesses the user has already made, so that when the user makes the next guess I can check that guess against a list of previous guesses. If the guess the user just made is in that list I want to tell the user to guess again and not count it as a attempt(5 attempts at guessing correct number)
tried using the append method to append the guesses to a blank list but I'm getting a "int obj has no append method" error.
import random
def guess_a_number():
chances = 5
random_number_generation = random.randint(1,21)
while chances != 0:
choice = int(input("Guess a number between 1-20, you only have {} chances left ".format(chances)))
if choice > random_number_generation:
print("Your number is too high, guess lower")
elif choice < random_number_generation:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
if chances == 0:
try_again = input("Do you want to try play again? ")
if try_again.lower() == "yes":
guess_a_number()
else:
print("Better luck next time")
guess_a_number()
Try keeping a list of previous guesses and then check if guess in previous_guesses: immediately after the choice. You can use continue to skip the rest and prompt them again.
Just use a set or a list to hold the previously attempted numbers and check for those in the loop.
I think you already tried something similar but by the sound of it you were attempting to append to an int.
import random
while True:
chances = 5
randnum = random.randint(1, 21)
prev_guesses = set()
print("Guess a number between 1-20, you have {} chances ".format(chances))
while True:
try:
choice = int(input("what is your guess? "))
except ValueError:
print('enter a valid integer')
continue
if choice in prev_guesses:
print('you already tried {}'.format(choice))
continue
if choice > randnum:
print("Your number is too high, guess lower")
elif choice < randnum:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
prev_guesses.add(choice)
print("you have {} chances left".format(chances))
if chances == 0:
print("You ran out of guesses, it was {}".format(randnum))
break
try_again = input("Do you want to play again? ")
if try_again.lower() not in ("y", "yes"):
print("Better luck next time")
break

Python: How to fix my code that will allow to repeat the input task whenever I enter anything except integer? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
Another newbie question:
I'm trying to add a statement inside a while loop that if the person enters anything except integer it will repeat the input but I didn't figure out how to do that without ruining the program. Whenever I enter anything i get the following error: "ValueError: invalid literal for int() with base 10" What is needed to be added to my code?
Here is my code:
import random
#Playing dice game against the computer
num = int(input("Enter a number between 1 and 6 please: "))
while not int(num) in range(1, 7):
num = int(input("Please choose a number between 1 and 6: "))
def roll_dice(num):
computer_dice = random.randint(1, 6)
if num > computer_dice:
print("Congratulations you win! Your opponent's dice is:", computer_dice)
elif num < computer_dice:
print("Sorry but you lose! Your opponent's dice is:", computer_dice)
else:
print("Draw. Your opponent's dice is:", computer_dice)
roll_dice(num)
Thank you in advance!
I think the problem is that you are trying an empty string to an integer. Same problem when you type in alphabetical characters.
You can use try and except to try the conversion of the input to an integer and then when it failed you run the loop again and when the conversion was successfully you have your number.

Python 3.6.5. Why does OR not work as i expect it to? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 4 years ago.
Why if i use OR at !!! section, does it break even if i type a number 1 - 9 in the guess input. And why do i not need to type BOTH 'q' and 'quit', because thats what i assume AND means... 'q' AND 'quit'...
import random
while True:
print("\nGuess a number between 1 and 9.")
guess = input("I guess: ")
if guess == 'q' !!!or!!! 'quit':
break
number = random.randrange(1, 10)
try:
if int(guess) < number:
print(f"You guess was too low. The number was {number}")
elif int(guess) > number:
print(f"Your guess was too high. The number was {number}")
elif int(guess) == number:
print(f"Your guess was exactly right! The number was {number}")
except ValueError:
print("Please only guess numbers!")
So with OR it doesn't work and with AND it does. This makes no sense to me. Why is this?
if guess == 'q' or 'quit':
This statement will not work because you are trying to use a string as a boolean. The OR doesn't assume you want the exact same thing to happen like before it, you have to fill the condition again.
if guess == 'q' or guess == 'quit':
This will work because you are now getting a boolean out of the right side instead of just trying to use a string.

Loops not working in Python 3

I originally wrote this program in python 2, and it worked fine, then I switched over to python 3, and the while loop working.
I don't get any errors when I run the program, but it isnt checking for what the value of i is before or during the run. The while loop and the first if loop will run no matter what.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")
Thanks for any help in advance.
You are comparing something like '6' == 6, since you didn't convert the user input to an int.
Replace user_answer = input("Try to guess the magic number. (1 - 10) ") with user_answer = int(input("Try to guess the magic number. (1 - 10) ")).
user_answer will store the input as string and random.randint(1,10) will return an integer. An integer will never be equal to a string. So you need to convert user_input to integer before checking.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then
asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
# better use exception handling here
try:
user_answer = int(user_answer)
except:
pass
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")

Categories

Resources