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.
