gpt4 book ai didi

Python - 我无法理解这个错误

转载 作者:行者123 更新时间:2023-11-30 23:25:00 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,要求用户输入 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

我做错了什么?

最佳答案

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 = [int(raw_input("Enter an int: ")) for _ in xrange(4)]

关于Python - 我无法理解这个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23155265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com