[英]How can I create a user input loop for a Guess the Number game between 1-100?
#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.每次我猜一个数字时,它都会退出代码。
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您忘记在评论中的代码中将输入转换为 int,所以这就是它不起作用的原因
return
will break the define so you should return the data when the user guess the correct answer return
将打破定义,因此当用户猜出正确答案时,您应该返回数据
from random import *
correct_number = randint(1, 100)
#print(correct_number)
def guess(user_guess):
while user_guess != 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_guess = int(input("Guess a number between 1 and 100.\n"))
else:
print("Guess a higher number\n")
user_guess = int(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这将工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.