如何针对2个不同的字符串检查变量? 9行例子

时间:2015-07-18 01:46:49

标签: python variables

为什么这不起作用?

rank=input("Is the realm a duchy, kingdom or empire? ")  
if rank=="duchy"or"Duchy":  
    realm=input("What is the duchy named? ")  
elif rank=="kingdom"or"Kingdom":  
    realm=input("What is the kingdom named? ")  
elif rank=="empire"or"Empire":  
    realm=input("What is the empire named? ")  
else:  
    print("Restart and say duchy, kingdom or empire. ")  

无论我的答案是什么,我都会被问到公爵的名字是什么。

2 个答案:

答案 0 :(得分:0)

正在评估if "Dutchy",它会返回True

你需要

if rank=="duchy"or rank == "Duchy":

或更好,

if rank.lower() == "duchy":

答案 1 :(得分:0)

代码中的错误在if statement

if rank=="duchy"or"Duchy":  
# it equals
if rank == "duchy" or bool("Duchy"):
# equals
if rank == "duchy" or True:
# equals
if True:

因此,无论您的rank是什么,or "duchy"总是会True。你有很多解决方案来解决这个问题:

# Fix your "or" statement
if rank =="duchy" or rank == "Duchy":

# Use "in" keyword
if rank in ("duchy", "Duchy"):

# Use "string.capitalize()"
if rank.capitalize() == "Duchy":