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')
1 Answer 1
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')
-
1\$\begingroup\$ Thank you, janos! \$\endgroup\$eddyxide– eddyxide2022年09月01日 15:32:30 +00:00Commented 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– BruceWayne2022年09月02日 01:31:31 +00:00Commented 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– Teepeemm2022年09月02日 01:51:30 +00:00Commented 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– BruceWayne2022年09月02日 03:06:12 +00:00Commented Sep 2, 2022 at 3:06
Explore related questions
See similar questions with these tags.