Code: Alles auswählen
#!/usr/bin/env python3
def ask_input(convert, prompt="", error_message=""):
while True:
user_string = input(prompt)
try:
return convert(user_string)
except ValueError as error:
print(error_message.format(user_string, error))
def choice(convert, low, high):
def validate(user_string):
value = convert(user_string)
if not low <= value <= high:
raise ValueError("Invalid choice")
return value
return validate
def run_demo():
number = ask_input(
choice(int, 1, 10), "Choose a number (1-10): ", "Invalid choice: {!r}"
)
print("You picked", number)
if __name__ == "__main__":
run_demo()