Why if Is Not Enough: Understanding try/except in Python

Published: (December 20, 2025 at 06:29 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Cover image for Why if Is Not Enough: Understanding try/except in Python

Why if Is Not Enough

While I was writing a tip calculator in Python (you can check my GitHub for the full code), I realized that even though I used an if condition, errors were still happening.

The reason is that the if condition runs after the type conversion, but the error happens during the conversion itself.

def get_bill_amount(prompt: str) -> float:
    while True:
        value = input(prompt).strip()
        try:
            amount = float(value)
            if amount > 0:
                return amount
            print("Amount must be greater than 0.")
        except ValueError:
            print("Please enter a valid number.")
  • Expected user input: a number greater than 0
  • Type mismatch: when the user enters a string like abc
  • Error: the program crashes with ValueError: could not convert string to float

The key point is that float(value) is a risky operation. If the conversion fails, Python throws an error before the if condition is even checked.

Using value.isdigit() may look safe, but it fails for valid inputs like 12.5, -3, or even 10 with spaces. This is why try/except exists.

Rule of thumb

  • if → checks logic (rules, range, conditions)
  • try/except → catches crashes (invalid operations like type conversion)

Always use if to validate rules, and try/except to protect your program from crashing.

Back to Blog

Related posts

Read more »

Python Applied Mathematics Labs

Article URL: https://labs.acme.byu.edu/Pages/intro.html Comments URL: https://news.ycombinator.com/item?id=46381839 Points: 21 Comments: 1...

When Compilers Surprise You

Article URL: https://xania.org/202512/24-cunning-clang Comments URL: https://news.ycombinator.com/item?id=46375384 Points: 20 Comments: 3...