|
| 1 | +"""Utility functions for prompting users for numeric input. |
| 2 | +
|
| 3 | +This file accompanies the Real Python tutorial How To Read User Input As |
| 4 | +Integers. It contains examples of functions that filter user input for valid |
| 5 | +integers and floats. |
| 6 | +""" |
| 7 | + |
| 8 | + |
| 9 | +def get_integer(prompt: str, error_message: str = None) -> int: |
| 10 | + """Prompts the user for an integer value. |
| 11 | +
|
| 12 | + If the input is invalid, prints error_message (if specified) and then |
| 13 | + repeats the prompt. |
| 14 | + """ |
| 15 | + while True: |
| 16 | + try: |
| 17 | + return int(input(prompt)) |
| 18 | + except ValueError: |
| 19 | + if error_message: |
| 20 | + print(error_message) |
| 21 | + |
| 22 | + |
| 23 | +def get_float(prompt: str, error_message: str = None) -> float: |
| 24 | + """Prompts the user for a float value. |
| 25 | +
|
| 26 | + If the input is invalid, prints error_message (if specified) and then |
| 27 | + repeats the prompt. |
| 28 | + """ |
| 29 | + while True: |
| 30 | + try: |
| 31 | + return float(input(prompt)) |
| 32 | + except ValueError: |
| 33 | + if error_message: |
| 34 | + print(error_message) |
| 35 | + |
| 36 | + |
| 37 | +def get_integer_with_default( |
| 38 | + prompt: str, default_value: int, error_message: str = None |
| 39 | +) -> int: |
| 40 | + """Prompts the user for an integer, and falls back to a default value. |
| 41 | +
|
| 42 | + If the input is an empty string, then the function returns default_value. |
| 43 | + Otherwise, if the input is not a valid integer, prints error_message (if |
| 44 | + specified) and then repeats the prompt. |
| 45 | + """ |
| 46 | + while True: |
| 47 | + input_string = input(prompt) |
| 48 | + if not input_string: |
| 49 | + return default_value |
| 50 | + try: |
| 51 | + return int(input_string) |
| 52 | + except ValueError: |
| 53 | + if error_message: |
| 54 | + print(error_message) |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + # Test functions when running as a script. |
| 59 | + print(get_integer("Test get_integer(): ")) |
| 60 | + print( |
| 61 | + get_integer( |
| 62 | + "Test get_integer() with an error message: ", |
| 63 | + error_message="Invalid integer!", |
| 64 | + ) |
| 65 | + ) |
| 66 | + print( |
| 67 | + get_float( |
| 68 | + "Test get_float() with an error message: ", |
| 69 | + error_message="Invalid float!", |
| 70 | + ) |
| 71 | + ) |
| 72 | + print( |
| 73 | + get_integer_with_default( |
| 74 | + "Test get_integer_with_default(): ", |
| 75 | + default_value=99, |
| 76 | + error_message="That's not a valid integer!", |
| 77 | + ) |
| 78 | + ) |
0 commit comments