Defining Functions

A function is a block of organized, reusable code that performs a specific task.
Functions help make programs shorter, cleaner, and easier to manage.

Instead of writing the same code again and again, you can define it once and reuse it.

WHY USE FUNCTIONS?

• Reduce code repetition
• Improve readability
• Make programs modular
• Simplify debugging and maintenance

SYNTAX OF A FUNCTION

def function_name(parameters):
# code block

def is the keyword used to define a function
function_name is the name of the function
parameters are optional inputs
• Indentation is required

EXAMPLE 1: SIMPLE FUNCTION

def greet():
print("Hello, welcome to Python!")greet()

When you call greet(), the message is printed.

FUNCTION WITH PARAMETERS

You can pass values into a function.

def greet(name):
print("Hello", name)greet("Hira")

The function prints a personalized message.

FUNCTION WITH RETURN VALUE

Functions can return a result using the return keyword.

def add(a, b):
return a + bresult = add(5, 3)
print(result)

The function calculates the sum and returns it.

DEFAULT PARAMETERS

You can provide default values to parameters.

def greet(name="Guest"):
print("Hello", name)greet()
greet("Ali")

If no value is passed, the default value is used.

KEY POINTS

• Function names should be meaningful
• Always use parentheses when calling a function
• Use return when you need output from a function
• Indentation is very important

WHY FUNCTIONS ARE IMPORTANT

Functions are essential for building large applications.
They help organize code into manageable sections and make programs more efficient and professional.

Understanding how to define and use functions is a fundamental skill in Python programming.

Home » PYTHON FUNDAMENTALS (PYF) > Functions > Defining Functions