[英]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.