简体   繁体   中英

How to use variable from def? in Python

I have the following code and the assingment is to make an animation using the interface where a piece of wall changes of coordinates (from 0,0 to 0,1 etc.) an when you press the left arrow key the frame rate decreases and when the right key is pressed the frame rate increases. Further the wall should change into a snake when pressing g.

However, I don't understand how i could use the variables that should come out of the def's in the for loop.

from ipy_lib import SnakeUserInterface
from ipy_lib import Event

ui=SnakeUserInterface(3,3)
SNAKE=2
WALL=3

def Process_event(event):

    if event.name == "arrow" :
        frames(event.data)
    if event.name == "g":
        color = SNAKE 
    else:
        color = WALL
        return color

def frames(data):

    frames_per_second=24
    if data=="l":
        frames_per_second-=0.5
    if data=="r":
        frames_per_second+=0.5
    return frames_per_second

for j in range(0,3):

    for i in range(0,3):
        event=ui.get_event()
        Process_event(event)
        ui.set_animation_speed(frames_per_second)
        ui.place(i, j,color)
        ui.show()
        ui.clear()

First, fix the indentation in Process_event() so it always returns a value:

def Process_event(event):

    if event.name == "arrow" :
        frames(event.data)
    if event.name == "g":
        color = SNAKE 
    else:
        color = WALL
    return color  # This line was indented too far

Next, when you call Process_event(event) , make sure you grab its return value:

for i in range(0,3):
    event=ui.get_event()
    color = Process_event(event)  # Grab the value here
    ui.set_animation_speed(frames_per_second)
    ui.place(i, j,color)
    ui.show()
    ui.clear()

Any variables created inside of a function can only be used in that function. However, as it looks right now, your functions are returning variables, and that is basically the value, so to speak, of the function. So:

def timestwo(x):
    print x*2

print timestwo(4)

This would return 8 because I am printing the function timestwo with the argument 4, so the return value will be 8 and therefore sets timestwo(4) to 8.

You can't take a variable from a function, it's local to that function. However, you can take a variable globally INTO a function using the global keyword. Example:

numberone = 12

def print(i):
    global numberone
    return print(str(i))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM