Objective
Develop a Python program to prompt the user for two numbers and display their division. Errors should be caught using "try..except".
Example Python Exercise
Show Python Code
# Prompt the user for two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Try to perform the division and handle any potential errors
try:
result = num1 / num2
print(f"The result of {num1} divided by {num2} is {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter valid numbers.")
Output
Case 1:
Enter the first number: 10
Enter the second number: 2
The result of 10.0 divided by 2.0 is 5.0
Case 2:
Enter the first number: ten
Enter the second number: 2
Error: Please enter valid numbers.
Case 3:
Enter the first number: ten
Enter the second number: 2
Error: Please enter valid numbers.
Share this Python Exercise
Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.
In this exercise, you will develop a Python program that prompts the user to input a number and then determines if the number is positive or n...
In this exercise, you will develop a Python program that prompts the user for a number. If the number is not zero, the program will ask for a second ...
In this exercise, you will develop a Python program that prompts the user for two numbers. The program will display their division if the second numb...
In this exercise, you will develop a Python program that prompts the user for two numbers. The program will display their division if the second numb...
In this exercise, you will develop a Python program that prompts the user to input three numbers and then determines and displays the largest one. This ...
In this exercise, you will develop a Python program that prompts the user for a number "x" and calculates the result of 10 * x. The program will display...