python 如何使用带条件的输入语句?[已关闭]

bsxbgnwa  于 2022-11-21  发布在  Python
关注(0)|答案(2)|浏览(151)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答案。

这个问题是由一个打字错误或一个无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
9小时前关门了。
Improve this question
希望有一个输入变量来问一个问题,有很多合适的真语句,但根据用户输入的内容给出不同的答案。我目前的代码与下面的类似,但不能正常工作。
我只想打印一个或另一个语句。我还想使这个代码适合许多其他的答案,如“也许你有什么?”“有便宜的东西吗?”“我想要一些随机的!”
我的代码如下所示:
第一个

moiiocjp

moiiocjp1#

从你的问题中,我理解的是,你需要一个问题列表来让用户回答。在Python 3.10中,可以使用matchcase关键字以更好的方式来完成,就像reference中提到的那样。我已经实现了一个示例,以供你理解,沿着提供了输出。
编码:

print('combo shack') ##title of my program
combo_1 = 'FOOD1' ###variable 1
combo_2 = 'FOOD2' ###variable 2
combo_3 = 'FOOD3' ####variable 3

menu_decision = input('Would you like to see the menu?') ####input variable for coustmers decision
match menu_decision:
    case 'yes':
        print('todays menu: ' + combo_1 + ', ' + combo_2 + ', ' + combo_3)
        order_decision = input('Would you like to order?')
        match order_decision:
            case 'yes':
                order = input('What would you like to order?')
                match order:
                    case 'FOOD1':
                        print('You ordered ' + combo_1)
                    case 'FOOD2':
                        print('You ordered ' + combo_2)
                    case 'FOOD3':
                        print('You ordered ' + combo_3)
                    case _:
                        print('Sorry we dont have that')
            
            case 'no':
                print('Have a nice day')
            case _:
                print('Sorry we dont have that')
    case 'no':
        exit('Have a nice day!')
    case _:
        print('Please enter yes or no')

输出量:

combo shack
Would you like to see the menu?yes
todays menu: FOOD1, FOOD2, FOOD3
Would you like to order?yes
What would you like to order?FOOD1
You ordered FOOD1
iezvtpos

iezvtpos2#

Python使用==来检查字符串条件匹配,例如:

print('combo shack')### title of my program
combo_1 = 'FOOD1, ' ### variable 1
combo_2 = 'FOOD2, ' ### variable 2
combo_3 = 'FOOD3 '  ### variable 3

menu_decision = input('would you like to see the menu?') #### input variable for coustmers decision

if menu_decision == 'yes':
    print('todays menu: ' + combo_1 + combo_2 + combo_3)

elif menu_decision == 'no': 
    exit('Have a nice day!')

elif menu_decision == 'I want something random!':
    randomizer = input('what is your food preference?')

相关问题