Exercise 5-9 Solution Python Crash Course Chapter 5: if Statements

 

πŸ“˜ 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:

  1. 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 uncommenting users = [].

  2. Check if the list is empty:

    An if statement checks whether the length of the users list is 0 using the len() function. If the list is empty, a message is displayed indicating that new users need to be found.

  3. Iterate through the list:

    If the list is not empty, the else block is executed. A for loop iterates through each username in the users 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:


πŸ”— 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

“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