Higher/Lower 游戏的嵌套循环

Nested Loops for a Higher/Lower Game

import random

seedVal = int(input("What seed should be used? "))
random.seed(seedVal)

while (True):
    lower = int(input("What is the lower bound? "))
    upper = int(input("What is the upper bound? "))
    number = random.randint(min(lower, upper), max(lower, upper))

    if (lower >= upper):
        print("Lower bound must be less than upper bound.")

    else:
        guess = int(input("What is your guess? "))
        if (guess < number):
            print("Nope, too low.")

        elif (guess > number):
            print("Nope, too high.")

        elif (guess == number):
            print("You got it!")
            break

        else:
            print("Guess should be between lower bound and upper bound.")

这是我目前正在编写的 higher/lower 游戏的代码 class。我在测试时 运行 遇到的问题是:嵌套的 if/else 语句在错误猜测后返回到 while 循环的开头,例如“不,太低”。我知道 while 循环是这样工作的;但是,我不知道如何在不提示用户进行另一个 lower/upper 绑定的情况下让 if/else 语句继续。显然,我最好的猜测是使用嵌套循环,我只是不知道在这种情况下该怎么做。

您不需要嵌套循环,只需在不同的循环中设置 upper/lower。

顺便说一句,你永远不会到达最后的 else,因为你不检查值是否在范围内。

correct_boundaries = False
while not correct_boundaries:
    lower = int(input("What is the lower bound? "))
    upper = int(input("What is the upper bound? "))
    if (lower >= upper):
        print("Lower bound must be less than upper bound.")
    else:
        number = random.randint(min(lower, upper), max(lower, upper))
        correct_boundaries = True


while (True):

        guess = int(input("What is your guess? "))
        if (guess < number):
            print("Nope, too low.")

        elif (guess > number):
            print("Nope, too high.")

        elif (guess == number):
            print("You got it!")
            break

        else:
            print("Guess should be between lower bound and upper bound.")

只需将它们移出循环

import random

seedVal = int(input("What seed should be used? "))
random.seed(seedVal)

lower = int(input("What is the lower bound? "))
upper = int(input("What is the upper bound? "))
if (lower >= upper):
    raise ValueError("Lower bound must be less than upper bound.")

number = random.randint(min(lower, upper), max(lower, upper))

while (True):    
    guess = int(input("What is your guess? "))
    if (guess < number):
        print("Nope, too low.")
    elif (guess > number):
        print("Nope, too high.")
    elif (guess == number):
        print("You got it!")
        break
    else:
        print("Guess should be between lower bound and upper bound.")