|
| 1 | +## Functions in Python |
| 2 | + |
| 3 | +Functions are blocks of reusable code designed to perform specific tasks. They make code more modular, organized, and easier to read and maintain. The code inside the body of a function is executed only when the function is called. |
| 4 | + |
| 5 | +In Python, functions can be broadly categorized into two types: predefined functions and user-defined functions. |
| 6 | + |
| 7 | +### 1. Predefined Functions |
| 8 | + |
| 9 | +Predefined functions, also known as built-in functions, are functions that are already available in Python. These functions are provided by Python's standard library and can be used without the need for any additional code or imports. Common examples include: |
| 10 | + |
| 11 | +- **`print()`**: Outputs data to the console. |
| 12 | +- **`len()`**: Returns the length of an object. |
| 13 | +- **`type()`**: Returns the type of an object. |
| 14 | + |
| 15 | +### 2. User-Defined Functions |
| 16 | + |
| 17 | +User-defined functions are functions created by the programmer to perform specific tasks. These functions are not built into Python; instead, they are defined by the user to handle tasks unique to their program or application. |
| 18 | + |
| 19 | +### Creating a Function |
| 20 | + |
| 21 | +In Python, a function is defined using the `def` keyword: |
| 22 | + |
| 23 | +```python |
| 24 | +def my_function(): |
| 25 | + print("Hello from a function") |
| 26 | +``` |
| 27 | +### Calling a Function |
| 28 | + |
| 29 | +```python |
| 30 | +def my_function(): |
| 31 | + print("Hello from a function") |
| 32 | + |
| 33 | +my_function() # Output: Hello from a function |
| 34 | + |
| 35 | +``` |
| 36 | +## Practice Questions for Functions |
| 37 | + |
| 38 | +### 1. Sum of Two Numbers |
| 39 | + |
| 40 | +Write a Python function `sum_two_numbers` that takes two arguments and returns their sum. |
| 41 | + |
| 42 | +### 2. Maximum of Three Numbers |
| 43 | + |
| 44 | +Write a Python function `max_of_three` that takes three numbers as arguments and returns the largest of the three. |
| 45 | + |
| 46 | +### 3. Fibonacci Sequence |
| 47 | + |
| 48 | +Write a Python function `fibonacci` that takes an integer `n` and returns the `n`th number in the Fibonacci sequence. |
| 49 | + |
| 50 | +### 4. Factorial of a Number |
| 51 | + |
| 52 | +Write a Python function `factorial` that takes an integer `n` and returns the factorial of `n` (i.e., `n!`). |
| 53 | + |
| 54 | +### 5. Check Prime Number |
| 55 | + |
| 56 | +Write a Python function `is_prime` that takes an integer `n` and returns `True` if `n` is a prime number, and `False` otherwise. |
| 57 | + |
| 58 | +### 6. Reverse a String |
| 59 | + |
| 60 | +Write a Python function `reverse_string` that takes a string `s` and returns the reversed version of the string. |
0 commit comments