# Function
Function is a group of many commands.
We had used a lot of function before this lesson. For example,
lenprintrangeand more.
# How to define our own function
- uses
defkeyword following with the name of function
def introduce():
print("Hi, My name is CodeKids. I am 4 years old.")
1
2
2
OUTPUT
- Does not have any output? Why? We need to call them.
def introduce():
print("Hi, My name is CodeKids. I am 4 years old.")
introduce()
1
2
3
2
3
OUTPUT
Hi, My name is CodeKids. I am 4 years old.
# Function parameter(s) and argument(s)
def introduce(name, age):
print(f"Hi, My name is {name}. I am {age} years old.")
introduce("CodeKids",4)
introduce("CodeKit",5)
1
2
3
4
5
2
3
4
5
OUTPUT
Hi, My name is CodeKids. I am 4 years old.
Hi, My name is CodeKit. I am 5 years old.
# return keyword
returnkeyword is used for returning some values back to somebody who make a call to particular function.- Moreover, if the
returnis executed, the function would be stopped itself.
def my_plus(a, b):
return a+b
data = my_plus(3, 4)
print(data)
data2 = my_plus("3", "4")
print(data2)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
OUTPUT
7
34
Debugging process
def my_plus(a, b):
return a+b
data = my_plus(3, 4)
print(data)
1
2
3
4
5
2
3
4
5
def my_plus(a, b):
return a+b
data = my_plus(3, 4)
print(data)
1
2
3
4
5
2
3
4
5
my_plus(a, b) => my_plus(3, 4) => a=3, b=4
def my_plus(a, b):
return a+b
data = my_plus(3, 4)
print(data)
1
2
3
4
5
2
3
4
5
a=3, b=4 => return a+b => return 3+4 => return 7
def my_plus(a, b):
return a+b
data = my_plus(3, 4)
print(data)
1
2
3
4
5
2
3
4
5
Therefore, my_plus(3, 4) == 7 => data = my_plus(3, 4) => data = 7
def my_plus(a, b):
print("HelloWorldddddddd")
return a+b
data = my_plus(3, 4)
print(data)
data2 = my_plus("3", "4")
print(data2)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
OUTPUT
HelloWorldddddddd
7
HelloWorldddddddd
34
def my_plus(a, b):
return a+b
print("HelloWorldddddddd")
data = my_plus(3, 4)
print(data)
data2 = my_plus("3", "4")
print(data2)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
OUTPUT
7
34