如何解决 Python 错误“NameError: name 'X' is not defined”

时间:2021-01-09 10:06:26

标签: python python-3.x

这是错误:

Traceback (most recent call last):
File "test.py", line 27, in <module>
      id_check(id,gender)
NameError: name 'gender' is not defined

这是我的简单代码:

#!/bin/python3 
def clear_line():
    print("\n")

def id_check(id,gender):
                    
    id = input(" Do you have an id? : ")    


    if (id == "yes" ) or (id == "Yes") or (id == "y"):
        
        id = True   
    
    elif (id == "no" ) or (id == "No") or (id == "n"):
        
        print ("I need your id")
                
    else:
        print ("Please respound with yes or no "), 
        clear_line()
        id_check(id)

    gender = input(" What is you gender ? ")
    print (gender)

id_check(id,gender) 

1 个答案:

答案 0 :(得分:3)

问题在于,在您的函数中,您要求用户添加一个将作为性别的变量。但是,您提供的变量性别未定义。因此,它会引发错误。

要修复它,请从函数中删除参数,如下所示:

def clear_line():
    print("\n")

def id_check():
                    
    id = input(" Do you have an id? : ")    


    if (id == "yes" ) or (id == "Yes") or (id == "y"):
        
        id = True   
    
    elif (id == "no" ) or (id == "No") or (id == "n"):
        
        print ("I need your id")
                
    else:
        print ("Please respound with yes or no "), 
        clear_line()
        id_check(id)

    gender = input(" What is you gender ? ")
    print (gender)

id_check()