python 为什么我的程序不断重复else循环?

iugsix8n  于 2022-12-10  发布在  Python
关注(0)|答案(4)|浏览(168)

尽管满足条件,否则循环重复。

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()

如果你输入了正确的密码“1234”,它会跳过并进入else循环。2尝试使用引号(''),语音符号(“”),没有任何变化。3我的代码有什么问题吗?

bis0qfac

bis0qfac1#

您应该将输入保存在变量中,并在与字符串进行比较时使用该变量,例如:

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()
r3i60tvu

r3i60tvu2#

input是一个从标准输入中 * 返回 * 字符串的函数。您需要保存该值,而不是假设函数的名称可以用作保存最后键入的字符串的变量。(input * 是 * 一个变量,但它的值是函数本身,而不是函数的最后返回值。)
不要使用(相互)递归来实现循环。

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

ac1kyiln3#

您可以将输入提示移到if语句中:

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()
xkftehaa

xkftehaa4#

下面是我的解决方案:

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()

如果你猜错了密码,循环会在函数之外播放,直到猜对为止。希望我能帮上忙!

相关问题