Home > Software design >  I'm getting an error trying to find the max an min of a set of inputs by the user
I'm getting an error trying to find the max an min of a set of inputs by the user

Time:12-26

This is my assigned task :

Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and having as output:

Invalid input Maximum is 10 Minimum is 2

This is what I have so far but is not showing me the maximum neither the minimum of the inputs , as is not showing the Invalid input whenever the user try to put any word in it .

list = []

for i in range(2,10):
  list.append(int(input('Ingrese un número\n')))

# Ordenar lista
list.sort()

# Numero menor
print(list[0])
# Numero mayor
print(list[-1])


largest = None
smallest = None
while True:
    num = input("Enter a number: ")
    if num == "done":
        break
    print(num)

print("Maximum", largest)

CodePudding user response:

Code:-

lis = []
while True:
    try:
        num=int(input("Enter a number: "))
        lis.append(num)
    except ValueError:
        print("It is not a number.. please verify!! Invalid input\n")
    check=input("If you want to continue to write number please enter. if you are done please write done:\n")
    if check.lower() == "done":
        break
print("Maximum", max(lis))
print("Minimum",min(lis))

Output:-

Enter a number: 7
If you want to continue to write number please enter. if you are done please write done:

Enter a number: 2
If you want to continue to write number please enter. if you are done please write done:

Enter a number: bob
It is not a number.. please verify!! Invalid input

If you want to continue to write number please enter. if you are done please write done:

Enter a number: 10
If you want to continue to write number please enter. if you are done please write done:
done
Maximum 10
Minimum 2

CodePudding user response:

You can use walrus operator (:=) to prompt and check if num equals 'done' or not. Catch invalid num using try except and add num to numlist if it can be casted to int. Print out the largest and the smallest num of numlist using max() and min().

numlist = []
while (num := input('Enter a number: ')) != 'done':
    try: numlist  = [int(num)]
    except ValueError: print('Invalid input')

print('Maximum is', max(numlist))
print('Minimum is', min(numlist))

Output:

Enter a number: 7
Enter a number: 2
Enter a number: bob
Invalid input
Enter a number: 10
Enter a number: 4
Enter a number: done
Maximum is 10
Minimum is 2
  • Related