Search code examples
pythoniphoneuser-interfaceglobal-variablespythonista

I cannot get the restart button to work on my stopwatch. Using Pythonista on iPhone


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')

Solution

  • 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’.