Functions

Python Functions

Python Functions

A function is a block of reusable code that performs a specific task.

Functions help us:

  • Avoid repeating code
  • Organize code
  • Reuse the same logic with different inputs

1. Creating a Function

In Python, a function is defined using the def keyword.

Syntax

python
1def function_name(parameters):
2 # function body

Example

python
1def greet():
2 print("Hello, Akash!")

The function does not run when it is defined. It runs when we call it.

python
1

Output:

text
1Hello, Akash!

2. Function Parameters

Parameters are variables that receive values when a function is called.

python
1def greet(name):
2 print("Hello", name)
3
4greet("Akash")

Output:

text
1Hello Akash

Here:

  • name → parameter
  • "Akash" → argument

A function can have multiple parameters:

python
1def add(a, b):
2 print(a + b)
3
4add(10, 20)

Output:

text
130

3. Return Value

A function can send a result back to the caller using return.

python
1def add(a, b):
2 return a + b
3
4result = add(10, 20)
5
6print(result)

Output:

text
130

return also stops the execution of the function.

If a function does not have a return statement, it returns None.


4. Arguments

Arguments are the actual values passed to a function.

python
1def greet(name):
2 print("Hello", name)
3
4greet("Akash")

Here:

text
1name → Parameter
2"Akash" → Argument

Python supports different ways of passing arguments, such as:

  • Positional arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

5. Default Parameter

A parameter can have a default value.

python
1def greet(name="User"):
2 print("Hello", name)
3
4greet()
5greet("Akash")

Output:

text
1Hello User
2Hello Akash

The default value is used when no argument is provided.


6. pass Statement

The pass statement is used when a function has no implementation yet.

python
1def my_function():
2 pass

It allows us to create an empty function without getting an error.


7. Why Use Functions?

Without a function:

python
1print("Hello Akash")
2print("Hello Rahul")
3print("Hello Priya")

With a function:

python
1def greet(name):
2 print("Hello", name)
3
4greet("Akash")
5greet("Rahul")
6greet("Priya")

The second approach lets us write the logic once and reuse it.


Quick Revision

ConceptMeaning
defUsed to define a function
FunctionReusable block of code
ParameterVariable defined in a function
ArgumentValue passed to a function
returnSends a result back
Default parameterParameter with a default value
passPlaceholder for an empty function
Function callExecutes a function
Next Topic*args, **kwargs