Что это значит под UnboundLocalError? (python) - PullRequest
0 голосов
/ 25 мая 2020

Я хочу написать программу, которая использует время l oop для суммирования четных целых чисел от 1 до 20. Это мой код в Python IDLE.

#Important Notes
#===============
#You MUST use the following variables
#   - total
#   - number

#START CODING FROM HERE
#======================

#Set number value
number = 2
total = 0
#Check closest object
def total_num(number):
    while number % 2 == 0 and number <=20:
        total = total + number
        number = number + 2

    print('The total is {}'.format(total)) #Modify to display the total
    return total #Do not remove this line

#Do not remove the next line
total_num(number)

#output 110

Я получаю следующие ошибки:

total_num(number)
and
total = total + number
UnboundLocalError: local variable 'total' referenced before assignment

Ответы [ 2 ]

0 голосов
/ 25 мая 2020

просто инициализируйте общее значение (total = 0) внутри функции. когда вы инициализируете общую переменную внутри функции foo, она будет работать нормально, и вам не нужно будет использовать global.

#Set number value
number = 2
#Check closest object
def total_num(number):
    total = 0 #declare total variable here instead.
    while number % 2 == 0 and number <=20:
        total = total + number
        number = number + 2

    print('The total is {}'.format(total)) #Modify to display the total
    return total #Do not remove this line

#Do not remove the next line
total_num(number)
0 голосов
/ 25 мая 2020

total объявлен вне функции, поэтому это переменная global, чтобы вызвать ее, вам нужно объявить ее как global first

number = 2
total = 0
#Check closest object
def total_num(number):
    global total #<<----- here
    while number % 2 == 0 and number <=20:
        total = total + number
        number = number + 2

    print('The total is {}'.format(total)) #Modify to display the total
    return total #Do not remove this line

#Do not remove the next line
total_num(number)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...