numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(first_input)
while first_input:
input_numb = input("Write next number")
if input_numb == int():
numbers.append(input_numb)
elif input_numb == "done":
print("The largest number is "+max(numbers))
print("The smallest number is "+min(numbers))
break
有人可以看看这段代码并告诉我,我做错了吗?在我输入输入数字后,我想打印列表numbers
中的最大和最小数字,但我不知道为什么max函数不返回最大数字,而是返回最小数字(就像min
功能。为什么?
答案 0 :(得分:3)
numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(int(first_input))
while first_input:
input_numb = input("Write next number")
try:
numbers.append(int(input_numb))
except:
if input_numb == "done":
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))
break
else:
print('invalid input!')
出:
Write any number.When you are done just write "done":1
Write next numbera
invalid input!
Write next number2
Write next number3
Write next number6
Write next numberdone
The largest number is 6
The smallest number is 1
int()
将返回0:class int(x,base = 10)
返回一个由数字或字符串x构成的整数对象,或 如果没有给出参数则返回0 。如果x是数字,则返回x .__ int __()。对于浮点数,这会截断 零。
In [7]: int() == 0 == False
Out[7]: True
max
而不是字符串列表,在append
列出之前将字符串转换为int "The largest number is " + max(numbers)
回报:
TypeError: Can't convert 'int' object to str implicitly
,只需使用,
来连接字符串和int。答案 1 :(得分:0)
您应该使用int(my_input)
将输入转换为整数,然后将其添加到列表my_list.append(int(my_input))
并使用 max 或 min 函数{{ 1}}获取用户的所有输入后
max(my_list)