在Python代码中要求用户输入时出现EOF错误

时间:2017-11-29 14:59:41

标签: python input eoferror

程序“goofin.py”询问用户列表,并且应该从列表中删除奇数并打印出新列表。这是我的代码:

def remodds(lst):
    result = []
    for elem in lst:
        if elem % 2 == 0:          # if list element is even
            result.append(elem)    # add even list elements to the result 
    return result


justaskin = input("Give me a list and I'll tak out the odds: ") #this is 
                                                                #generates 
                                                                #an EOF 
                                                                #error

print(remodds(justaskin))      # supposed to print a list with only even-
                               # numbered elements


#I'm using Windows Powershell and Python 3.6 to run the code. Please help! 

#error message: 

#Traceback (most recent call last):
# File "goofin.py", line 13, in <module>
#    print(remodds(justaskin))
# File "goofin.py", line 4, in remodds
#    if elem % 2 == 0:
#TypeError: not all arguments converted during string formatting

2 个答案:

答案 0 :(得分:0)

这对我来说很好:

def remodds(lst):
    inputted = list(lst)
    result = []
    for elem in inputted:
        if int(elem) % 2 == 0:          
            result.append(elem)
    return result


justaskin = input("Give me a list and I'll tak out the odds: ") 
print(remodds(justaskin))   

我的意见:

15462625

我的输出:

['4', '6', '2', '6', '2']

说明:

- convert the input (which was a string) to a list
- change the list element to an integer

希望这有帮助!

答案 1 :(得分:0)

即使您输入lst2, 13, 14, 7等列表,您的输入2 13 14 7也不是列表。它仍然是一个字符串,当你用elem循环分开时,意味着每个字符都是一个循环。您必须首先拆分lst并将其转换为数字。

def remodds(lst):
    real_list = [int(x) for x in lst.split()]
    result = []
    for elem in real_list:           #and now the rest of your code

split方法目前使用数字之间的空格,但您也可以定义元素之间用逗号分隔。

 real_list = [int(x) for x in lst.split(',')]