Input
Input validation code checks user's entered values.
"""Input validation:
We repeatedly ask user for input values.
"""
while True:
age = input('What is your age? ')
try:
age = int(age)
except:
print('Please use numberic values!')
continue
if age < 0:
print('Please enter a positive number!')
continue
break
print(f'Your age is: {age}')
# What is your age? abc
# Please use numberic values!
# What is your age? -10
# lease enter a positive number!
# What is your age? 20
# Your age is: 20
Plus
Pyinputplus module has useful features like limit of tries.
"""Pyinputplus
Contains functions similar to input() for other kind of data:
number, date, email, adress
Pyinputplus is not part of the standard distribution.
pip install pyinputplus
Import as pyip save us from typing pyinputplus every time.
"""
import pyinputplus as pyip
response = pyip.inputNum('What is your age? ', min=10, limit=4)
print(f'Your age is: {response}')
# What is your age? 6
# Number must be at minimum 10.
# What is your age? -10
# Number must be at minimum 10.
# What is your age? abc
# 'abc' is not a number.
# What is your age? 5
# Exception: pyinputplus.RetryLimitException
response = pyip.inputMenu(['dog', 'cat', 'horse'], lettered=True,
prompt='What is your favorite animal? \n'
)
print(f'Your favorite animal is: {response}')
# What is your favorite animal?
# A. dog
# B. cat
# C. horse
# b
# Your favorite animal is: cat
Last update: 450 days ago