使用函数时Python代码错误

时间:2015-12-02 12:21:28

标签: python

我有这个代码,我希望它能够多次询问问题,直到给出是或否答案

def teacheraskno():
teacher = input("Are you a teacher? yes and no answers only! > ")
if teacher == "no" or "yes".lower():
    if teacher == "no".lower():
        start()
    if teacher == "yes".lower():
        teacheraskyes()
else:
    print ("Please enter yes and no answers only!")
    teacheraskno()

def teacheraskyes():
if teacher == "yes".lower(): 
    password = input("What is the Password? > ")
if password =="123".lower(): 
    print ("ACCESS GRANTED!")
    classname = input("what class would you like to view? 1, 2 or 3 > ")

    f = open(classname + ".txt", 'r') #opens the class file
    file_contents = f.read()
    print (file_contents)
    f.close()


teacher = input("Are you a teacher? yes and no answers only! > ")
if teacher == "no" or "yes".lower():
    if teacher == "no".lower():
        start()
    if teacher == "yes".lower():
        teacheraskyes()
    else:
        print ("Please enter yes and no answers only!")
        teacheraskno()

我一直收到此错误

==============================Math Revision Quiz================================
Are you a teacher? yes and no answers only! > bla
Please enter yes and no answers only!
Are you a teacher? yes and no answers only! > yes
Traceback (most recent call last):
  File "S:\My Documents\Ben Atia CA A453\Python Code\Python Code 1.py", line 142, in <module>
    teacheraskno()
  File "S:\My Documents\Ben Atia CA A453\Python Code\Python Code 1.py", line 118, in teacheraskno
    teacheraskyes()
  File "S:\My Documents\Ben Atia CA A453\Python Code\Python Code 1.py", line 125, in teacheraskyes
    if password =="123".lower(): #if the password is correct it will let the teacher view the code
UnboundLocalError: local variable 'password' referenced before assignment
>>> 

这个错误意味着什么,我该如何解决? 请帮我解决这个问题。

3 个答案:

答案 0 :(得分:2)

你应该改变这一行

if teacher == "no" or "yes".lower():

if teacher.lower() not in ("no", "yes"):

正如目前所写,表达并不意味着你的想法。如果我添加括号用于强调,则表达式实际上显示为

if (teacher == "no") or ("yes".lower()):

子表达式"yes".lower()始终收益True

答案 1 :(得分:0)

鉴于你的片段缩写,很难确定,但是在这里:

if teacher == "yes".lower(): 
    password = input("What is the Password? > ")
if password =="123".lower(): 
    print ("ACCESS GRANTED!")

您只在第一个password分支中定义if变量,但在两种情况下都尝试阅读它。因此,如果teacher不等于&#34;是&#34;,则password未定义。

您的代码存在许多其他问题,但这不在您的问题范围内。

答案 2 :(得分:0)

而不是.lower,您可以在str.casefold()之前使用input()。这将使用户进入小写的任何内容。这不仅是一种验证,而且它允许您以小写形式编写所有代码。例如:

teacher = str.casefold(input("Are you a teacher?"))

这应该改变用户输入小写的任何内容,并且代码的res可以用小写字母写成,而不需要.lower()函数。