如果语句在检查输入值时未按预期工作

时间:2014-02-07 12:45:47

标签: python

尝试让我的if允许用户输入名称或随机选择,但无论输入什么,它都会转到名称输入?

有什么想法吗?

这是我的代码:

import random
import os
names = "Balo", "Bandugl", "Baroro", "Cag", "Charoth", "Dugling", "Dulko", "Fangot", "Gormath", "Varth", "Ugort", "Ogong", "Tuli", "Corg", "Chau", "Korg", "Salath", "Wegia",        "Wecha", "Moroth", "Kangir", "Bethindu", "Duak", "Fagoot", "Penam"
rand_name = random.choice(names)

#Character creation (1)#
if input("Would you like to choose a name?: ") == "Y" or "y" or "yes" or "YES":
    print("")
    c1 = {"Name":input("Name: ")}
else:
    c1 = {"Name":rand_name}
print(c1)

提前致谢!

4 个答案:

答案 0 :(得分:3)

在你的行

if input("Would you like to choose a name?: ") == "Y" or "y" or "yes" or "YES":

您不能链接这样的值,它将按如下方式进行评估

( input("Would you like to choose a name?: ") == "Y") or ("y") or ("yes") or ("YES")

在这种情况下,or ("y")将返回True,因为非空字符串都已经过评估True

你必须尝试:

if input("Would you like to choose a name?: ") in ["Y", "y", "yes", "YES"]:

然后它会检查输入是"Y""y""yes"还是"YES"

之一

或者您可以使用str.upper()使您的选项列表不那么拥挤:

if input("Would you like to choose a name?: ").upper() in ["Y", "YES"]:

答案 1 :(得分:1)

if input("Would you like to choose a name?: ").lower() in ("y", "yes"):

答案 2 :(得分:0)

你的比较是错误的。

if input("Would you like to choose a name?: ") in ("Y", "y", "yes", "YES"):

了解您的错误:

>>> "a" == "Y" or "y"
'y'
>>> "Y" == "Y" or "y"
True

答案 3 :(得分:0)

在3

中使用raw_input(2.7)输入
import random
import os
names = "Balo", "Bandugl", "Baroro", "Cag", "Charoth", "Dugling", "Dulko", "Fangot", "Gormath", "Varth", "Ugort", "Ogong", "Tuli", "Corg", "Chau", "Korg", "Salath", "Wegia",        "Wecha", "Moroth", "Kangir", "Bethindu", "Duak", "Fagoot", "Penam"
rand_name = random.choice(names)

#Character creation (1)#
if raw_input('Enter your name: ').upper() in ["Y" , "YES" ]:
    print("")

    c1 = {"Name":raw_input("Name: ")}
else:
    c1 = {"Name":rand_name}
print(c1)