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

 

📘 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:

  1. 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".

  2. Iterate through the list:

    A for loop is used to iterate through each username in the usernames list. The variable username takes on each value in the list, one at a time.

  3. Check for the special username:

    An if statement checks whether the current username is "admin". If the condition is true, a special greeting is displayed for the admin user.

  4. Provide a generic greeting:

    If the username is not "admin", the else 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:


🔗 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

Previous Post Next Post

Contact Form