Want to find the smallest and largest numbers in Python? This allows the user to enter a list of numbers until the user types done or press enter then the prompt would stop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | largest = None smallest = None while True: num = input('Enter a number: ') # Handle edge cases if num == 'done': break # Allows user to press enter to complete if len(num) < 1: break # Try and Except to catch input errors try: num = float(num) except: print('Invalid Input') # Jumps to the start of the loop without running the code below continue # This will be permanently false after the first iteration if smallest is None: smallest = num # Replaces the iteration variable with smaller input num if num < smallest: smallest = num # This will be permanently false after the first iteration if largest is None: largest = num # Replaces the iteration variable with larger input num elif num > largest: largest = num print("Maximum number:", largest) print("Smallest number:", smallest) |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.