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
1def function_name(parameters):2 # function bodyExample
1def greet():2 print("Hello, Akash!")The function does not run when it is defined. It runs when we call it.
1
Output:
1Hello, Akash!2. Function Parameters
Parameters are variables that receive values when a function is called.
1def greet(name):2 print("Hello", name)3 4greet("Akash")Output:
1Hello AkashHere:
name→ parameter"Akash"→ argument
A function can have multiple parameters:
1def add(a, b):2 print(a + b)3 4add(10, 20)Output:
1303. Return Value
A function can send a result back to the caller using return.
1def add(a, b):2 return a + b3 4result = add(10, 20)5 6print(result)Output:
130return 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.
1def greet(name):2 print("Hello", name)3 4greet("Akash")Here:
1name → Parameter2"Akash" → ArgumentPython 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.
1def greet(name="User"):2 print("Hello", name)3 4greet()5greet("Akash")Output:
1Hello User2Hello AkashThe default value is used when no argument is provided.
6. pass Statement
The pass statement is used when a function has no implementation yet.
1def my_function():2 passIt allows us to create an empty function without getting an error.
7. Why Use Functions?
Without a function:
1print("Hello Akash")2print("Hello Rahul")3print("Hello Priya")With a function:
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
| Concept | Meaning |
|---|---|
def | Used to define a function |
| Function | Reusable block of code |
| Parameter | Variable defined in a function |
| Argument | Value passed to a function |
return | Sends a result back |
| Default parameter | Parameter with a default value |
pass | Placeholder for an empty function |
| Function call | Executes a function |