#Guess the number
from random import *
correct_number = randint(1, 100)
#print(correct_number)
def guess(user_guess):
while user_input != correct_number:
if user_guess == correct_number:
return f"{correct_number} is the correct number! Congratulations! Would you like to play again?"
elif user_guess > correct_number:
return "Guess a lower number\n"
user_input = int(user_input("Guess a number between 1 and 100.\n"))
else:
return "Guess a higher number\n"
user_input = int(user_input("Guess a number between 1 and 100.\n"))
"""user_input = ""
while user_input != correct_number:
user_input = input("Hey user, guess a number between 1 and 100.\n")"""
user_input = input("Hey user, guess a number between 1 and 100.\n")
user_input_guess = int(user_input)
value = guess(user_input_guess)
print(value)
I have the bulk of the code ready. I just can't nail the user input loop. Each time I guess a number it exits the code.
CodePudding user response:
from random import randint
correct_number = randint(1, 100)
user_input = ""
while user_input != correct_number:
user_input = int(input("Hey user, guess a number between 1 and 100.\n"))
No need to use functions. You forgot to convert the input to an int in the code inside the comment so that's why it wasn't working
CodePudding user response:
return
will break the define so you should return the data when the user guess the correct answer
#Guess the number
from random import *
correct_number = randint(1, 100)
#print(correct_number)
def guess(user_guess):
while user_input != correct_number:
if user_guess == correct_number:
return f"{correct_number} is the correct number! Congratulations! Would you like to play again?"
elif user_guess > correct_number:
print("Guess a lower number\n")
user_input = int(user_input("Guess a number between 1 and 100.\n"))
else:
print("Guess a higher number\n")
user_input = int(user_input("Guess a number between 1 and 100.\n"))
"""user_input = ""
while user_input != correct_number:
user_input = input("Hey user, guess a number between 1 and 100.\n")"""
user_input = input("Hey user, guess a number between 1 and 100.\n")
user_input_guess = int(user_input)
value = guess(user_input_guess)
print(value)
This will work