gpt4 book ai didi

python - 两个选项都在猜谜游戏中运行

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

所以我对编程非常陌生,我正在使用 Python (v3.33) 创建像这样的小程序:

option = input('What Game Would You Like To Play? A, B, C, or D? ')
option == 'A'
guess = int(input('Guess a number: '))
while True:
while guess != 100:
if guess > 100:
print('Too High... Try Again')
if guess < 100:
print('Too Low... Try Again')
guess = int(input('Guess a number: '))
if guess == 100:
print('You Win')
break

option == 'B'
guess = int(input('Guess a number: '))
while True:
while guess != 50:
if guess > 50:
print('Too High...Try Again')
if guess < 50:
print('Too Low... Try Again')
guess = int(input('Guess a number: '))
if guess == 50:
print('You Win')
break

这是我的问题 - 我希望用户能够选择“A”或“B”(我将添加“C”和“D”,但想先解决问题)但程序需要用户自动通过“A”,然后到达“B”:如何获取它以便用户可以选择“A”和“B”。另外,如果用户想再次运行它,我该如何制作,以便用户可以选择说"is"或“否”。谢谢

最佳答案

将整个事情包裹在一个 while 循环中:

while True:

option = input('What Game Would You Like To Play? A, B, C, or D (Q to quit)? ').upper() # this can accept both lower and upper case input

if option == 'Q':
break

elif option == 'A':
Do some code

elif option == 'B':
Do some code

elif option == 'C':
Do some code

elif option == 'D':
Do some code

else:
print ("You didn't enter a valid choice!")

关于您的代码:

option == 'A'

该行只是测试选项是否等于“A”。它返回 TrueFalse。您想要测试期权的实际值(value)。因此就有了上面的 if 语句。

您的代码只是运行所有场景,因为您没有提供事情发生的条件。仅当 option == 'A' 时才应运行针对该情况的代码。仅当 option == 'D' 时才应运行该代码。并且只有当 option == 'Q' 时主循环才会中断。这是何时使用 if 语句的一个很好的示例。

编辑:

针对您的评论,您可以执行以下操作:

option = input('What Game Would You Like To Play? A, B, C, or D (Q to quit)? ')
if option == 'a': # upper is gone, you can specify upper or lower case 'manually'
do this
if option == 'A':
do this

或者

if option in ['a', 'A']: # this basically same effect as my original answer
do something

查看 str.upper() 方法的工作原理 here

关于python - 两个选项都在猜谜游戏中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21667652/

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