gpt4 book ai didi

Python 猜谜游戏——if vs while

转载 作者:行者123 更新时间:2023-12-05 05:39:05 28 4
gpt4 key购买 nike

我正在尝试用 Python 制作一个简单的猜谜游戏。我,用户,有 3 次猜测来猜出正确的数字。我尝试自己做,我使用了if语句,而在正确的解决方案中,应该使用while循环。我的解决方案运行良好,但是当我在第一次或第二次尝试中猜出正确的数字时,我收到一条错误消息,指出第二个/第三个数字的输入缺失,请参见下面的代码。我知道 'break' 只能在 while 循环中使用。有没有办法使用 if 语句来完成这项工作,还是只能通过使用 while 循环来解决?这里是初学者'coder',请耐心等待。谢谢!

correct = 3

first_number = int(input('Guess: '))

if first_number == correct:
print('You win!')
elif first_number != correct:
second_number = int(input('Try again: '))

if second_number == correct:
print('You win, second guess!')
elif second_number != correct:
third_number = int(input('Last guess: '))

if third_number == correct:
print('Finally!')
elif third_number != correct:
print('You lose!')

最佳答案

python 3.8。我们在 while 循环中使用 walrus 运算符。

之前:

correct = 3

first_number = int(input('Guess: '))

if first_number == correct:
print('You win!')
elif first_number != correct:
second_number = int(input('Try again: '))

if second_number == correct:
print('You win, second guess!')
elif second_number != correct:
third_number = int(input('Last guess: '))

if third_number == correct:
print('Finally!')
elif third_number != correct:
print('You lose!')

之后:

correct = 3

while (first_number := int(input('Guess: ')) is not correct):
print('Try again!')
else:
print('You win!')

关于Python 猜谜游戏——if vs while,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72782677/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com