大家好 我正在创建一个游戏,在这个游戏中,计算机选择一个随机数1-10 然后用户猜测数字,直到他们猜对为止。 我遇到的问题是,当用户输入错误的答案时,应该更新变量high或low,但它只是继续循环,直到用户输入正确的答案。这将导致“高”和“低”始终为0。 有什么想法吗?我知道我的循环方式可能有问题? 任何朝正确方向的推动都将是伟大的
# module to generate the random number
import random
def randomNum():
selection = random.randint(0,9)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = randomNum()
guess = userGuess()
high = 0
low = 0
if guess != correctNum:
print('uhoh try again!')
guess=userGuess()
elif guess > correctNum:
print('That guess is too high!')
high = high + 1
elif guess < correctNum:
print('That guess is too low')
low = low + 1
else:
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
main()
我发现这个解决方案可以很好地满足我的需要! 谢谢所有回复这篇文章的人
您可以尝试使用字典:
当然,这不是全部代码,但应该为您指明正确的方向。在线python词典上有大量的资源
尝试修改
main
函数:另外,要小心使用
random.randint(0,9)
:这将给出一个介于0-9之间的数字(包括0和9,但绝不是10)您想做^{cd3>}
相关问题 更多 >
编程相关推荐