Python Functions
3 min read ·
A function is a block of reusable code that performs a specific task.
Functions help in:
- Reducing code repetition
- Improving readability
- Making programs modular and organized
Once a function is defined, it can be called multiple times.
Why Use Functions?
Functions are used to:
- Break large programs into smaller parts
- Reuse logic instead of rewriting code
- Make debugging and maintenance easier
Syntax of a Function
defis a keyword used to define a functionfunction_namefollows variable naming rules- Parentheses
()are mandatory - Function body must be indented
Simple Function Example
Calling the function:
Function with Parameters
Parameters allow passing data to a function.
Calling the function:
Function with Multiple Parameters
Function with Return Statement
The
return statement sends a value back to the caller.Note
A function stops executing once return is encountered.
Function Without Return (Void Function)
Default Parameter Values
Keyword Arguments
Positional Arguments
Function with *args
Used to pass multiple arguments.
Function with **kwargs
Used to pass key-value pairs.
Calling a Function Inside Another Function
Nested Functions
Function with Conditional Logic
Function with Loop
Scope of Variables in Functions
- Variables inside a function are local
- They cannot be accessed outside
Common Mistakes with Functions
Forgetting to Call the Function ❌
Function will not run until called.
Missing Parentheses ❌
Caution
Always use () while calling a function.
Real World Example
Real World Scenario
ATM balance check using function
Exercise
Practice Task
- Create a function to add two numbers
- Write a function to check prime number
- Create a function that returns square of a number
- Use
*argsto calculate sum of numbers - Create a function to display user details