The following script prompts the user for a positive integer and is meant to make sure
that the given value is in the range 1-99
.
#!/usr/bin/env python3
def get_positive_int():
while True:
l = int(input("Level: "))
if 0 < l < 100:
return l
else:
get_positive_int()
l = get_positive_int()
print(l)
Submitting a positive integer yields no unexpected behaviour:
Level: 5
5
Yet when I give a negative integer than my interaction with the script looks like this:
Level: -300
Level: 5
Level: 5
5
I also noticed that when I remove the while
loop from get_positive_int
:
def get_positive_int():
l = int(input("Level: "))
if 0 < l < 100:
return l
else:
get_positive_int()
then my interaction with the script looks like this:
Level: -300
Level: 5
None
Why doesn't my code print 5
right away when it is submitted after submitting -300
?
Why does get_positive_int
seem to return None
despite having been given 5
?
I have not noticed such behaviour in other languages as in Bash
get_positive_int() {
echo "Level: "
read l
if [[ "${l}" -gt 0 ]] && [[ "${l}" -lt 100 ]]; then
:
else
get_positive_int
fi
}
get_positive_int
echo "${l}"
or in Racket
(define (take-positive-int) (displayln "Level: ")(let ((l (string->number (read-line))))
(if (and (> l 0) (< l 100)) l
(take-positive-int))))
(define l (take-positive-int))
(displayln l)
where the interaction looks like this:
Level:
-300
Level:
5
5