What are Functions?
A function is a reusable block of code that performs a specific task.
Functions help make programs easier to understand, reuse and maintain.
def function_name():
# code
1. Creating a Function
In Python, we use the def
keyword to define a function.
def greet():
print("Hello, PyStep!")
Here, greet is the name
of the function.
2. Calling a Function
A function runs when we call it using its name followed by parentheses.
def greet():
print("Hello, PyStep!")
greet()
Hello, PyStep!
3. Function Parameters
Parameters allow us to pass information to a function.
def greet(name):
print("Hello", name)
greet("Sudhanshu")
Hello Sudhanshu
4. Multiple Parameters
A function can have more than one parameter.
def add(a, b):
print(a + b)
add(10, 20)
30
5. return Statement
The return statement sends
a result back from a function.
def add(a, b):
return a + b
result = add(10, 20)
print(result)
30
6. Practical Example
Functions can be used to calculate the square of a number.
def square(number):
return number * number
answer = square(5)
print("Square =", answer)
Square = 25
7. Advantages of Functions
Reusability
Write code once and use it multiple times.
Easy to Understand
Functions divide a large program into smaller parts.
Easy Maintenance
Changes can be made in one function instead of repeating code.
def is used to define a function.
Parameters receive values, while
return sends a result back.
Quick Quiz
Which keyword is used to define a function in Python?
Finished this lesson?