在Python代码中请求用户输入时出现EOF错误
程序“goofin.py”要求用户提供一个列表,并且应该从列表中删除奇数并打印出新的列表。这是我的密码:在Python代码中请求用户输入时出现EOF错误,python,input,eoferror,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 re
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
def拆卸(lst):
结果=[]
对于lst中的元素:
如果元素%2==0:#如果列表元素为偶数
result.append(elem)#向结果中添加偶数列表元素
返回结果
justaskin=input(“给我一个列表,我来计算赔率:)#这是
#产生
#EOF
#错误
打印(remodds(justaskin))#应该只打印偶数的列表-
#编号元素
#我正在使用Windows Powershell和Python 3.6来运行代码。请帮忙!
#错误消息:
#回溯(最近一次呼叫最后一次):
#文件“goofin.py”,第13行,在
#打印(删除(justaskin))
#remodds中第4行的文件“goofin.py”
#如果元素%2==0:
#TypeError:在字符串格式化过程中并非所有参数都已转换
这对我来说很好:
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
希望这有帮助 您的输入
lst
不是一个列表,即使您键入的列表类似于2、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(',')]
您是否在有机会键入任何内容之前,或在按enter键之后,或在其他时间收到错误?我在Windows Powershell中运行程序时收到错误。在我点击enterPost后,你的错误。在您的问题中。在lst中的元素的
之间放置一个打印(元素,键入(元素))
:如果元素%2==0:
,您将立即看到您的问题所在。根据您键入的内容,您有a)一个问题是您的元素是字符串,b)您有其他列表元素,如空格,,
或[]
。