π Python Crash Course – Chapter 5: if Statements – Exercise 5-9 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
π Exercise 5-9
Task:
create a list of users .make sure the list of users is
not empty .
• If the list is empty, print the message We need to find some users!
• Remove all of the usernames from your list, and make sure the correct
message is printed
✅ Solution Code:
users = ["Tony","Hulk","Bruce","admin","Natasha"]
#users = [] #empty user list
if len(users) == 0:
print(" We need to find some users!")
else:
for user in users :
print(f'Hello {user}')
π§ Code Explanation:
This Python code demonstrates how to handle a list of users and check whether the list is empty or contains usernames. Here's how it works:
-
Create a list of users:
The variable
users
is assigned a list containing usernames:["Tony", "Hulk", "Bruce", "admin", "Natasha"]
. Alternatively, the list can be set to empty by uncommentingusers = []
. -
Check if the list is empty:
An
if
statement checks whether the length of theusers
list is 0 using thelen()
function. If the list is empty, a message is displayed indicating that new users need to be found. -
Iterate through the list:
If the list is not empty, the
else
block is executed. Afor
loop iterates through each username in theusers
list, and a personalized greeting is displayed for each user.
This code demonstrates how to check for an empty list and handle its contents dynamically using conditional logic and loops.
π Output:
Hello Tony
Hello Hulk
Hello Bruce
Hello admin
Hello Natasha
π 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