Unable to reference one particular variable declared outside a function

tikker

I'm trying to animate a projectile motion path using Python. To achieve this I'm using matplotlib's animation module. My full script is below.

#!/usr/bin/env python

import math
import sys

import matplotlib.animation as anim
from matplotlib.pyplot import figure, show

# Gravitational acceleration in m/s/s
g = -9.81
# Starting velocity in m/s.
vel = 100
# Starting angle in radians.
ang = 45 * math.pi / 180
# Starting height in m.
y0 = 0
# Time settings.
t = 0
dt = 0.1
time = -vel**2 * math.sin(2 * ang) / g

def projectile():
    print g, vel, ang, y0, dt, time
    print t # Crashes here with UnboundLocalError: local variable 't' referenced before assignment
    t=0 # With this it works
    x = 0
    y = 0.1
    xc = []
    yc = []

    # Simulate the projectile.
    while t < time:
        x = vel * math.cos(ang) * t
        y = vel * math.sin(ang) * t + (g * t**2) / 2 + y0
        if y < 0:
            break
        t += dt
        xc.append(x)
        yc.append(y)
        yield x, y

def update_frame(sim):
    x, y = sim[0], sim[1]
    line.set_data(x, y)
    return line,

def init():
    line.set_data([], [])
    return line,

# Show the results.
fig = figure()
ax = fig.add_subplot(111)
ax.set_xlim([-5,1500])
ax.set_ylim([0,300])

# ax.plot returns a single-element tuple, hence the comma after line.
line, = ax.plot([], [], 'ro', ms=5)
ani = anim.FuncAnimation(fig=fig, func=update_frame, frames=projectile, blit=True, interval=20, init_func=init, repeat=False)
show()

The problem I have is that I seem to be able to use every variable, except t. I did it to create a stop condition so it would run only once and I later found out about repeat=False, but I'm still curious about this. Why can't I use t inside projectile? I am running Python 2.7.6 with Matplotlib 1.3.1 from the Anaconda 1.9.1 package.

dwitvliet

The problem arises because you try to reassign the global variable t.

The variables g, vel, ang, y0, dt, time you only access (without reassigning them), so python tries to access them both locally and then globally. However, when you reassign t with the line t += dt, you are really telling python to create a local variable with the identifier t and assign it the desired value. Therefore, the global identifier t cannot be accessed as you've told python that t is local, and when you try to access t before it is assigned, you the UnboundLocalError is raised.

To tell python to reassign t as a global variable, you simply need to add global t to the beginning of your function:

t = 0
(..)
def projectile():
    print g, vel, ang, y0, dt, time
    global t # now t can be edited as a global variable
    print t #works
    x = 0
    y = 0.1
    xc = []
    yc = []

    while t < time:
        (..)
        t += dt

EDIT:

As flebool pointed out, you can actually still change a global variable as long as you don't reassign the identifier for it. For example, the code below is valid:

>>> l = [1,2,3]
>>> def changelist():
...    l.append(4)
...
>>> changelist()
>>> l
[1,2,3,4]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Use a variable declared in a function outside that function

From Dev

Java reference variable declared outside method lives on stack or on heap

From Dev

Will a variable declared with cdef outside a function have the same type inside the function?

From Dev

When does a variable need to be declared outside a function in Javascript?

From Dev

Global variable declared outside function doesn't work

From Dev

What memory used for variable declared outside of a method or function

From Dev

How to Manipulate Variable Value inside a Function When The Variable was Declared Outside the Function?

From Dev

How is it possible to reference to a variable outside of a code block when it is declared inside a block?

From Dev

Why does a variable of a function declared outside its function definition doesn't throw an error?

From Dev

variable declared by auto sometimes is by reference?

From Dev

How to use JavaScript variable outside if-statement scope between two if-statements when it is declared in one of them?

From Dev

How to use JavaScript variable outside if-statement scope between two if-statements when it is declared in one of them?

From Dev

Unable to update global variable inside a function and call it outside it (jQuery)

From Dev

Bash array declared in a function is not available outside the function

From Dev

unable to store one function value in variable

From Dev

Cannot access variable declared outside of Switch Statement

From Dev

Swift: I am unable to pass back a variable from Firebase FIRAuth function to a declared variable from a parent funciton

From Dev

using variable outside of a function

From Dev

Use a variable outside function

From Dev

Checkbox variable outside of function

From Dev

Variable accessible outside the function

From Dev

reference a value outside of the request function

From Dev

Function reference lost outside loop

From Dev

call function on click outside of a particular div

From Dev

Function returning a variable without declared it

From Dev

Using variable/function before it is declared

From Dev

Function returning a variable without declared it

From Dev

function access variable declared in decorator

From Dev

variable or field (function) declared void

Related Related

  1. 1

    Use a variable declared in a function outside that function

  2. 2

    Java reference variable declared outside method lives on stack or on heap

  3. 3

    Will a variable declared with cdef outside a function have the same type inside the function?

  4. 4

    When does a variable need to be declared outside a function in Javascript?

  5. 5

    Global variable declared outside function doesn't work

  6. 6

    What memory used for variable declared outside of a method or function

  7. 7

    How to Manipulate Variable Value inside a Function When The Variable was Declared Outside the Function?

  8. 8

    How is it possible to reference to a variable outside of a code block when it is declared inside a block?

  9. 9

    Why does a variable of a function declared outside its function definition doesn't throw an error?

  10. 10

    variable declared by auto sometimes is by reference?

  11. 11

    How to use JavaScript variable outside if-statement scope between two if-statements when it is declared in one of them?

  12. 12

    How to use JavaScript variable outside if-statement scope between two if-statements when it is declared in one of them?

  13. 13

    Unable to update global variable inside a function and call it outside it (jQuery)

  14. 14

    Bash array declared in a function is not available outside the function

  15. 15

    unable to store one function value in variable

  16. 16

    Cannot access variable declared outside of Switch Statement

  17. 17

    Swift: I am unable to pass back a variable from Firebase FIRAuth function to a declared variable from a parent funciton

  18. 18

    using variable outside of a function

  19. 19

    Use a variable outside function

  20. 20

    Checkbox variable outside of function

  21. 21

    Variable accessible outside the function

  22. 22

    reference a value outside of the request function

  23. 23

    Function reference lost outside loop

  24. 24

    call function on click outside of a particular div

  25. 25

    Function returning a variable without declared it

  26. 26

    Using variable/function before it is declared

  27. 27

    Function returning a variable without declared it

  28. 28

    function access variable declared in decorator

  29. 29

    variable or field (function) declared void

HotTag

Archive