Python - 我无法理解这个错误

时间:2014-04-18 13:33:12

标签: python string formatting

我正在尝试编写一个程序,询问用户4个整数并打印输入的最大奇数。这是代码:

a = raw_input("Enter an int: ")
b = raw_input("Enter an int: ")
c = raw_input("Enter an int: ")
d = raw_input("Enter an int: ")

numbers = [a, b, c, d]
odd_numbers = []
print numbers
for i in numbers:
    if i%2!=0:
        odd_numbers.append(i)
    else:
        print "This is not an odd number."


for nums in odd_numbers:
    max_num = max(odd_numbers)
    print max_num

这是我收到的错误:

line 10, in <module>
  if i%2!=0:
TypeError: not all arguments converted during string formatting

我做错了什么?

4 个答案:

答案 0 :(得分:3)

raw_input()返回一个字符串。结果,numbers列表成为字符串列表。 %操作行为取决于变量类型,如果是字符串则是string formatting操作:

>>> s = "3"
>>> s % 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

如果是int,它会为您提供division remainder

>>> n = 3
>>> n % 2
1

您需要将所有输入转换为int

a = int(raw_input("Enter an int: "))
b = int(raw_input("Enter an int: "))
c = int(raw_input("Enter an int: "))
d = int(raw_input("Enter an int: "))

为避免使用冗余代码,您可以使用list comprehension简化numbers列表的填写:

numbers = [int(raw_input("Enter an int: ")) for _ in xrange(4)]

答案 1 :(得分:0)

您输入字符串但需要使用整数进行计算。 我你做print type(a),例如你会看到你实际上有一个字符串作为输入。将其解析为int的方法是使用内置函数int()

a = raw_input("Enter an int: ")
b = raw_input("Enter an int: ")
c = raw_input("Enter an int: ")
d = raw_input("Enter an int: ")

numbers = [a, b, c, d]
odd_numbers = []
print numbers
for i in numbers:
    value = int(i)
    if value%2!=0:
        odd_numbers.append(value)
    else:
        print "This is not an odd number."


for nums in odd_numbers:
    max_num = max(odd_numbers)
    print max_num

答案 2 :(得分:0)

因为您输入的内容为string,请将其转换为int

>>> a =raw_input("Enter an int: ")
Enter an int: 10
>>> type(a)
<type 'str'> 

试试这个:

a =int(raw_input("Enter an int: "))
b = int(raw_input("Enter an int: "))
c = int(raw_input("Enter an int: "))
d = int(raw_input("Enter an int: "))

OR

for i in numbers:
    if int(i)%2!=0:
             odd_numbers.append(i)

您的输出应如下所示:

>>> 
Enter an int: 10
Enter an int: 20
Enter an int: 20
Enter an int: 50
[10, 20, 20, 50]
This is not an odd number.
This is not an odd number.
This is not an odd number.
This is not an odd number.

答案 3 :(得分:0)

raw_input会返回一个字符串。因此,numbers中的每个元素都是字符串

numbers = ["1", "2", "3", "4"]

当您尝试i%2时,python会将%评估为string formatting operator,但无法在字符串中找到任何占位符以进行格式化并引发错误。因此,您必须将输入解析为int

a = int(raw_input("Enter an int: "))

或者您可以使用input,它会将您的输入评估为正确的类型(在您的情况下为int)

a = input("Enter an int: ")

但是,如果您没有使用inputeval states in the docs,则不建议使用{{1}}:

  

相当于eval(raw_input(prompt))。

     

此功能不会捕获用户错误。如果输入语法无效,则会引发SyntaxError。如果在评估过程中出现错误,可能会引发其他异常。

     

如果加载了readline模块,则input()将使用它来提供精细的行编辑和历史记录功能。

     

考虑将raw_input()函数用于用户的一般输入。