[英]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.")
到目前为止,这是我正在为我的脚本 class 编写的更高/更低游戏的代码。 我在测试时遇到的问题是:嵌套的 if/else 语句在错误猜测后返回到 while 循环的开头,例如“不,太低了”。 我知道这就是 while 循环的工作原理; 但是,我无法弄清楚如何在不提示用户输入另一个下限/上限的情况下继续执行 if/else 语句。 显然,我最好的猜测是使用嵌套循环,我只是不知道在这种情况下如何使用。
您不需要嵌套循环,只需在不同的循环中设置上/下即可。
顺便说一句,你永远不会在最后到达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.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.