你需要做兩件事情:
在此行中刪除方括號:
numbers = [numbers.split(',')]
否則,str.split
返回的列表將被放在另一個列表。
將由str.split
返回的字符串列表轉換爲整數列表。這可以用map
和int
來完成:
numbers = map(int, numbers.split(','))
否則,下一行%
將被解釋爲字符串格式化,這將引發錯誤:
Traceback (most recent call last):
File ".\t.py", line 3, in <module>
odds = [x for x in numbers if x%2==1]
TypeError: not all arguments converted during string formatting
以下是您的腳本的固定版本:
numbers = raw_input('Enter 10 integers separated by comma ')
numbers = map(int, numbers.split(','))
odds = [x for x in numbers if x%2==1]
# The Python standard for indentation is 4 spaces
if not odds:
print "no odd number was entered"
else:
print max(odds)
演示:
>>> numbers = raw_input('Enter 10 integers separated by comma ')
Enter 10 integers separated by comma 1,2,3,4,5,6,7,8,9,10
>>> numbers = map(int, numbers.split(','))
>>> odds = [x for x in numbers if x%2==1]
>>> if not odds:
... print "no odd number was entered"
... else:
... print max(odds)
...
9
>>>