Home > OS >  Why does my program keep repeating the else loop?
Why does my program keep repeating the else loop?

Time:12-10

Else loop repeating although conditions are met.

import time

def main():
    print("Welcome to the teaching system")
    login()

def login():
    input("What is your password?")
    if input == "1234":
        print("Login successfull...")
    else:
        print("Try again")
        time.sleep(3)
        main()

main()

if you input the correct password '1234' it skips and enters the else loop. Tried using Quotation marks (''), Speech marks ("") and nothing has changed. Is anything wrong with my code?

CodePudding user response:

You should save the input in a variable and use that when comparing to your string like this for example:

import time

def main():
    print("Welcome to the teaching system")
    login()

def login():
    password = input("What is your password?")
    if password == "1234":
        print("Login successfull...")
    else:
        print("Try again")
        time.sleep(3)
        main()

main()

CodePudding user response:

input is a function that returns a string from standard input. You need to save that value, rather than assume that the name of the function can be used as a variable holding the last string typed. (input is a variable, but it's value is the function itself, not the last return value of the function.)

And don't use (mutual) recursion to implement a loop.

def login():
    while True:
        passwd = input("What is your password?")
        if passwd == "1234":
            print("Login successfull...")
            break
        print("Try again")
        time.sleep(3)

 

CodePudding user response:

You can move your input prompt into if statement:

import time

def main():
    print("Welcome to the teaching system")
    login()

def login():
    if input("What is your password?") == "1234":
        print("Login successfull...")
    else:
        print("Try again")
        time.sleep(3)
        main()

main()

CodePudding user response:

Here is my solution:

import time


def main():
    print("Welcome to the teaching system")


def login():
    if password != '1234':
        print('Try again')
        time.sleep(3)
    else:
        print("Login successfull...")

main()
password = input("What is your password?")
login()
while password != '1234':      
    main()
    password = input("What is your password?")
    login()

The loop that plays if you guessed the wrong password plays outside the function until the guess is correct. Hope I helped!

  • Related