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