最小/最大输出有时正确,其他时候不正确

问题描述 投票:0回答:1

所以我正在编写一个基本程序,输出的一部分是说明用户输入的最低和最高数字。由于某些原因,min and max在某些时候是正确的,而在其他时候则是正确的。而且我无法弄清楚何时是对还是错(不一定是最低的数字是第一个或最后一个,等等)。其他所有功能都可以正常运行,并且每次代码都能正常运行。这是代码:

total = 0
count = 0
lst = []
while True:
    x = input("Enter a number: ")
    if x.lower() == "done":
        break
    if x.isalpha():
        print("invalid input")
        continue
    lst.append(x)
    total = total + int(x)
    count = count + 1
    avg = total / count

print("The total of all the numbers your entered is: " + str(total))
print("You entered " + str(count) + " numbers.")
print("The average of all your numbers is: " + str(avg))
print("The smallest number was: " + str(min(lst)))
print("The largest number was: " + str(max(lst)))

有什么想法吗?请记住,我(显然)在编码研究的初期。谢谢!

python loops max min
1个回答
0
投票

如果在程序末尾添加:

print("Your input, sorted:", sorted(lst))

您应该按照Python认为的排序顺序查看lst

您会发现它并不总是与您认为的排序相符。

这是因为当元素按数字顺序排列时,您认为lst已排序。但是,要素不是数字,而是数字。当您将它们添加到lst时,它们就是字符串,即使您在它们上调用min()max()sorted(),Python也会将它们视为字符串。

解决问题的方法是,通过以下方式将int添加到lst列表中:

lst.append(x)

至:

lst.append(int(x))

进行这些更改,看看是否有帮助。

P.S .:而不是像在打印语句中那样对所有这些整数值调用str()

print("The total of all the numbers your entered is: " + str(total))
print("You entered " + str(count) + " numbers.")
print("The average of all your numbers is: " + str(avg))
print("The smallest number was: " + str(min(lst)))
print("The largest number was: " + str(max(lst)))

您可以利用以下事实:Python的print()函数将单独打印每个参数(默认情况下用空格分隔)。因此,请改用它,它更简单,更易于阅读:

print("The total of all the numbers your entered is:", total)
print("You entered", count, "numbers.")
print("The average of all your numbers is:", avg)
print("The smallest number was:", min(lst))
print("The largest number was:", max(lst))

((如果需要,您可以使用f-strings。但是您可以自己查看。)

© www.soinside.com 2019 - 2024. All rights reserved.