如何确保仅在代码(python)中得到特定的输出?

问题描述 投票:0回答:1

我正在编写一个包含登录子例程的代码,它的工作原理很好,除了当我只想要其中一个输出时它提供两个输出。子例程如下:

def Login():

    chances = 0 
    Status = True #Status refers to whether the person is logged in or not

    while Status is True:
        Supplied_Username = input('What is your username?')
        Supplied_Password = input('What is your password?')
        with open("Loginfile.txt","r") as Login_Finder:
            for x in range(0,100):

                for line in Login_Finder:

                    if (Supplied_Username + ',' + Supplied_Password) == line.strip():  
                        print("You are logged in")
                        game()
            else:
                print("Sorry, this username or password does not exist please try again")
                chances = chances + 1
                if chances == 3:
                    print("----------------------------------------------------\n Wait 15 Seconds")
                    time.sleep(15)
                    Login()
                    sys.exit()

def game():
    print('HI')

就像我上面说的那样很好。当用户输入正确的详细信息时,他们将同时获得:

'您已登录'输出和'抱歉...这些详细信息不存在'输出

我需要做些什么来确保我在每种情况下都得到正确的输出(错误的信息和正确的信息)?

python for-loop if-statement while-loop output
1个回答
0
投票

我对您的代码进行了一些更改,使功能保持不变,仅显示了一些python最佳实践。

((请注意,在python中,大写的名称是按惯例为类名保留的,蛇形用于变量和函数的名称)。

def login(remaining_chances=3, delay=15):
    '''Requests username and password and starts game if they are in "Loginfile.txt"'''

    username = input('What is your username?')
    password = input('What is your password?')

    with open("Loginfile.txt","r") as login_finder:
        for line in login_finder.readlines():
            if line.strip() == f'{Supplied_Username},{Supplied_Password}':
                print("You are logged in")
                game()

    print("Sorry, this username or password does not exist please try again")

    remaining_chances -= 1

    if remaining_chances == 0:
        print(f"----------------------------------------------------\n Wait {delay} Seconds")
        time.sleep(delay)
        login(delay=delay)
    else:
        login(remaining_chances=remaining_chances, delay=delay)

但是,这不能解决您的问题。

问题是您没有退出此功能。在python中,函数应在完成时显示return值,但是在这里,您要么开始游戏,要么抛出异常。在许多方面,此函数从不打算具有返回值。

也许您想return game()。这将退出函数并调用game()

© www.soinside.com 2019 - 2024. All rights reserved.