python - 如何在Python函数中应用嵌套的while循环

标签 python while-loop

我正在学习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/

相关文章:

python - 如何在 Windows 的控制台中显示语言的本地口音?

c++ - 使用 while 循环计算数学常数 e

java - 循环并比较变量值

python - 我可以递归地在 Zookeeper 中创建路径吗?

python - 在 Hadoop 上运行 MapReduce 程序仅输出一半的数据

while-loop - 同时停止多个 RT 定时循环的最佳方法?

bash - 监视目录并在创建时更改文件的所有权

javascript - 打印的字符串显示为未定义

python - 在 python 中忽略 numpy bincount 中的 NaN

python - tensorflow -对象检测.pbtxt;没有这样的文件或目录