如何根据两个不同的字符串检查变量?9行examp

2024-10-06 03:59:46 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么这样不行

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. ")  

不管我怎么回答,都有人问我公爵叫什么名字


Tags: ortheinputifiswhatnamedempire
2条回答

代码中的错误在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":

它计算if "Dutchy",返回True

你需要

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

或者更好

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

相关问题 更多 >