簡體   English   中英

如何使用def中的變量? 在Python中

[英]How to use variable from def? in Python

我有以下代碼,並且要使用一個界面制作動畫,其中一塊牆的坐標發生變化(從0,0到0,1等),當您按向左箭頭鍵時,幀速率會降低,而當按下右鍵,幀速率增加。 進一步,按g時牆應變成蛇形。

但是,我不明白如何在for循環中使用應該來自def的變量。

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

首先,在Process_event()修復縮進,使其始終返回一個值:

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

接下來,當您調用Process_event(event) ,請確保獲取其返回值:

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

在函數內部創建的任何變量只能在該函數中使用。 但是,就目前看來,您的函數正在返回變量,這基本上就是該函數的值。 所以:

def timestwo(x):
    print x*2

print timestwo(4)

這將返回8,因為我正在打印帶有參數4的功能timestwo,因此返回值將為8,因此將timestwo(4)設置為8。

您不能從函數中獲取變量,它是該函數的局部變量。 但是,您可以使用global關鍵字將變量全局轉換為INTO函數。 例:

numberone = 12

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM