Search code examples
python-3.x

Python loop on list


I'm new in Python.

Hello Admin:

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 logging in again.

Code:

u = input('Enter Username: ').title()

for user in usernames:
    if u in user == 'Admin':
        print('Welcom admin')
        if u in user:
            print('In list')
    else:
        print('Not in list')

Solution

  • As per the question, you are looking for an answer

    Create a list user_names(based on PEP 8 naming convention) and loop through them

    user_names = ['eric', 'willie', 'admin', 'erin', 'ever']
    
    for user in user_names:
        if user == 'admin':
            print("Hello admin, would you like to see a status report?")
        else:
            print("Hello " + user + ", thank you for logging in again!")
    

    To see an answer as below

    Hello eric, thank you for logging in again!
    Hello willie, thank you for logging in again!
    Hello admin, would you like to see a status report?
    Hello erin, thank you for logging in again!
    Hello ever, thank you for logging in again!
    

    If you want to just ask for a name as input and print the output based on the provided input here's the code

    user = input('Enter Username: ').lower()
    
    if user == 'admin':
        print(f'Hello {user}, would you like to see a status report?')
    else:
        print(f'Hello {user.title()}, thank you for logging in again.')
    

    With a predefined list where you will be checking the user in the user_name list, here's the answer

    user = input('Enter Username: ').lower()
    
    user_names = ["eric", "admin", "lever", "matt"]
    
    if user in user_names:
        if user == 'admin':
            print(f'Hello {user}, would you like to see a status report?')
        else: 
            print(f'Hello {user.title()}, thank you for logging in again.')
    
    else:
        print('Not in list')
    

    Output:

    enter image description here