// Functions
RETURN Mini Project — Username Generator
The problem...
Your Username Generator function calculates and prints — all in one place. That works. But what if you want to use the username somewhere else? Store it. Pass it to another function. Print it differently.
Right now you can't. The value never leaves the function.
The idea!
Return the username instead of printing it. Once it's returned — it's free. Use it however you want.
The solution
def generate_username(name, year, prefix="rhd_"):
return prefix + name.replace(" ", "").lower() + year[-2:]
def print_username(username):
print(f"Your username is: {username}")
username = generate_username("Bull", "2001")
print(username) # rhd_bull01
print(f"Your username is: {username}") # Your username is: rhd_bull01
print_username(username) # Your username is: rhd_bull01
Test it
# rhd_bull01
# Your username is: rhd_bull01
# Your username is: rhd_bull01
What's really happening
generate_username() builds the username and returns it. The returned value is stored in username. From there — three different ways to use the same value. Same result, different approaches. The value is free.
Go further
- Pass the returned value directly —
print_username(generate_username("Bull", "2001")) - Generate two usernames and print both
- Add a
validate_username()function — check if it's longer than 5 characters
What you should understand now
returnfrees the value — store it, print it, pass it — your choice- The same returned value can be used in multiple ways
- Returned values connect functions — output of one becomes input of another
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment