variable not defined in python

2020-05-10 04:06发布

Hi I'm very new with programming in python. I'm starting my first program but i'm having a little trouble.. is there a better way of doing the snippet of code below? When i run the program I get "yes_no" not defined.

def main():
    print "\n Welcome to registration. Are you an authorized user?\n"
    yes_no = raw_input("Yes or No?: ")
    if yes_no in ("Yes", "yes"):
        return oldUser()
    elif yes_no in ("y", "Y"):
        print ("Please enter YES")
        return wrong()
    elif yes_no in ("n", "N"):
        return wrong()
    else:
        print ("\n Unauthorized text!\n")
        return main()

def wrong():
    if yes_no in ("y", "Y"):
        print ("Please Enter Yes!")
        return main()
    else:
        yes_no in ("n", "N")
        print ("Please Enter No!")
        return main()

3条回答
够拽才男人
2楼-- · 2020-05-10 04:20

yes_no is not defined in wrong() method, so it is only visible in main(). You can pass yes_not into wrong() like wrong(yes_no)

查看更多
啃猪蹄的小仙女
3楼-- · 2020-05-10 04:24

You defined a variable called yes_no in the function main, and that's the only place it exists.

Now, you could pass it into wrong as an argument:

def main():
    yes_no = ...
    wrong(yes_no)

def wrong(yes_no):
    # your existing code will work here now
    ...

but this ignores the problem that your main/wrong functions are mutually recursive, which in this case is a poor fit for what you're trying to do.

It'd be nicer here to unroll the recursion into a loop:

def main():
    print "\n Welcome to registration. Are you an authorized user?\n"
    while True:
        yes_no = raw_input("Yes or No?: ")
        if yes_no in ("Yes", "yes"):
            return oldUser()
        elif yes_no in ("y", "Y"):
            print ("Please enter 'Yes'")
            # return wrong() ## just loop round again
        elif yes_no in ("n", "N"):
            print ("Please Enter 'No'")
            # return wrong() ## just loop round again
        else:
            print ("\n Unauthorized text!\n")

NB that you may ask the user to enter "No", but never handle that as valid input.

查看更多
萌系小妹纸
4楼-- · 2020-05-10 04:25

yes_no is defined in main(); code in wrong() cannot see it (wrong scope).

Also, you have main() call wrong() which calls main() in an infinite loop.

You probably want something more like

def is_yes(s):
    return s.strip().lower() in ('y', 'yes')

def is_no(s):
    return s.strip().lower() in ('n', 'no')

def existing_user():
    # ok, they are signed in; now what?
    pass

def sign_up():
    # what can I sell you today?
    pass

def main():
    print('Welcome to registration.')
    while True:
        inp = raw_input('Are you an authorized user? ')
        if is_yes(inp):
            return existing_user()
        elif is_no(inp):
            return sign_up()

if __name__=="__main__":
    main()
查看更多
登录 后发表回答