2017-03-31 78 views
0

试图让下面的代码正常工作,但它仍然返回变量未定义,当用户输入整数来尝试和分配性别时。你会如何解决这个问题?程序返回undefined变量(python)

#define the function for the physical characteristics question 
def physical_characteristics_question (question, answer1, answer2, answer3) : 
    print (question) 
    print ('1. ' + answer1) 
    print ('2. ' + answer2) 
    print ('3. ' + answer3) 

    while True: 
     variable = (input('Please enter a number: ')) 
     while True: 
     #repeats question if a type other than integer is entered 
      try: 
       int(variable) 
       break 
      except ValueError: 
       variable = 0 
       continue 

     #repeats question if a number out of range is entered 
     if int(variable) >= 1 and int(variable) <= 3: 
      break 

    return int(variable) 


physical_characteristics_question ("What is your gender?", 'male', 'female', 'other') 

if (variable) == 1: 
    gender = 'male' 
elif (variable) == 2: 
    gender = 'female' 
else: 
    gender = 'other' 

非常感谢!

+0

您没有将返回值分配给任何东西;做'variable = physical_characteristics_question(“你的性别?”,...)'。您在功能中分配的变量仅在该功能中可用。 – Ryan

+0

固定,非常感谢! –

回答

0

您的功能physical_characteriscs_question未将其结果返回给任何变量。尝试这样做:

variable = physical_characteristics_question ("What is your gender?", 'male', 'female', 'other')