简体   繁体   English

在给定输入中查找 python 中的最大和最小数字

[英]Finding largest and smallest number in python in given input

lst = []
while True:
    num = int(input("Please enter a number: "))
    if num == -1:
        break
    lst.append(int(num))
print(max(lst))
print(min(lst))

So here is the code.所以这里是代码。 It works but when i enter -1 as a first number it gives an error like "ValueError: max() arg is an empty sequence.它可以工作,但是当我输入 -1 作为第一个数字时,它会给出一个错误,例如“ValueError:max() arg 是一个空序列。

How can i exit from the program directly when -1 is entered as first number?当 -1 作为第一个数字输入时,如何直接退出程序?

break only breaks out of the loop, print() functions are still being executed. break只是跳出循环, print()函数仍在执行中。 Since lst is an empty list, it has no max() hence the error.由于lst是一个空列表,它没有max()因此错误。

To exit out of program do this:要退出程序,请执行以下操作:

lst = []
while True:
    num = int(input("Please enter a number: "))
    if num == -1:
        break
    lst.append(int(num))
if lst:
    print(max(lst))
    print(min(lst))

if ypu enter -1 as a first number, you break out of the loop before actually adding it to the list.如果 ypu 输入 -1 作为第一个数字,则在实际将其添加到列表之前退出循环。 Thus the list is empty, which explains your error.因此列表为空,这解释了您的错误。

This code should work for you:此代码应该适合您:

EDIT: Made sure code printed min() and max() before exiting编辑:确保代码在退出前打印min()max()

lst = []
while True:
    num = int(input("Please enter a number: "))
    if num == -1:
        if len(lst) > 0:
            print(max(lst))
            print(min(lst))
        quit()
    lst.append(int(num))
print(max(lst))
print(min(lst))

quit() , well, quits the program. quit() ,好吧,退出程序。

You can also use the exit() function too.您也可以使用exit() function。

Documentation文档

In this case you can use a try - catch code block to detect the error and manage it like this:在这种情况下,您可以使用try - catch代码块来检测错误并像这样管理它:

try:
    ... code that throws error ...
except ValueError:
    ... Handling of the ValueError ...
else:
    ... Normal case with no errors ...

once input is -1, you need to see the max and min of the list before exiting the program.一旦输入为-1,您需要在退出程序之前查看列表的最大值和最小值。

lst = []
while True:
    num = int(input("Please enter a number: "))
    if num == -1:
        if lst:
            print(max(lst))
            print(min(lst))
        else:
            print("list is empty")
        exit(0)
    lst.append(num)
print(max(lst))
print(min(lst))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM