|
| 1 | +# number_input_examples.py |
| 2 | + |
| 3 | +# This file accompanies the Real Python article "How To Read User Input As Integers". |
| 4 | +# It contains examples of functions that filter user input for valid integers and floats. |
| 5 | + |
| 6 | + |
| 7 | +def get_integer(prompt: str, error_message: str = None) -> int: |
| 8 | + # Prompts the user for an integer value. If the input is invalid, |
| 9 | + # prints error_message (if specified) and then repeats the prompt. |
| 10 | + while True: |
| 11 | + try: |
| 12 | + return int(input(prompt)) |
| 13 | + except ValueError: |
| 14 | + if error_message: |
| 15 | + print(error_message) |
| 16 | + |
| 17 | + |
| 18 | +def get_float(prompt: str, error_message: str = None) -> float: |
| 19 | + # Prompts the user for a float value. If the input is invalid, |
| 20 | + # prints error_message (if specified) and then repeats the prompt. |
| 21 | + while True: |
| 22 | + try: |
| 23 | + return float(input(prompt)) |
| 24 | + except ValueError: |
| 25 | + if error_message: |
| 26 | + print(error_message) |
| 27 | + |
| 28 | + |
| 29 | +def get_integer_with_default( |
| 30 | + prompt: str, default_value: int, error_message: str = None |
| 31 | +) -> int: |
| 32 | + # Prompts the user for an integer. If the input is an empty string, |
| 33 | + # returns default_value. Otherwise, if the input is not a valid integer, |
| 34 | + # prints error_message (if specified) and then repeats the prompt. |
| 35 | + while True: |
| 36 | + input_string = input(prompt) |
| 37 | + if input_string == "": |
| 38 | + return default_value |
| 39 | + try: |
| 40 | + result = int(input_string) |
| 41 | + return result |
| 42 | + except ValueError: |
| 43 | + if error_message: |
| 44 | + print(error_message) |
| 45 | + |
| 46 | + |
| 47 | +# Run this file as a main module |
| 48 | +# (ie python number_input_examples.py) |
| 49 | +# to perform simple interactive testing of the functions. |
| 50 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + print(get_integer("Testing get_integer(): ")) |
| 53 | + print( |
| 54 | + get_integer("Testing get_integer() with an error message: ", "Invalid integer!") |
| 55 | + ) |
| 56 | + print(get_float("Testing get_float() with an error message: ", "Invalid float!")) |
| 57 | + print( |
| 58 | + get_integer_with_default( |
| 59 | + "Testing get_integer_with_default(): ", 99, "That's not a valid integer!" |
| 60 | + ) |
| 61 | + ) |
0 commit comments