为什么max()函数不按预期运行?

时间:2017-01-15 16:59:16

标签: python

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功能。为什么?

2 个答案:

答案 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
  1. int()将返回0:
  2.   

    class int(x,base = 10)

         

    返回一个由数字或字符串x构成的整数对象,或   如果没有给出参数则返回0 。如果x是数字,则返回x .__ int __()。对于浮点数,这会截断   零。

    In [7]: int() == 0 == False
    Out[7]: True
    
    1. 你应该在数字列表中使用max而不是字符串列表,在append列出之前将字符串转换为int
    2. "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)