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

han

我正在学习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循环转换为有效的函数。

麦迪逊·科托(Madison Courto)

我不确定您要实现的目标,但是如果您需要做的就是添加另外两个功能,那么也许这就是您想要的;

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')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章