【问题标题】:EOF error when asking user for input in Python code要求用户输入 Python 代码时出现 EOF 错误
【发布时间】:2017-11-29 14:59:40
【问题描述】:

程序“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

【问题讨论】:

  • 您是否在有机会输入任何内容之前、在您按 Enter 之后或在其他时间收到错误?
  • 在 Windows Powershell 中运行程序时出现错误。 IE。在我点击进入后
  • 发布您的错误。在您的问题中。
  • for elem in lst: if elem % 2 == 0: 之间放置一个print(elem, type(elem)),您将立即看到您的问题所在。取决于您输入的内容 a) 一个问题是您的 elem 是一个字符串 b) 您还有其他列表元素,例如 space,[]

标签: python input eoferror


【解决方案1】:

这对我来说很好用:

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

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    您输入的lst 不是一个列表,即使您输入的是2, 13, 14, 72 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(',')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 2022-11-13
      • 1970-01-01
      相关资源
      最近更新 更多