使用函数时出现Python代码错误

2024-10-04 05:27:42 发布

您现在位置: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
>>> 

这个错误是什么意思?我如何修复它?
请帮我解决这个问题。你知道吗


Tags: andthenoyouonlyinputifcode
3条回答

你应该换这条线

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

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

正如目前所写的,这个表达并不意味着你认为它是什么。如果我加上括号来强调,你的表达式实际上是

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

子表达式"yes".lower()始终产生True。你知道吗

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

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

这将改变用户输入的任何小写字母,并且代码的res可以用小写字母编写,而不需要.lower()函数。你知道吗

考虑到你的代码片段的boken缩进很难确定,但这里:

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

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

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

相关问题 更多 >