Python'忘记'变量?

时间:2015-03-28 01:34:48

标签: python-3.x

所以,我试图将变量写入一个单独的.txt文件,python说我的变量没有定义,即使它在程序中使用了相同的变量

我在哪里分配并使用变量operator_choice:

    operator_choice = input ("Ok Mate, now chose your function: multiplication, division, addition or subtraction!")        
    if operator_choice in times:
        while Question < 12:
            Mathmultiplication();
        break
    if operator_choice in division:
        while Question < 12:            
            Mathdivision();
        break
    if operator_choice in subtraction:
        while Question < 12:
            Mathsub();
        break
    if operator_choice in addition:
        while Question < 12:
            Mathadd();
        break  
    elif operator_choice not in total_difficulty:
        print ("\nNot an option, try again")

但是当我尝试将其写入.txt文件时:

Results.write (", " + operator_choice)

它给了我这个错误:

NameError: name 'operator_choice' is not defined

有人可以告诉我们发生了什么,为什么以及如何解决这个问题? 这不是一个函数,但它是一个while循环

完整代码是一个代表:

import random
#just some variables
times = {'*'}
divide = {'/'}
other = {'-','+'}
myName = input ("So user, whats your name?... ")
#Operator stuff
correct = 0
incorrect = 0     
Question = 0
#Defining The Math
def math():
    global Question
    global correct
    global incorrect
    Question = Question + 1
    print ("________________________________________________________________________________")
    print ("Ok Then, This is question:", Question)
    print (str(number) + operator_choice + str(second_number) , "= ?")
    answer = eval(str(number) + operator_choice + str(second_number))
    guess = input ()
    if guess == str (answer):
        print('Correct!')
        correct = correct + 1
    elif guess != str(answer):
        print("Sorry, but that's wrong!The answer was:", answer, "Onto the next question then!")
        incorrect = incorrect +1    
def division():
    global Question
    global correct
    global incorrect
    Question = Question + 1
    print ("________________________________________________________________________________")
    print ("Ok Then, This is question:", Question,)
    number = (random.randint (12,24) * level)
    second_number = (random.randint(2,12)* level)
    print (number,"/",second_number)
    answer = number//second_number
    guess = input ()
    if guess == str (answer):
        print('Correct!')
        correct = correct + 1
    elif guess != str(answer):
        print("Sorry, but that's wrong!The answer was:", answer, "Onto the next question then!")
        incorrect = incorrect +1
#Difficulty
four = {'Impossible','impossible','4'}
total_difficulty = {'1','2','3','4'}
while True:
    print ("Ok,; Choose a difficulty: 1 , 2, 3 or 4(Changing operators, Near impossible!)...")
    difficulty_choice = input ()
    if difficulty_choice not in total_difficulty:
        print ("Not an option, try again")
    else: break
level = int(difficulty_choice)
if difficulty_choice not in four:
    print ("________________________________________________________________________________")
    while True:
        operator_choice = input ("Ok Mate, now chose your function: \nmultiplication (input * )\ndivision (input / ) \naddition (input + ) \nsubtraction (input - )\n...")        
        if operator_choice in times:
            while Question < 12:
                number = (random.randint (2,6) * level)
                second_number = (random.randint (2,6) * level)
                math();
            break
        if operator_choice in divide:
            while Question < 12:            
                division();
            break
        if operator_choice in other:
            while Question < 12:
                number = (random.randint (1,25) * level)
                second_number = (random.randint (1,25) * level)
                math();
            break  
        elif operator_choice not in total_difficulty:
            print ("\nNot an option, try again")
#Randomised operators
elif difficulty_choice in four:
    print ("you have chosen: Random. Be warned, These questions are HARD, and the operator WILL change!")
    Question = 0
    while Question < 12:
        Question = Question + 1
        print ("________________________________________________________________________________")
        print ("Ok Then, This is question:", Question)
        ops = ['*', '/', '+', '-']
        op = random.choice (ops)
        number = random.randint (2,25)
        number2 = random.randint (2,25)
        number3 = eval(str(number) + op + str(number2))
        number3 = int(number3)
        answer = eval(str(number3) + op + str(number))
        answer = int (answer)
        print (number3, op, number)
        guess = input()
        if guess == str (answer):
            print('Correct!')
            correct = correct + 1
       elif guess != str(answer):
            print("Sorry, but that's wrong!The answer was:", answer, "Onto the next question then!")
            incorrect = incorrect +1
#Outros
print ("________________________________________________________________________________")     
print ("Game Over!", myName," got:", correct,"questions right, and",incorrect,"Wrong!")
if correct == 12:
print ("Congratz",myName,"! You got a perfect score! See ya around",myName,"!")
else: print ("good luck next time! Bye!")
#save results
correct = str(correct)
incorrect = str(incorrect)
Results = open (r"Results.txt", 'a')
Results.write ("\nHello There Teacher! " + myName + " got: " + correct + "correct, and: " + incorrect + " wrong on level: " + difficulty_choice + ", ")
Results.write (operator_choice)
Results.close()

1 个答案:

答案 0 :(得分:0)

在发布完整代码之前,您无法获得完整的答案。但是,我可以给你一个可能的(可能)解决方案:

您上面发布的代码位于单独的函数中,因此operator_choice的范围仅在该函数中定义。确保在函数中返回变量,或在该函数中调用Results.write

示例:

>>> def foo(): 
...    bar = 1 
...
>>> bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
>>> foo()
>>> bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined