1

我想知道是否有人可以告诉我这段代码有什么问题,当我运行代码时它什么也没显示,但如果我取出“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!");
4

3 回答 3

6

这是问题所在:

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")
于 2013-09-24T16:45:58.113 回答
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”等输入。如果这是一个问题,请使用第一个解决方案。

于 2013-09-24T16:46:53.493 回答
1

你检查correct不正确

if (correct == "Yes" or "yes"):

表示(correct == "Yes") or ("yes"),并且非空字符串True在 python 中计算为,所以第一个条件将始终是True。如果你想检查多个字符串,你可以这样做:

if (correct in ("Yes", "yes")):

但这一个没有考虑'yEs''yES'考虑。如果您想要不区分大小写的比较,那么我认为correct.lower() == "yes"将是首选方法。

于 2013-09-24T16:49:05.303 回答