π Python Crash Course – Chapter 5: if Statements – Exercise 5-8 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
π Exercise 5-8
Task:
Make a list of five or more usernames, including the name
'admin' . Imagine you are writing code that will print a greeting to each user
after they log in to a website . Loop through the list, and print a greeting to
each user:
• If the username is 'admin', print a special greeting, such as Hello admin,
would you like to see a status report?
• Otherwise, print a generic greeting, such as Hello Eric, thank you for log
ging in again.
✅ Solution Code:
usernames = ["Tony","Hulk","Bruce","admin","Natasha"]
for username in usernames:
if username == "admin":
print("Hello Admin.. Do you want to see the status report")
else:
print(f"Hello {username} Thanks For Login")
π§ Code Explanation:
This Python code demonstrates how to use a for
loop and an if-else
statement to provide personalized greetings based on usernames. Here's how it works:
-
Create a list of usernames:
The variable
usernames
is assigned a list containing five usernames:["Tony", "Hulk", "Bruce", "admin", "Natasha"]
. The list includes a special username,"admin"
. -
Iterate through the list:
A
for
loop is used to iterate through each username in theusernames
list. The variableusername
takes on each value in the list, one at a time. -
Check for the special username:
An
if
statement checks whether the currentusername
is"admin"
. If the condition is true, a special greeting is displayed for the admin user. -
Provide a generic greeting:
If the
username
is not"admin"
, theelse
block is executed, displaying a generic greeting for regular users.
This code demonstrates how to use conditional logic within a loop to provide customized output based on specific conditions.
π Output:
Hello Tony Thanks For Login
Hello Hulk Thanks For Login
Hello Bruce Thanks For Login
Hello Admin.. Do you want to see the status report
Hello Natasha Thanks For Login
π Related Exercises from Chapter 5:
- ➤ Exercise 5-1 | Conditional Tests
- ➤ Exercise 5-2 | More Conditional Tests
- ➤ Exercise 5-3 | Alien Colors #1
- ➤ Exercise 5-4 | Alien Colors #2
- ➤ Exercise 5-5 | Alien Colors #3
- ➤ Exercise 5-6 | Stages of Life
- ➤ Exercise 5-7 | Favorite Fruit
- ➤ Exercise 5-8 | Hello Admin
- ➤ Exercise 5-9 | No Users
- ➤ Exercise 5-10 | Checking Usernames|
- ➤ Exercise 5-11 | Ordinal Numbers
- ➤ Exercise 5-12 | Styling if statements
- ➤ Exercise 5-13 | Your Ideas
π Connect With Us:
“Programs must be written for people to read, and only incidentally for machines to execute.”
— Harold Abelson
π Tags: #Python #PythonCrashCourse #CodingForBeginners #LearnPython #PythonProjects #PythonTips
πTrending Topics
π Connect With Us:
“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python
π Follow Us And Stay Updated For Daily Updates
Comments
Post a Comment