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.
>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}")