我正四处乱逛,想看看我能否使这个简单的程序正常工作。我想对照我的列表检查用户输入,并输出它是否在列表中。我目前如何设置它,它将返回0索引,但不返回其他两个索引。我在做什么错了?
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name == check_name[0]:
print("Welcome lisa")
if name == check_name[1]:
print("Welcome jim")
elif name == check_name[2]:
print("Welcome betty")
pass
else:
print("Sorry, Looks like you are not in the system")
pass
答案 0 :(得分:1)
您的最后两个if
语句仅对嵌套在第一个语句中的值进行求值。您需要取消缩进,以便他们可以评估是否第一个不匹配。
另一种解决方案:
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name not in check_name:
print("Sorry, Looks like you are not in the system")
答案 1 :(得分:0)
您有缩进问题。
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name == check_name[0]:
print("Welcome lisa")
elif name == check_name[1]:
print("Welcome Jim")
elif name == check_name[2]:
print("Welcome Betty")
else:
print("Sorry, Looks like you are not in the system")
答案 2 :(得分:0)
您已经在上面得到答案。这是另一种解决方案,无需使用多个if
语句来简化代码:
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name in check_name:
print("Welcome %s" %name)
else:
print("Sorry, Looks like you are not in the system")
命令if name in check_name:
检查输入的名称是否在名称列表中,并欢迎相应的人。如果输入名称不存在,则会引发Sorry...
语句