Functions
🔧 What Is a Function in Programming?
A function is a reusable block of code designed to perform a specific task. Instead of writing the same code repeatedly, you can define it once in a function and "call" it whenever needed.
✅ Why Use Functions?
Reusability: Write once, use many times.
Clarity: Makes code easier to read and understand.
Organization: Helps break large programs into smaller, manageable pieces.
Debugging: Easier to find and fix errors in isolated blocks of code.
🧠 How Functions Work
A basic function has:
Name – to identify the function.
Parameters (optional) – input values.
Code block – what the function does.
Return value (optional) – the result it gives back.
1. Basic Function Without Parameters
def who_i_am():
name = "KT"
age = 25
gpa = 2.8
print("My name is " + name + " and I am " + str(age) + " years old.")
who_i_am()
def
: Defines a function namedwho_i_am
.Inside the function, variables are set and a message is printed.
who_i_am()
calls the function and displays:

2. Function with One Parameter
def add_one_hundred(num):
print(num + 100)
add_one_hundred(200)
Accepts one input (
num
), adds 100 to it, and prints the result.Output:

3. Function with Two Parameters
def add(x, y):
print(x + y)
add(10, 20)
Takes two inputs and prints their sum.
Output:

4. Function with Return Value
def multiply(x, y):
return(x * y)
print(multiply(10, 20))
Multiplies
x
andy
, then returns the result usingreturn
.print()
displays the returned value.Output:

✅ Summary
Functions organize code into reusable blocks.
Use parameters to pass data in.
Use
return
to send data out.Calling a function runs its code.
#!/bin/python3
#Functions
def who_i_am():
name = "KT"
age = 25
gpa = 2.8
print("My name is " + name + " and I am " + str(age) + " years old.")
who_i_am()
#adding parameters
def add_one_hundred(num):
print(num + 100)
add_one_hundred(200)
#multiple parameters
def add(x,y):
print(x + y)
add(10,20)
def multiply(x,y):
return(x * y)
print(multiply(10,20))
Last updated