[英]Repeat while loop if input is a specific string
我刚刚创建了一个小游戏,如果用户愿意,我想重复它。 我创建了一个输入,然后尝试将 guess_count 变量设置回 0,所以我认为它会再次触发 while 循环。
secret_number = 8
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Guess the number: "))
guess_count += 1
if guess == secret_number:
print("You won!")
break
else:
print("Sorry, you failed!")
try_again = input("Try again? ")
if try_again == "yes":
guess_count = 0
playing = True
secret_number = 8
while playing:
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Guess the number: "))
guess_count += 1
if guess == secret_number:
print("You won!")
break
else:
print("Sorry, you failed!")
try_again = input("Try again? (yes/no) ")
if try_again == "no":
playing = False
在else
块中将guess_count
设置回0
将不会再次触发循环。 这是因为else
块是在循环退出后执行的。 您可能希望将重新启动循环的逻辑移到循环本身中。 例如。
secret_number = 8
guess_count = 0
guess_limit = 3
while True:
if guess_count >= guess_limit:
print("Sorry, you failed!")
try_again = input("Try again? ")
if try_again == "yes":
guess_count = 0
continue
else:
break
else:
guess = int(input("Guess the number: "))
guess_count += 1
if guess == secret_number:
print("You won!")
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.