Python 在 false if 中执行 print 语句

问题描述 投票:0回答:1
salt = "Salt and Vinegar"
bland = "Saltenes"
sweet = "Chocolate"
spicy = "Takis"
sour = "Sour Patch Kids"
q1 = print(input("Do you want a bland or flavorful snack? "))
q2 = print(input("Do you want a sweeter or saltier snack? "))
q3 = print(input("Would you like a sour snack or not? "))
q4 = print(input("Would you like a spicy snack or not? "))
rec = ""

print(input("Do you want a bland or flavorful snack? "))
if q1 == "Bland":
   rec = bland
elif q1 == "Flavorful":
    print(input("Do you want a sweeter or saltier snack? "))
    if q2 == "Sweeter":
        print(input("Would you like a sour snack or not? "))
        if q3 == "Sour":
            rec = sour
        elif q3 == "Not":
            rec = sweet
    elif q2 == "Saltier":
        print(input("Would you like a spicy snack or not? "))
        if q4 == "Spicy":
            rec = spicy
        elif q4 =="Not":
            rec = salt

print("We recommend " + rec + " as your snack!")

我的代码看起来像这样。我在运行时遇到问题,例如, print(input("你想要更甜还是更咸的零食?")) 即使人们的输入很平淡,因此,不应该运行程序的其余部分.

我已经将每个问题设为自己的变量,并且我所有的最终答案都是变量。我相对确定,例如,使用字符串的 q1 == "Bland" 不会破坏我的代码,但我很可能是错的。我是编码新手。

python if-statement variables nested
1个回答
0
投票

您打算将变量分配给调用

input()
的结果,但在您的
if
部分中,这样您的程序就不需要运行其中的一些变量。

salt = "Salt and Vinegar"
bland = "Saltenes"
sweet = "Chocolate"
spicy = "Takis"
sour = "Sour Patch Kids"
rec = ""

q1 = input("Do you want a bland or flavorful snack? ")
if q1 == "Bland":
   rec = bland
elif q1 == "Flavorful":
    q2 = input("Do you want a sweeter or saltier snack? ")
    if q2 == "Sweeter":
        q3 = input("Would you like a sour snack or not? ")
        if q3 == "Sour":
            rec = sour
        elif q3 == "Not":
            rec = sweet
    elif q2 == "Saltier":
        q4 = input("Would you like a spicy snack or not? ")
        if q4 == "Spicy":
            rec = spicy
        elif q4 =="Not":
            rec = salt

print("We recommend " + rec + " as your snack!")

您不需要使用

print()
,因为
input()
反映了用户键入的内容。

© www.soinside.com 2019 - 2024. All rights reserved.