4
\$\begingroup\$

Is it a bad thing to use asserts to validate user inputs? Or should I keep using an if statement in case the number isnt positive?

Code with assert statement:

def get_posit_n() -> int:
    from locale import atoi
    while True:
        try:
            number = atoi(input('Enter a positive integer:\n-> ').strip())
            assert (number > 0)
            return number
        except (ValueError, AssertionError):
            print('Number must be an positive integer...\n')

Code with if statement:

def get_positive_integer(msg: str = "Enter a integer value: ") -> int:
    from locale import atoi
    while True:
        try:
            number: int = atoi(input(msg + '\n-> ').strip())
            if number <= 0:
                continue
            return number
        except ValueError:
            print('Invalid value!\n')
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

The intended use of assert is in test code, or to validate internal preconditions.

To validate user input, the common recommendation is to raise a ValueError.

There is no point in raising an error (with assert in the posted code) only to catch it right after.

Also, AssertionError is not meant to be caught, it's meant to let it crash the program.

Taking the best parts of the examples:

from locale import atoi


def input_positive_integer() -> int:
    while True:
        try:
            number: int = atoi(input('Enter a positive integer:\n-> ').strip())
            if number <= 0:
                print('Number must be a positive integer...\n')
                continue
            return number
        except ValueError:
            print('Invalid value!\n')
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Thank you, janos! \$\endgroup\$
    – eddyxide
    Sep 1, 2022 at 15:32
  • \$\begingroup\$ What does atoi do? "Attempt to Integer"? Is it basically forcing/expecting the input to be an integer? \$\endgroup\$
    – BruceWayne
    Sep 2, 2022 at 1:31
  • 2
    \$\begingroup\$ @BruceWayne It appears to be a standard function: docs.python.org/3/library/locale.html#locale.atoi \$\endgroup\$
    – Teepeemm
    Sep 2, 2022 at 1:51
  • \$\begingroup\$ @Teepeemm I will look into it, thanks. I wonder why int() wouldn't work ...but that's a separate question. \$\endgroup\$
    – BruceWayne
    Sep 2, 2022 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.