A
A
asb-kapusta2020-07-09 21:03:25
Python
asb-kapusta, 2020-07-09 21:03:25

Why is the error "local variable 'seconds' referenced before assignment" thrown?

There is a code:

import time

print("Запустить таймер?")
a = input(">>> ")

seconds = 0
minutes = 0
hours = 0

print(seconds)

def timer():
  if a == "да":
    time.sleep(1)

    if seconds == 60:
      if minutes == 60:
        hours = hours + 1
        print(hours + ": " + minutes + ": " + seconds)
        timer()
      else:
        minutes = minutes + 1
        print(hours + ": " + minutes + ": " + seconds)
        timer()
    else:
      seconds = seconds + 1
      print(hours + ": " + minutes + ": " + seconds)
      timer()
timer()

Throws an error: Traceback (most recent call last):
File "clock.py", line 29, in
timer()
File "clock.py", line 16, in timer
if seconds == 1:
UnboundLocalError: local variable 'seconds' referenced before assignment
After a little googling, I found out that this error means "the variable is not assigned yet", but I have it assigned (seconds = 0). Where is the mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2020-07-09
@asb-kapusta

Because seconds hours and minutes are defined outside of the function. Inside a function, external variables are not available. To work, they need to be passed to the function in a similar way. Do not listen to advice about global - this is bad practice

import time

print("Запустить таймер?")
a = input(">>> ")

seconds = 0
minutes = 0
hours = 0

print(seconds)

def timer(seconds, minutes, hours):
  if a == "да":
    time.sleep(1)

    if seconds == 60:
      if minutes == 60:
        hours = hours + 1
        print(hours + ": " + minutes + ": " + seconds)
        timer()
      else:
        minutes = minutes + 1
        print(hours + ": " + minutes + ": " + seconds)
        timer()
    else:
      seconds = seconds + 1
      print(hours + ": " + minutes + ": " + seconds)
      timer()

timer(seconds, minutes, hours)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question