Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a function which limits user string input to a maximum of 30 characters with no spaces

This is my first post here so apologies if formatting is incorrect

I am a newcomer to coding having started Python recently in college and I am currently working on a project. Part of this project is to prompt the user for a string input, only allowing max. 30 characters and no spaces i.e. one word , then re-prompting the user for said input if the requirements are not met. I would like to assign this operation to a function which I have thus far failed to achieve. I am sure this is a relatively simple fix but as mentioned I am a newbie to the world of coding so any help would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Within the function, we use a while loop to keep prompting the user until they provide a valid input.

def get_valid_input():
    while True:
        user_input = input("Enter a single word with a maximum of 30 characters (no spaces): ")

        if user_input.isalpha() and len(user_input) <= 30:
            return user_input  # Return the input if it's valid (While will be promoting the user until the input is valid)
        else:
            print("Invalid input. Please try again.")

user_word = get_valid_input()
print(f"You entered: {user_word}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading