0
import ui
from time import *
start = int(time())
def stop_time(sender):
    finish = int(time())
    total_time = int(finish - start)
    button1 = str("Your time is %i seconds." % (total_time))
    sender.title = None
    sender.title = str(button1)

How do I allow the restart button to change the start variable?

def restart_time(sender):
    start = int(time())
    button2 = str("Stopwatch restarted.")
    sender.title = None
    sender.title = str(button2)
ui.load_view('stop_time').present('sheet')
Luke Taylor
  • 8,631
  • 8
  • 54
  • 92
SleepyViking
  • 59
  • 12

1 Answers1

1

By default, when you assign to an identifier for the first time in a function it creates a local variable, even if there's a global one with the same name. Try this:

def restart_time(sender):
    global start
    start = int(time())
    button2 = str("Stopwatch restarted.")
    sender.title = None
    sender.title = str(button2)

From the relevant entry in the Python FAQ:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.

rakslice
  • 8,742
  • 4
  • 53
  • 57