改变程序内部的变量

时间:2014-03-15 19:55:43

标签: python variables procedures

我在Start()过程中创建了一个变量,但它似乎没有记住过程之外的变量。有没有办法让python记住Start()过程之外的变量?我的代码如下:

def Start():
    password = raw_input("Enter A Password With 7 Or More Characters: ")
    passwordLength = len(password)
    if passwordLength<7:
        print "Your entered a password with less than 7 characters. Enter a longer password."
        Start()
    else:
        reEnter = raw_input("Re-enter your password: ")
        if reEnter<>password:
        print "Your passwords did not match, please try again."
        Start()
        if reEnter==password:
        print "Your password has been saved."


Start()

print password
print passwordLength

3 个答案:

答案 0 :(得分:1)

您可以在函数结束时返回变量。

def Start():
    password = input("Enter A Password With 7 Or More Characters: ")
    passwordLength = len(password)
    if passwordLength<7:
        print("Your entered a password with less than 7 characters. Enter a longer password.")
        return Start()
    else:
        reEnter = input("Re-enter your password: ")
        if not reEnter == password:
            print("Your passwords did not match, please try again.")
            return Start()
        else:
            print("Your password has been saved.")
            return password, passwordLength

savedPass, passLength = Start()

print(savedPass)
print(passLength)
编辑:编辑样式(感谢@jrennie)和递归调用。 (感谢@bgporter)

答案 1 :(得分:1)

我在这里假设密码和密码长度是全局变量。为此,您可以使用global关键字,只需在Start()的开头定义它们,如下所示:

def Start():
    global password
    global passwordLength

    password = raw_input("Enter A Password With 7 Or More Characters: ")
    passwordLength = len(password)
    if passwordLength<7:
        print "Your entered a password with less than 7 characters. Enter a longer password."
        Start()
    else:
        reEnter = raw_input("Re-enter your password: ")
        if reEnter<>password:
            print "Your passwords did not match, please try again."
            Start()
        if reEnter==password:
            print "Your password has been saved."

然而,全局变量在python中经常被不满。如果可能的话尝试使用return来打印输出,但对于大多数情况来说,全局都很好。

答案 2 :(得分:0)

待办事项

def Start():
    global password
    global passwordLength
    ....