Contoh Python Scope
# The code will not work
def f(x,y):
    print('you called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
    print('x + y = ' + str(x*y))
    z = 4 # z is lokal
z = 3
f(3,2)
# Function scope make code can be used
def f(x,y):
    g=3
    print('you called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
    print('x + y = ' + str(x + y)) # x + y, not x * y
    print(g)
f(3,2)
Output: 
you called f(x,y) with the value x = 3 and y = 2
x + y = 5
3
>>> 
Another example:
def f(x,y,z):
    return x+y+y
result = f(3,2,3)
print(result)
Output: 7 ....> because: x + y + y = 3+2+2 = 7
Nested functions and variabel scope
def highFive():
    return 5
def f(x,y):
    g = highFive()
    return x+y+g
result = f(3,2)
print (result)
Output= 10
# Posting sebelumnya:
No comments:
Post a Comment