繁体   English   中英

使用函数时发生Python代码错误

[英]Python code error while using functions

我有此代码,我希望它根据需要多次询问该问题,直到给出是或否的答案为止

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

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

您应该更改此行

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

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

就目前而言,该表达式并不表示您认为的含义。 如果我加括号以强调,您的表达实际上为

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

子表达式"yes".lower()始终产生True

鉴于您的摘要的缩进,很难确定,但是在这里:

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

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

您的代码还有很多其他问题,但这超出了您的问题范围。

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

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

这应该更改用户输入的所有小写字母,而没有.lower()函数的情况下,代码的结果可以用小写字母编写。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM