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

 

📘 Python Crash Course – Chapter 5: if Statements – Exercise 5-10 Solution

Welcome to another solution from Python Crash Course by Eric Matthes.


📝 Exercise 5-10

Task:
Do the following to create a program that simulates how websites ensure that everyone has a unique username .
• Make a list of five or more usernames called current_users .
• Make another list of five usernames called new_users . Make sure one or two of the new usernames are also in the current_users list .
• Loop through the new_users list to see if each new username has already been used . If it has, print a message that the person will need to enter a new username . If a username has not been used, print a message saying that the username is available .
• Make sure your comparison is case insensitive . If 'John' has been used, 'JOHN' should not be accepted

✅ Solution Code:


current_users = ["tony","natasha","hulk","spider","panther"]
new_users = ["TonY","Hwakeye"]

for new_user in new_users:
    if new_user.lower() in current_users:
        print(f'Username {new_user} cannot be accepted')
    else:
        print(f'username : {new_user} accepted')

🧠 Code Explanation:

This Python code simulates how websites ensure that usernames are unique by comparing new usernames with existing ones. Here's how it works:

  1. Create a list of current users:

    The variable current_users is assigned a list of existing usernames: ["tony", "natasha", "hulk", "spider", "panther"]. These represent usernames that are already taken.

  2. Create a list of new users:

    The variable new_users is assigned a list of usernames that are being requested: ["TonY", "Hwakeye"]. Some of these usernames may already exist in the current_users list.

  3. Loop through new usernames:

    A for loop iterates through each username in the new_users list. The variable new_user takes on each value in the list, one at a time.

  4. Check for case-insensitive matches:

    The lower() method is used to convert both the new_user and the usernames in current_users to lowercase. This ensures that the comparison is case-insensitive (e.g., "TonY" matches "tony").

  5. Determine username availability:

    If the lowercase version of new_user is found in current_users, a message is displayed indicating that the username is already taken. Otherwise, a message is displayed indicating that the username is available.

This code demonstrates how to handle case-insensitive comparisons and ensure unique usernames using lists and loops in Python.

🔍 Output:


Username TonY cannot be accepted
username : Hwakeye accepted

📚 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