python 如果我向IF添加OR选项,代码将无法正常运行[duplicate]

ewm0tg9j  于 2022-12-25  发布在  Python
关注(0)|答案(3)|浏览(141)
    • 此问题在此处已有答案**:

Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?(6个答案)
昨天关门了。
当我输入第7行or时,代码没有按预期工作。有人能告诉我原因吗?

# x = int(input("Insert price for your product :"))
x=100
print ("Does your product include taxes?")
# answer = input(" yes or no ")
answer = "no"
if answer == "yes" or "Yes" or "YES":
    print ("final price is : ", x, "\n the tax is :" ,x*0.17)
elif answer == "no":
     print ("final price is : ", x*1.17, "\n the taxes is ", x*0.17)
else:
    print ("Your answer is not according to the dictionnary - try again")

我希望对单词YES的任何输入都能对代码中的if起作用。

yeotifhr

yeotifhr1#

试试看:

if answer in ["yes","Yes","YES"]:
            OR
if answer == "yes" or answer=="Yes" or answer=="YES":

而不是。

if answer == "yes" or "Yes" or "YES":
zsohkypk

zsohkypk2#

而不是使用if answer == "yes" or "Yes" or "YES":.你应该试试
if answer == "yes" or answer == "Yes" or answer == "YES":.
或者使用python内置的方法lower(),这样就可以将输入小写

x = int(input("Insert price for your product :"))

print ("Does your product include taxes?")
answer = input(" yes or no ").lower()
if answer == "yes":
    print ("finel price is : ", x, "\nthe tax is :" ,x*0.17)
elif answer == "no":
     print ("finel price is : ", x*1.17, "\nthe taxes is ", x*0.17)
else:
    print ("Your answer is not according to the dictionary - try agin")
5sxhfpxr

5sxhfpxr3#

这是语法上的问题。

if answer == "yes" or "Yes" or "YES":

在Python中,在这个上下文中,每次使用什么变量时,都需要详细说明,例如:

if answer == "yes" or answer== "Yes" or answer== "YES":

也可以采用其他格式,例如:

answer = answer.lower()
if answer == "yes":
    print ("final price is : ", x, "\nthe tax is : " , x*0.17)
elif answer == "no":
    print ("final price is : ", x*1.17, "\nthe tax is : ", x*0.17)
else:
    print ("Your answer is not according to the dictionary - try again")

这个解决方案将把answer全部改为小写,这允许人们也写一些东西,比如YeS或yeS。2这也使代码看起来不那么混乱。

相关问题