我想知道是否有人可以告诉我这段代码有什么问题,当我运行代码时它没有显示任何内容,但如果我拿出“elif”它确实有效。\
first=input("What is your first name? ");
middle=input("What is your middle name? ");
last=input("What is your last name? ");
test = [first, middle, last];
print ("");
print ("Firstname: " + test[0]);
print ("Middlename: " + test[1]);
print ("Lastname: " + test[2]);
print ("");
correct=input("This is the information you input, correct? ");
if (correct == "Yes" or "yes"):
print ("Good!")
elif (correct == "no" or "No"):
print ("Sorry about that there must be some error!");
答案 0 :(得分:5)
问题在于:
if (correct == "Yes" or "yes"):
# ...
elif (correct == "no" or "No"):
# ...
应该是:
if correct in ("Yes", "yes"):
# ...
elif correct in ("No", "no"):
# ...
请注意,进行包含多个条件的比较的正确方法如下:
correct == "Yes" or correct == "yes"
但通常它写得像这样,更短:
correct in ("Yes", "yes")
答案 1 :(得分:3)
您需要使用in
关键字:
if correct in ("Yes", "yes"):
print ("Good!")
elif correct in ("no", "No"):
print ("Sorry about that there must be some error!")
或将整个输入转换为相同的大小写:
# I use the lower method of a string here to make the input all lowercase
correct=input("This is the information you input, correct? ").lower()
if correct == "yes":
print ("Good!")
elif correct == "no":
print ("Sorry about that there must be some error!")
就个人而言,我认为lower
解决方案是最干净,最好的。但请注意,它会使您的脚本接受诸如“YeS”,“yEs”等输入。如果这是一个问题,请使用第一个解决方案。
答案 2 :(得分:1)
您检错correct
if (correct == "Yes" or "yes"):
表示(correct == "Yes") or ("yes")
,非空字符串在python中计算为True
,因此第一个条件始终为True
。如果要检查多个字符串,可以执行以下操作:< / p>
if (correct in ("Yes", "yes")):
但是这个不考虑'yEs'
或'yES'
。如果你想要不区分大小写的比较,那么我认为correct.lower() == "yes"
将是首选方法。