🐍 Functions in Python
Defining, Calling, Passing Arguments and Returning Values
1. What is a Function?
Instead of writing the same code repeatedly, we define the code inside a function and call the function whenever required.
Write code once and execute it multiple times.
Large programs can be divided into smaller modules.
Functions make programs easier to understand.
Changes can be made inside one function.
2. Defining a Function
Python uses the def keyword to define a function.
def function_name():
statements
Important Parts
| Part | Meaning |
|---|---|
| def | Keyword used to define a function. |
| function_name | Name of the function. |
| () | Contains parameters, if required. |
| : | Marks the beginning of the function body. |
| Indented statements | Statements executed when the function is called. |
3. Simple Function Example
def greet():
print("Hello, Python!")
greet()
Output
Here, greet() is the function call. When Python reaches this statement, the function body is executed.
4. Function with Parameters
A parameter is a variable defined inside the function declaration to receive data.
def greet(name):
print("Hello", name)
greet("Bijan")
Output
| Term | Example | Meaning |
|---|---|---|
| Parameter | name | Variable defined by the function. |
| Argument | "Bijan" | Actual value passed to the function. |
5. Function with Multiple Parameters
def add(a, b):
print("Sum =", a + b)
add(10, 20)
Output
6. Function with Return Value
def square(n):
return n * n
result = square(5)
print("Square =", result)
Output
7. How a Function Works
8. Common Types of Functions
Function without parameters and without return value.
Function with parameters but without return value.
Function without parameters but with return value.
Function with parameters and return value.
9. Interactive Function Demonstration
Click a button to see how different function calls work.
10. Important Points for Examination
- Functions are defined using the def keyword.
- A function is executed when it is called.
- Parameters receive values passed to a function.
- The return statement sends a value back.
- Python functions improve code reusability.
- Indentation is compulsory inside a function.
- A function may have zero, one, or multiple parameters.
11. Quick Summary
def function_name(parameters):
statements
return value
function_name(arguments)
No comments:
Post a Comment