Defining functions
Beginning Python Programming
Makzan, 2020 April.
Defining functions
- Functions usage
- Functions parameters
- Returning result
- lambda function
Code example
# Defining functions
def square(x):
return x*x
# Using the function
print( square(2) )
print( square(5) )
print( square(10) )
Take a deep look of function
# Defining functions
def square(x):
return x*x
1. "def" function
2. function name
3. parameters
4. colon (:)
5. indentation
6. return
7. result
Parameters example
def percent(x, y=100):
return x / y * 100
print( percent(3,10))
# 30.0
print( percent(1,3))
# 33.3333333333
print( round(percent(1,3), 2))
# 33.33
print( percent(y=10,x=2))
# 20.0
print( percent(30))
#30.0
def percent(x, y=100):
return x / y * 100
print( percent(3,10))
# 30.0
print( percent(1,3))
# 33.3333333333
print( round(percent(1,3), 2))
# 33.33
print( percent(y=10,x=2))
# 20.0
print( percent(30))
#30.0
Parameters example
def percent(x, y=100):
return x / y * 100
print( percent(3,10))
# 30.0
print( percent(1,3))
# 33.3333333333
print( round(percent(1,3), 2))
# 33.33
print( percent(y=10,x=2))
# 20.0
print( percent(30))
#30.0
Parameters example
def percent(x, y=100):
return x / y * 100
print( percent(3,10))
# 30.0
print( percent(1,3))
# 33.3333333333
print( round(percent(1,3), 2))
# 33.33
print( percent(y=10,x=2))
# 20.0
print( percent(30))
#30.0
Parameters example
def percent(x, y=100):
return x / y * 100
print( percent(3,10))
# 30.0
print( percent(1,3))
# 33.3333333333
print( round(percent(1,3), 2))
# 33.33
print( percent(y=10,x=2))
# 20.0
print( percent(30))
#30.0
Parameters example
def percent(x, y=100):
return x / y * 100
print( percent(3,10))
# 30.0
print( percent(1,3))
# 33.3333333333
print( round(percent(1,3), 2))
# 33.33
print( percent(y=10,x=2))
# 20.0
print( percent(30))
#30.0
Parameters example
lambda x: x*x
Lambda function
A one-line function without function name.
quare = lambda x: x*x
print(square(10))
Lambda function
In rare case, we give lambda function a name
L = list(range(1,10))
print(L)
# [1,2,3,4,5,6,7,8,9]
# We can transform the list
L2 = list( map(lambda x: x*x, L) )
print(L2)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
Lambda function
Better usage, when we need an adhoc one-line function.