5.2 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 match the output below.

Python Program to Find the Largest and Smallest Numbers from User Input

When learning programming, one of the most useful exercises is processing user input and performing calculations based on that data. Python makes it easy to build interactive programs that accept input, validate it, and compute results.

In this tutorial, we will create a Python program that repeatedly asks the user to enter numbers. The program keeps track of the largest and smallest numbers entered by the user. The user can stop entering numbers by typing "done". After the loop ends, the program prints the maximum and minimum values entered.

Exercises like this help beginners understand important Python concepts such as loops, conditional statements, exception handling, and variable initialization. This example is similar to exercises found in learning resources such as Python for Everybody, which is widely used to teach programming fundamentals.


Problem Description

The program must perform the following tasks:

  1. Ask the user to enter numbers continuously.

  2. If the user enters "done", stop the program.

  3. Track the largest number entered.

  4. Track the smallest number entered.

  5. Handle invalid input such as letters or symbols.

  6. After finishing, display the maximum and minimum numbers.

This exercise demonstrates how Python programs process input dynamically.


Python Program

Below is the complete Python code.

largest = None
smallest = None

while True:
try:
num = input("Enter a number: ")

if num == "done":
break

num = int(num)

if largest is None or largest < num:
largest = num

elif smallest is None or smallest > num:
smallest = num

except ValueError:
print("Invalid input")

print("Maximum is", largest)
print("Minimum is", smallest)

Understanding the Program Step by Step

Let us examine how this program works.


1. Initializing Variables

The program begins by creating two variables.

largest = None
smallest = None

Here, both variables are assigned the value None.

In Python, None represents the absence of a value. It is useful when we want to initialize a variable but do not yet know its value.

These variables will later store:

  • largest → the biggest number entered

  • smallest → the smallest number entered


2. Creating an Infinite Loop

The program uses a while loop to repeatedly ask for input.

while True:

The condition True means the loop will run indefinitely until it is stopped manually using the break statement.

This allows the user to enter multiple numbers without knowing in advance how many inputs will be given.


3. Using Try and Except for Error Handling

Inside the loop, the program uses a try-except block.

try:

This allows Python to catch errors and prevent the program from crashing.

If the user enters something that cannot be converted into a number (such as text), Python would normally produce an error. The except block handles this situation gracefully.


4. Asking the User for Input

The program then asks the user to enter a number.

num = input("Enter a number: ")

Example input sequence:

Enter a number: 10
Enter a number: 5
Enter a number: 20
Enter a number: done

5. Checking for the Exit Condition

Next, the program checks whether the user entered the word done.

if num == "done":
break

If this condition is true, the break statement immediately exits the loop.

This stops the program from asking for more numbers.


6. Converting Input to an Integer

If the input is not done, the program converts the input into a number.

num = int(num)

The int() function converts the input string into an integer value.

Example:

"10" → 10
"5" → 5

This conversion is necessary because mathematical comparisons require numeric values.


7. Updating the Largest Number

Next, the program checks whether the entered number is the largest so far.

if largest is None or largest < num:
largest = num

This condition has two parts.

First, if largest is None, it means no numbers have been entered yet. Therefore, the current number automatically becomes the largest.

Second, if the new number is greater than the existing largest number, the program updates the largest variable.

Example:

Input: 10
largest = 10

Later:

Input: 20
largest = 20

8. Updating the Smallest Number

The program then checks for the smallest value.

elif smallest is None or smallest > num:
smallest = num

If smallest is still None, the first number becomes the smallest.

Otherwise, if the new number is smaller than the current smallest value, the program updates the smallest variable.

Example:

Input: 5
smallest = 5

9. Handling Invalid Input

If the user enters something that cannot be converted to an integer, Python raises an error.

Example:

Enter a number: abc

This causes a ValueError.

The program handles this using:

except ValueError:
print("Invalid input")

Instead of crashing, the program simply prints:

Invalid input

and continues asking for numbers.

This makes the program more user-friendly.


10. Printing the Final Result

After the loop finishes, the program prints the results.

print("Maximum is", largest)
print("Minimum is", smallest)

Example output:

Maximum is 20
Minimum is 5

This shows the largest and smallest numbers entered by the user.


Example Program Execution

Enter a number: 10
Enter a number: 5
Enter a number: 8
Enter a number: abc
Invalid input
Enter a number: 20
Enter a number: done
Maximum is 20
Minimum is 5

Key Concepts Learned

This program demonstrates several important Python concepts.

Loops

The while loop allows the program to repeat tasks multiple times.

Conditional Statements

The if and elif conditions help compare values and update variables.

Exception Handling

The try-except block prevents the program from crashing due to invalid input.

Variables

Variables store and update the largest and smallest values dynamically.


Possible Improvement

One improvement is updating the smallest number separately instead of using elif.

Example improved version:

if largest is None or num > largest:
largest = num

if smallest is None or num < smallest:
smallest = num

This ensures both conditions are checked independently.


Real-World Applications

Programs like this are useful in many real-world situations.

Examples include:

  • Finding highest and lowest exam scores

  • Analyzing temperature data

  • Processing financial transactions

  • Evaluating sensor readings

Learning how to track maximum and minimum values is an essential programming skill.


Conclusion

In this tutorial, we built a Python program that continuously accepts user input and determines the largest and smallest numbers entered. The program demonstrates key programming concepts such as loops, conditional logic, input validation, and exception handling.

By practicing exercises like this, beginners can improve their understanding of Python and develop the logical thinking needed to solve programming problems effectively.

Mastering these basic concepts will help you build more advanced programs involving data processing, automation, and analysis.

Post a Comment

2 Comments

  1. infinite loop me fas jayenge

    ReplyDelete
  2. largest = None
    smallest = None

    while True:
    num = input("Enter a number: ")
    if num == "done":
    break
    try:
    n = int(num)
    if largest is None or largest n:
    smallest = n
    elif smallest <n:
    n = n
    except:
    print("Invalid input")

    print("Maximum is", largest)
    print("Minimum is" ,smallest)

    ReplyDelete