两个非常相似的object.extend()代码填充列表,一个工作一个没有

时间:2017-05-27 14:32:05

标签: python list if-statement

下面的程序应该将单词放在列表中。它的工作测试是'print(allwords [1])'。有趣的是底部部分有效,但是当我使用顶部部分时却没有。该列表显然是空的。我的工作有何不同?

# DOES NOT WORK
print ('On what difficulty do you want to play?\n')
diffculty = input('1.Easy\n2.Medium\n3.Hard\n\n')
if diffculty == 1 or input == 'Easy' or input == 'easy' or input == 'EASY':
    with open('google-10000-english-usa-no-swears-short.txt') as inputfile:
        for line in inputfile:
            allwords.extend(line.strip().split(','))
elif diffculty == 2 or input == 'Medium' or input == 'medium' or input == 'MEDIUM':
    with open('google-10000-english-usa-no-swears-medium.txt') as inputfile:
        for line in inputfile:
            allwords.extend(line.strip().split(','))
elif diffculty == 3 or input == 'Hard' or input == 'hard' or input == 'HARD':
    with open('google-10000-english-usa-no-swears-long.txt') as inputfile:
        for line in inputfile:
            allwords.extend(line.strip().split(','))

# WORKS
print ('Okay then, let us begin with your first word.\n')
with open('google-10000-english-usa-no-swears-long.txt') as inputfile:
    for line in inputfile:
        allwords.extend(line.strip().split(','))

print (allwords[1])

所以问题实际上是IF声明。我做了两处修改,现在它可以工作了。  我对字符串编号('1')进行了if语句检查。  我纠正了if变量(它们都应该是难以理解的) 谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

更改if statement

尝试将其与

放在一起
if diffculty == '1' or input == 'Easy' or input == 'easy' or input == 'EASY':

请注意1现在正在使用字符串

input存储为字符串,您尝试将其与int进行比较。

另外,就像@zwer在他的回答中提到的那样,最好将用户输入转换为小写进行比较。因此,您不必担心比较同一个词的多种可能性。您可以尝试以下方式:

print ('On what difficulty do you want to play?\n')
diffculty = input('1.Easy\n2.Medium\n3.Hard\n\n')

#The code below converts the user input to lower case. If example the user types 
# HARD or Hard or harD or something it converts it to 'hard'

diffculty = diffculty.lower()

print(diffculty)

if diffculty == '1' or diffculty == 'easy':
    print('easy')
    #do your easy code
elif diffculty == '2' or diffculty == 'medium':
    print('medium')
    #do your medium code
elif diffculty == '3' or  diffculty == 'hard':
    print('hard')
    #do your hard code
else:
  print('Please enter the correct difficulty level')

答案 1 :(得分:0)

input()为您提供了一个字符串,因此您需要在执行difficulty == 1和类似检查之前将其转换为int:

difficulty = int(input('1.Easy\n2.Medium\n3.Hard\n\n'))

您可能想要添加一些额外的验证。

此外,input()是一个函数,因此检查input == 'Hard'是否有意义。如果您想要考虑所有'来自用户输入的可能性,请执行以下操作:

difficulty = input('1.Easy\n2.Medium\n3.Hard\n\n').lower()  # turn input to lowercase
if difficulty in ("1", "easy"):
    # your easy code
elif difficulty in ("2", "medium"):
    # your medium code
elif difficulty in ("3", "hard"):
    # your hard code
else:
    # wrong input...