简体   繁体   中英

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.

How can i exit from the program directly when -1 is entered as first number?

break only breaks out of the loop, print() functions are still being executed. Since lst is an empty list, it has no max() hence the error.

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. 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

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.

You can also use the exit() function too.

Documentation

In this case you can use a try - catch code block to detect the error and manage it like this:

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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