Exercise
Exception Handling V2
Objective
Develop a Python program to prompt the user for a real number and display its square root. Errors must be handled using "try...except".
Does it behave as you expected?
Example Python Exercise
Show Python Code
import math
# Prompt the user for a real number
number = input("Enter a real number: ")
try:
# Convert the input to a float
number = float(number)
# Check if the number is non-negative
if number < 0:
raise ValueError("Cannot compute the square root of a negative number.")
# Calculate the square root
square_root = math.sqrt(number)
# Display the square root
print(f"The square root of {number} is {square_root}")
except ValueError as ve:
# Handle invalid input or negative numbers
print(f"Error: {ve}")
except Exception as e:
# Handle any other unexpected errors
print(f"Unexpected error: {e}")
Output
Enter a real number: 25
The square root of 25.0 is 5.0
Enter a real number: -4
Error: Cannot compute the square root of a negative number.
Enter a real number: abc
Error: could not convert string to float: 'abc'
Enter a real number: 9.0
The square root of 9.0 is 3.0
Share this Python Exercise
More Python Programming Exercises of Python Data Types
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.
This Python program prompts the user to input three letters and then displays them in reverse order. The program uses basic input and string manipulation techn...
This Python program prompts the user to input a symbol and a width, then displays a triangle of the specified width using that symbol for the inner part...
This Python program prompts the user for a username and a password (both should be strings) and repeats the process until the correct credentials are en...
This Python program prompts the user for two numbers and an operation to perform on them, such as addition (+), subtraction (-), multiplication (*), or divisio...
This Python program calculates the perimeter, area, and diagonal of a rectangle, based on the given width and height. The perimeter is cal...
This Python program displays the values of the function y = x² - 2x + 1 for integer values of x ranging from -10 to +10. The function is a quadratic equation, ...