Python Functions
🐍 Python Functions — Full Tutorial
A function in Python is a block of reusable code that performs a specific task. Functions help reduce code repetition and make programs modular.
1. Creating a Function
Use the def keyword:
Calling the function:
✅ Output:
2. Function with Parameters
Parameters allow you to pass data to a function:
✅ Output:
3. Function with Return Value
Use return to send data back:
4. Default Parameters
Provide a default value if argument is not passed:
5. Keyword Arguments
You can pass arguments by name, order doesn’t matter:
6. Variable-length Arguments
6.1 *args → Non-keyword variable arguments
6.2 **kwargs → Keyword variable arguments
7. Lambda (Anonymous) Functions
A lambda function is a small one-line function:
8. Scope of Variables
8.1 Local Variables
Defined inside a function, accessible only inside.
8.2 Global Variables
Defined outside a function, accessible anywhere.
8.3 Using global Keyword
Modify global variable inside a function:
9. Nested Functions (Inner Functions)
10. Recursion (Function Calling Itself)
-
Important: Always define a base case to avoid infinite recursion.
11. Docstrings (Documentation Strings)
12. Higher-Order Functions
Functions that take other functions as arguments:
Python built-ins like map(), filter(), and reduce() also use higher-order functions.
13. Practical Examples
13.1 Calculator Function
13.2 Fibonacci Series Using Function
14. Summary Table
| Feature | Example |
|---|---|
| Function Definition | def func(): |
| Parameters | def greet(name): |
| Default Parameters | def greet(name="Guest"): |
| Variable Arguments | *args, **kwargs |
| Return Value | return value |
| Lambda Function | lambda x: x**2 |
| Docstring | """This is a function""" |
| Scope | Local vs Global |
🧠 Practice Exercises
-
Create a function to check if a number is prime.
-
Write a function that returns factorial of a number.
-
Create a function that counts vowels in a string.
-
Write a function that checks if a string is a palindrome.
-
Use
*argsto sum all numbers in a function call.
