What if input is not a number?

QuestionsQuestions8 SkillsProYour First Python LabNov, 20 2025
090

If the input is not a number (e.g., if the user enters a string like "twenty-five"), the program will raise a ValueError when it tries to convert the input to an integer using int(). To handle this situation gracefully, you can use a try-except block. Here's an updated version of the code:

age_str = input("How old are you? ")

try:
    age = int(age_str)
    print("Next year, you will be", age + 1)
except ValueError:
    print("Please enter a valid number.")

Explanation:

  • Try Block: Attempts to convert the input to an integer.
  • Except Block: Catches the ValueError if the conversion fails and prints a friendly message asking for a valid number.

This way, the program won't crash and will provide feedback to the user. If you have more questions or need further assistance, let me know!

0 Comments

no data
Be the first to share your comment!