【问题标题】:What should be my arguments in my function and what should i return我的函数中的参数应该是什么,我应该返回什么
【发布时间】:2019-09-18 23:36:59
【问题描述】:

我有一个关于 Python 的简单问题。编写一个程序,要求用户输入密码。

如果用户输入了正确的密码,程序应该告诉他们他们已经登录到系统。

否则,程序应该要求他们重新输入密码。用户应该只能尝试五次输入密码,然后程序应该告诉他们他们被踢出系统。

我已经解决了这个问题,但我不知道我的函数中是否需要参数。另一个问题是我应该在程序中返回什么。我把 return 0 但我不希望 0 出现在调试器中。

def code():
    global password
    password='123456'
    global total_guesses
    total_guesses=5
    while total_guesses<=5 and total_guesses>0:
        resposta=input('Digite password\n')
        if password==resposta:
            print('You have entered the system')
            break
        else:
            print('Wrong password you haver',total_guesses,'total_guesses')
            total_guesses-=1
    return 0
print(code())

【问题讨论】:

  • 您可以肯定地对密码和total_guesses进行参数化,并根据某些条件决定是否返回值! @Luismaia1994

标签: python-3.x return arguments


【解决方案1】:

你不需要任何参数......你也不需要返回任何东西,函数将在完成后退出。

【讨论】:

  • 但如果我不把 return 它说在调试器中没有
  • 这是个问题吗?
  • 它这样做是因为函数在完成时隐式返回None
【解决方案2】:

如果您希望用户控制它们,您可以将 passwordtotal_guesses 作为输入传递给函数。

如果您想返回某些东西也取决于您,如果密码正确,您可以返回True,否则返回False,如果您想根据这些值做出进一步的决定,例如,如果用户登录,打开用户界面,或者如果用户无法登录,关闭程序等。或者您可以不返回任何内容,用户登录/登录失败后取决于您的下一步

def code(password, total_guesses):

    #Flag to return if user logged in or not
    logged_in = False
    while total_guesses<=5 and total_guesses>0:
        resposta=input('Digite password\n')
        if password==resposta:
            print('You have entered the system')
            logged_in = True
            break
        else:
            print('Wrong password you haver',total_guesses,'total_guesses')
            total_guesses-=1

    #Return the flag        
    return logged_in

password='123456'
total_guesses=5

#Use password and total_guesses as inputs
print(code(password, total_guesses))

输出看起来像

Digite password
123456
You have entered the system
True

Digite password
1
Wrong password you haver 5 total_guesses
Digite password
2
Wrong password you haver 4 total_guesses
Digite password
3
Wrong password you haver 3 total_guesses
Digite password
4
Wrong password you haver 2 total_guesses
Digite password
5
Wrong password you haver 1 total_guesses
False

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 2012-12-04
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 2017-06-06
    • 2011-01-14
    • 1970-01-01
    相关资源
    最近更新 更多