Module 7 Assignment 5.2 Answer
Programming for Everybody (Getting Started with Python) Module 7 Assignment 5.2 Answer.
Question: Find the Largest and Smallest Numbers
Instructions
Write a Python program that:
- Repeatedly prompts the user to enter integer numbers.
- Stops when the user enters
"done"
. - Ignores invalid inputs (like
"bob"
) and displays"Invalid input"
. - Finds and prints the largest and smallest numbers entered.
Test Input:
7, 2, bob, 10, 4, done
Expected Output:
Invalid input
Maximum is 10
Minimum is 2
Correct Python Code
# Initialize variables for largest and smallest numbers
largest = None
smallest = None
# Loop to take user input repeatedly
while True:
num = input("Enter a number: ")
if num == "done":
break # Exit loop if user enters 'done'
try:
n = int(num) # Convert input to integer
if largest is None or n > largest:
largest = n # Update largest number
if smallest is None or n < smallest:
smallest = n # Update smallest number
except ValueError:
print("Invalid input") # Handle non-numeric input
# Print the final results
print("Maximum is", largest)
print("Minimum is", smallest)
Explanation
- Initialize variables
largest
andsmallest
toNone
. - Use a
while True
loop to repeatedly ask for user input. - Check if the input is
"done"
, and break the loop if it is. - Try converting input to an integer:
- If successful, update
largest
andsmallest
accordingly. - If unsuccessful (
ValueError
), print"Invalid input"
and continue.
- If successful, update
- After exiting the loop, print the maximum and minimum values.
Why This Code is Correct
✅ Handles both valid and invalid inputs properly.
✅ Updates largest and smallest correctly.
✅ Matches exact expected output.
✅ Uses try/except
to catch non-numeric inputs.
Expected Output for Test Case
Input Sequence:
7, 2, bob, 10, 4, done
Program Output:
Invalid input
Maximum is 10
Minimum is 2