Python Forum

Full Version: Help with for-loop printing. I want it to print only once.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi I'm new to python and I'm currently working on a python login programm for school. this is what I have so far:
The thing is when I intentionally type in a password or username wrong, I want the programm to type out username or password invalid. However it prints it out twice or thrice. This is because of the for loop that is going through my list and checking if the object's name or password are correct. If it's not it'll print out invalid etc. It does this twice or thrice. My question is: How can I make my programm type username or password invalid once? (btw I'm new to python, so go easy on me)
Thanks!
# making a login system.

#ask account prompt/function.
ask_account = input("Do you have an account? ")

#class to create new users
class users:
    def __init__(self, username, password):
        self.username = username
        self.password = password

# This is the user list.
user_list = [
users("Se", "ben0"),
users("Soar", "ben7")
]

# continuing function to access your account
if ask_account == "yes":
    username_ = input("What is your username: ")
    password = input("What is your password: ")
    for element in user_list:
        if username_ == element.username and password == element.password:
            print("Welcome {}".format(element.username) +"." + "You are logged in!")
        if username_ != element.username or password != element.password:
            print("Invalid username or password!")

# continuing function to create a new account and access your new account
if ask_account == "no":
    user_list.append(users(input("insert username: "), input("insert password ")))
    print("You have created a new account!")
    username_ = input("What is your username: ")
    password = input("What is your password: ")
    for x in user_list:
        if username_ == x.username and password == x.password:
            print("Welcome {}".format(x.username) +"." + "You are logged in!")
        if username_ != x.username or password != x.password:
            print("Invalid username or password!")
You can use break to exit your for loops once a condition you are testing for is satisfied. You can read about the break statement in the Python documentation here.
Note: Don't use 2 if statements - you change the second one to an elif statement