How to handle non-numeric input?

To handle non-numeric input in Python, you can use a try-except block to catch exceptions when converting input to a numeric type. Here's an example that demonstrates this:

Example Code

price = 10.00  # Price of one book

# Get user input for quantity
user_input = input("Enter the quantity of books: ")

try:
    quantity = int(user_input)  # Attempt to convert input to an integer
    total_cost = price * quantity
    print(f"The total cost for {quantity} books is ${total_cost:.2f}.")
except ValueError:
    print("Please enter a valid numeric value for quantity.")

Explanation

  1. Input: The program prompts the user to enter the quantity of books.
  2. Try Block: It attempts to convert the input to an integer.
  3. Except Block: If the input is non-numeric (e.g., a string like "three"), a ValueError is raised, and the program prints an error message.

This way, you can ensure that your program handles non-numeric inputs gracefully. If you have more questions or need further assistance, let me know!

0 Comments

no data
Be the first to share your comment!