2016-12-15 54 views
0

工作/ ELIF我有这样的代码如果未如预期在Python 2.7

print "Choose a category: Animals, Jobs or Cars?" 
while True: 
    cat = str(raw_input()) 
    if cat.lower() == "animals": 
     wordfile = open("Animals.txt") 
     break 
    elif cat.lower == "jobs": 
     wordfile = open("Jobs.txt") 
     break 
    elif cat.lower == "cars": 
     wordfile = open("Cars.txt") 
     break 
    else: 
     print "That's not a valid category!" 

wordlist = [line.split("\n") for line in wordfile] 
print wordlist 

当我输入的动物,它完美的作品和我的打印文件的内容。然而,当我输入工作或汽车时,它告诉我,这不是一个有效的类别(它跳过elif的,直接去其他地方),我不明白为什么。

+4

你在'elif'语句中'cat.lower'丢失了括号 – LMc

+2

另外,为什么要使用'cat = str(raw_input())'? 'raw_input()'本身将返回一个字符串。 –

回答

1

它,因为你需要使用cat.lower()所有案件:

print "Choose a category: Animals, Jobs or Cars?" 
while True: 
    cat = str(raw_input()) 
    if cat.lower() == "animals": 
     wordfile = open("Animals.txt") 
     break 
    elif cat.lower() == "jobs": 
     wordfile = open("Jobs.txt") 
     break 
    elif cat.lower() == "cars": 
     wordfile = open("Cars.txt") 
     break 
    else: 
     print "That's not a valid category!" 

wordlist = [line.split("\n") for line in wordfile] 
print wordlist 

使用cat.lower不会实际执行小写的功能,这反而给你的实际功能本身,这搅乱参考if/elif语句

1

您在第二个和第三个elif s中丢失了() s。比较一个函数和一个字符串将会产生False。

+0

这个问题真的需要一个答案吗? –

+1

我没有批评,但你可能有一点。另外,有人似乎不分青红皂白地提起东西。 – kabanus