我正在学习Python并尝试构建一个猜数字游戏。 游戏会随机生成1到250(含)之间的整数供用户猜测。当用户输入超出范围时,它会提示用户超出范围并请求重新输入。同样,它会提示用户是否太高或太低,直到猜出正确的数字。在任何时候,如果用户输入“停止”,游戏就会结束。 作为作业要求的一部分,我需要在已提供的函数之上编写 2 个新函数,并将其合并到游戏的最终运行中。
我正在尝试将下面的 while 循环转换为一个没有太多进展的函数。它要么以位置参数错误结束,要么以无限循环结束。
the_number = random.randint(1,250)
# capture initial user input
user_input = get_user_input()
# repeat code below as long as the user has not guessed the right number
while user_input != the_number:
# repeat code below as long as user has not entered STOP
while user_input != 'STOP':
# verify user input is within range
check_range(user_input)
if user_input < the_number:
slow_print("{} is too low". format(user_input))
print('\n')
user_input = get_user_input()
elif user_input > the_number:
slow_print("{} is too high". format(user_input))
print('\n')
user_input = get_user_input()
else:
slow_print("Congratulations you have guessed the correct number")
break
else:
slow_print('\nGame stopped by user. Thank you for playing')
break
请有人建议我如何将 while 循环转换为有效的函数。
最佳答案
我不确定您想要实现什么,但如果您需要做的只是添加另外 2 个功能,那么也许这就是您正在寻找的;
the_number = random.randint(1,250)
# capture initial user input
user_input = get_user_input()
# repeat code below as long as the user has not guessed the right number
while user_input != the_number:
# repeat code below as long as user has not entered STOP
while user_input != 'STOP':
# verify user input is within range
check_range(user_input)
if user_input < the_number:
tooLow(user_input)
user_input = get_user_input()
elif user_input > the_number:
tooHigh(user_input)
user_input = get_user_input()
else:
slow_print("Congratulations you have guessed the correct number")
break
else:
slow_print('\nGame stopped by user. Thank you for playing')
break
def tooLow(number):
slow_print("{} is too low". format(number))
print('\n')
def tooHigh(number):
slow_print("{} is too high". format(number))
print('\n')
关于python - 如何在Python函数中应用嵌套的while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56678358/