Exception Handling V2 - Python Programming Exercise

This Python program prompts the user for a real number and displays its square root. The program uses a "try...except" block to handle any potential errors that may arise, such as the user entering a negative number (since the square root of a negative number is not defined in real numbers) or a non-numeric input. When the user inputs a valid real number, the program calculates and displays the square root using the math.sqrt() function. If an error occurs, such as entering an invalid number or a negative number, the except block ensures that the program doesn't crash and displays an appropriate error message instead. This program demonstrates how to handle exceptions in Python, making it more robust and user-friendly. The use of "try...except" allows the program to manage unexpected inputs gracefully, ensuring it continues running even if an error occurs. By testing the program with both valid and invalid inputs, users can verify if the program behaves as expected, correctly computing the square root or handling errors when necessary. This reinforces the concept of error handling in Python, which is crucial for developing more resilient and dependable applications.

 Category

Python Data Types

 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

 Copy 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.

  •  Character

    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...

  •  Triangular Shape

    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...

  •  String Password

    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...

  •  Arithmetic - Conditional

    This Python program prompts the user for two numbers and an operation to perform on them, such as addition (+), subtraction (-), multiplication (*), or divisio...

  •  Double Value

    This Python program calculates the perimeter, area, and diagonal of a rectangle, based on the given width and height. The perimeter is cal...

  •  Evaluate Function Outputs

    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, ...