Without given error-message I can only suggest improvement:
- simplify the test for even number with
in [2,4]
(compare to a list of integers instead combining string-comparison)
- extract the test as function and make it defensive/safe (test also for int)
- improve readability of the loop-condition similar to "ask while input not valid"
- format strings (use f-string since Python 3.8) and give user a feedback which input was invalid
- reuse the prompt when asking for input
# extract condition to a function
def valid_even_num(number):
# test for int and number is even (in valid range)
if isinstance(number, int) and number in [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
return True
else
return False
# can reuse the prompt
prompt = "Please enter an even number from 1-20: "
# following input returned to n can also be a string
n = input(prompt)
# test what happens if no number is entered. Does int(n) raise an error?
while not valid_even_num(int(n)):
print(f"Entry '{n}' is invalid!\n")
n = input(prompt)
print(f"Entry {n} accepted.")
For advanced input-retries see Asking the user for input until they give a valid response.
The answer there explains the same pattern that Martineau answered: while True: try/except/continue
.