【问题标题】:How to make sure I get only specific outputs in my code (python)?如何确保在我的代码(python)中只获得特定的输出?
【发布时间】:2019-12-20 01:27:38
【问题描述】:

我正在编写一个涉及登录子例程的代码,它运行良好,除了当我只需要其中一个时它提供两个输出这一事实。子程序如下:

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

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

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

我需要做些什么来确保我得到每个场景的正确输出(错误的细节和正确的细节)?

【问题讨论】:

  • for x in range(0, 100): 循环的目的是什么?你永远不会使用x 做任何事情。
  • 如果循环正常结束而不是以break 停止,则执行循环的else: 块。所以当你找到你要找的东西时,你需要跳出循环。
  • Python 中的变量名通常不使用大写字母
  • @MadPhysicist 这个问题专门询问输出,而不是返回值。
  • 每次递归调用Login(),都会将chances设置为0,所以永远不会达到3。

标签: python for-loop if-statement while-loop output


【解决方案1】:

我对您的代码进行了一些更改,以保持功能不变,只是展示了一些 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'{username},{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()

【讨论】:

    猜你喜欢
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多