Project Level 1: Beginner
This project is designed for beginner learners who are still learning and practicing Python fundamentals.
Project Description
This program creates a function that checks whether a username is valid based on some simple rules. The function will take a username as input and return whether it is valid or not. The rules for a valid username are:
The username must be between 5 and 15 characters.
It must contain only alphanumeric characters (letters and numbers).
It must start with a letter.
How the Project Works
Define a function calledÂ
check_username_validity
 that takes a string (the username) as an argument.Inside the function, write conditions to check:
If the length of the username is between 5 and 15 characters.
If the username contains only alphanumeric characters using Python's built-inÂ
isalnum()
 method.If the first character of the username is a letter usingÂ
isalpha()
.
If all conditions are met, return "Valid username." Otherwise, return a message indicating why the username is invalid.
Here is how the program behaves when it is called with a valid username:
Here is how the program behaves when it is called with a non-valid username:
Prerequisites
Required Libraries: None
Required Files: No files are required.
IDE: You can use any IDE on your computer to code the project.
Danger Zone
Reveal the hints below:
Once you code the project, compare it with our solutions below.
#VALID USERNAME
def is_valid_username(username):
return (5 <= len(username) <= 15 and username[0].isalpha() and username.isalnum())
while True:
print('5 to 15 characteres and must start with a letter')
prompt = input('Type your username here (or type "exit" to quit): ')
if prompt.lower() == "exit":
print("Exiting...")
break
if is_valid_username(prompt):
print('Valid username')
break
else:
print('Username invalid. Please try again.')
username = input('Write here your name: ')
def check_username_validity(username):
characters = len(username)
key_num = username.isalnum()
key_alpha = username[0].isalpha()
if (characters > 15) or (characters < 5):
print('Your username is invalid because it doesnt have the exact numbers right!')
elif key_num is not True:
print('Your username does not contain only alphanumerics.')
elif key_alpha is not True:
print('The first character of the username must be a letter.')
else:
print('Valid username')
check_username_validity(username)