0

I want to write a program that uses a while loop to total up the even integers from 1 to 20. This is my code in 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

The errors I get are:

total_num(number)
and
total = total + number
UnboundLocalError: local variable 'total' referenced before assignment
MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46
yoyo
  • 25
  • 5
  • 1
    Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – sushanth May 25 '20 at 10:59

2 Answers2

0

total is declared outside of function therefore it is a global variable, to call it you need to declare it as 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)
ExplodingGayFish
  • 2,807
  • 1
  • 5
  • 14
0

just initialize total value (total = 0) inside the function. when you initialize total variable inside the function foo it will work fine and you wont need to use 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)
marksman123
  • 389
  • 2
  • 11