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.")
Related
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')
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")
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
Current code may have more bugs than I see at the moment, but what I am trying to fix is the get_guess() function. At the moment I have coded it to print i in the "for i in range..." because whenever I input a guess, it automatically assumes i = 0 and prints "You can only guess numbers." I'm not sure why, when 0 is part of the list of numbers that it is supposed to check. Any ideas on how to fix this?
Side note, things are indented correctly, I am just not used to the formatting of this website.
import random
def explain_instructions():
print("I am thinking of a number with nonrepeating digits. You will have 10 attempts to try and guess my number.")
print("'Bagel' will be displayed if no digits are correct.")
print("'Pico' will be displayed if a digit is correct but in the wrong place.")
print("'Fermi' will be displayed if a correct digit is in the correct place.")
def generate_number(length):
num_list = [0,1,2,3,4,5,6,7,8,9]
random.shuffle(num_list)
secret_num = num_list[0:length]
secret_num = "".join(str(digit) for digit in secret_num)
return secret_num
def give_clues(secret_num, guess):
clues = []
for i in range(len(str(guess))):
if guess[i] == secret_num[i]:
clues.append("Fermi")
elif guess[i] in secret_num and guess[i] != secret_num[i]:
clues.append("Pico")
if clues == []:
clues.append("Bagel")
return(clues)
print(clues)
def get_guess(length, guess):
for i in range(int(length)):
if guess[i] in guess[:i] or guess[i] in guess[i+1:]:
print("Repeating numbers don't work in this game.")
return
elif len(guess) != len(secret_num):
print("You don't have the correct number of digits.")
return
elif guess[i] not in num_list and guess != "":
print(i,"You can only guess numbers.")
return
else:
return int(guess)
def play_again():
print("Would you like to play again? (Yes/No)")
answer = input()
if answer.lower()== "yes":
return True
else:
print("That wasn't a firm 'yes' so.... goodbye :( ")
print("Welcome to Bagel, Fermi, Pico!")
explain_instructions()
num_list = [0,1,2,3,4,5,6,7,8,9]
game_is_done = False
while True:
print("How long would you like your number to be?")
length = input()
secret_num = generate_number(int(length))
print(secret_num)
max_guess = 0
while max_guess < 10:
print("Enter a", length, "digit guess:")
guess = input()
if guess == "411":
print(explain_instructions())
elif get_guess(length,guess):
max_guess += 1
clue = give_clues(secret_num,guess)
print(clue)
if clue == ['Fermi'] * len(secret_num):
print("Congrats! You guessed the correct number!")
break
if max_guess == 10:
print("Oh no! You have run out of guesses. The secret number was:", secret_num)
if not play_again():
break
I think it might be because you are declaring num_list inside the function
generate_number(length)
So when you ask for num_list outside the function, python has no idea what num_list is. Declaring it as a global variable could solve your problem (haven't tested it, though)
And yes, i = 0 because it's the iterator, not the number you've guessed. If you want to see your guess, write
print(guess[i],"You can only guess numbers.")
I would be careful with a couple things, nontheless
1. Specify that the input has to be a string. If you input an int without the quotes, it crashed (at least for me it crashed), or cast it to string before passing it to the function. It crashed when trying to access the array guess[i]
2. Be careful with digits that start with 0 (e.g. 02). Casting to int will transform it to 2 if you don't specify otherwise.
I created a Mastermind code and when I attempt to run it on my Mac it just says "logout". If anyone knows why, that would be extremely helpful! Here is the code:
def masterMind():
number = random.ranint(10000,99999) #the computer chooses 5 random numbers
userGuess = raw_input("Guess my 5 digit password:") #asking the user to input their guess
tries = 10 # telling the computer number of tries the user is allowed
while tries < 0: # 10 attempts is the maximum amount
if number != userGuess: # if the computer's password does not equal the user's guess then it equals to one attempt
tries += 1
userGuess = input("Guess my 5 digit password:")
else: #if the user and the computer's answers align
print "Win: ", userGuess
print number
tries = 10
while tries < 0:
will never enter the loop.
You may want to reverse the sense of the comparison, using > instead.
You'll also need to decrement tries within the loop rather than incrementing it.
more "pythonic" (2.x) way. fixes answers like "00000", fixes int to str compair.
def masterMind():
number = "%05d" % random.randint(0, 99999) #the computer chooses 5 random numbers
for tries in range(10):
user_guess = raw_input("Guess my 5 digit password:") #asking the user to input their guess
if number == user_guess:
print "Win on the %d try" % (tries + 1)
break
print "answer was:", number