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')
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Sep 1, 2022 at 15:08
\$\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')
answered Sep 1, 2022 at 15:26
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Thank you, janos! \$\endgroup\$ Commented 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\$ Commented 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\$ Commented 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\$ Commented Sep 2, 2022 at 3:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.