Limit user input length in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Limit user input length in Python #

To limit user input length:

  1. Use a while loop to iterate until the user enters a string of the specified length.
  2. Check if the user entered a message of the given length.
  3. If the condition is met, break out of the loop.
main.py
while True: user_input = input('Enter 3 characters: ') if len(user_input) > 3: print('Enter a maximum of 3 characters.') continue else: print(user_input) break

limit user input length

We used a while loop to iterate until the user enters a message that is maximum 3 characters long.

If you need to get a string of exactly N characters, check for equality.

main.py
while True: user_input = input('Enter 3 characters: ') if len(user_input) == 3: print(user_input) break else: print('Enter exactly 3 characters.') continue

On each iteration, we check if the user entered exactly 3 characters.

If they did, the if block runs and we break out of the while loop.

The break statement breaks out of the innermost enclosing for or while loop.

If they didn't, the else block runs where we print a message and continue to the next iteration of the loop.

You can use the same approach if you need to only allow the user to enter letters.

main.py
user_input = '' while True: user_input = input('Enter a maximum of 3 letters: ') if not user_input.isalpha() or len(user_input) > 3: print('Enter 3 letters.') continue else: print(user_input) break

The if statement runs if the input message doesn't contain only letters or has a length greater than 3.

If either condition is met, we continue to the next iteration and prompt the user again.

Otherwise, we print the input string and break out of the while loop.

You can use the same approach if you need to limit the user input string to a length of exactly N letters.

main.py
user_input = '' while True: user_input = input('Enter a maximum of 3 letters: ') if user_input.isalpha() and len(user_input) == 3: print(user_input) break else: print('Enter 3 letters.') continue

We used the boolean and operator, so for the if block to run, both conditions have to be met.

The first condition checks if the input string contains only letters and the second checks if it has a length of exactly 3 characters.

If both conditions are met, we use the break statement to break out of the loop.

Otherwise, we print a message and prompt the user again.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.