我试图制作一个猜谜游戏,如果你选择它,它会继续玩,但我在打破循环时遇到了问题,每次代码到达“”时,程序都会给我quit()一个错误
quit()
当我使用回复时: repl process died unexpetily
repl process died unexpetily
当我使用 programiz.com 时: Traceback (most recent call last): File "<string>", line 42, in <module> File "<string>", line 40, in game File "<frozen _sitebuiltins>", line 26, in __call__ SystemExit: None
Traceback (most recent call last): File "<string>", line 42, in <module> File "<string>", line 40, in game File "<frozen _sitebuiltins>", line 26, in __call__ SystemExit: None
所以我需要一些帮助,这是代码
import random import time Name = input("Hello there!, What is your name? ") print(f"Hi {Name}! Welcome to the guessing game. I'm going to pick a number between 1 and 100") def game(): time.sleep(2) print('picking ...') time.sleep(2) guess = int(input("Alright! What is your guess?: ")) correct_number = random.randint(1,2) guess_count = 1 while guess != correct_number: guess_count += 1 if guess < correct_number: guess = int(input("Nope.Try higher. What is your guess?: ")) else: guess = int(input("Nope.Try lower. What is your guess?: ")) print(f"Congrats {Name}! The right answer was {correct_number}. It took you {guess_count} guess.") time.sleep(3) Next_Try = input(''' Wanna Try again? 1: Yes! 2: No thanks ''') while Next_Try: if Next_Try == "1": game() else: time.sleep(2) print("Thanks for Playing!") quit() game()
我已经尝试过exit()但仍然有同样的问题
exit()
问题出在循环中的条件判断上。在 while Next_Try: 这一行,Next_Try 被当作条件进行判断,但它是一个字符串,因此始终为真。这导致程序无法跳出循环。
while Next_Try:
Next_Try
为了解决这个问题,可以将条件判断修改为 while Next_Try != "2":,这样只有当用户选择了 “No thanks”(即输入为 “2”)时,循环才会结束。
while Next_Try != "2":
以下是修复后的代码:
import random import time Name = input("Hello there! What is your name? ") print(f"Hi {Name}! Welcome to the guessing game. I'm going to pick a number between 1 and 100") def game(): time.sleep(2) print('picking ...') time.sleep(2) guess = int(input("Alright! What is your guess?: ")) correct_number = random.randint(1,2) guess_count = 1 while guess != correct_number: guess_count += 1 if guess < correct_number: guess = int(input("Nope. Try higher. What is your guess?: ")) else: guess = int(input("Nope. Try lower. What is your guess?: ")) print(f"Congrats {Name}! The right answer was {correct_number}. It took you {guess_count} guess.") time.sleep(3) Next_Try = input(''' Wanna Try again? 1: Yes! 2: No thanks ''') while Next_Try != "2": if Next_Try == "1": game() else: time.sleep(2) print("Thanks for Playing!") quit() game()
现在,当用户选择 “No thanks”(输入为 “2”)时,程序会结束。