Prompt the user for an integer input, retrying up to a given number of attempts. Args: prompt: The message shown to the user. attempts: Maximum number of input attempts. Returns: The integer entered by the user, or None if all attempts fail. Example:
(prompt: str, attempts: int)
| 21 | |
| 22 | |
| 23 | def get_integer_input(prompt: str, attempts: int) -> int | None: |
| 24 | """ |
| 25 | Prompt the user for an integer input, retrying up to a given number of attempts. |
| 26 | |
| 27 | Args: |
| 28 | prompt: The message shown to the user. |
| 29 | attempts: Maximum number of input attempts. |
| 30 | |
| 31 | Returns: |
| 32 | The integer entered by the user, or None if all attempts fail. |
| 33 | |
| 34 | Example: |
| 35 | User input: "12" -> returns 12 |
| 36 | """ |
| 37 | for i in range(attempts, 0, -1): |
| 38 | try: |
| 39 | # Attempt to parse user input as integer |
| 40 | n = int(input(prompt)) |
| 41 | return n |
| 42 | except ValueError: |
| 43 | # Invalid input: notify and decrement chances |
| 44 | print("Enter an integer only") |
| 45 | print(f"{i - 1} {'chance' if i - 1 == 1 else 'chances'} left") |
| 46 | return None |
| 47 | |
| 48 | |
| 49 | def sum_of_digits(n: int) -> int: |