### Functions in Python
#### 1. Functions
- **Definition**: A block of reusable code that performs a specific task.
- **Syntax**:
def function_name(parameters):
# Code block
return value
#### 2. Built-in Functions
- Predefined functions provided by Python, e.g., print(), len(), type(), input(), etc.
- Examples:
print("Hello World") # Outputs: Hello World
len([1, 2, 3]) # Outputs: 3
#### 3. Commonly Used Modules
- **math**: Provides mathematical functions like sqrt, sin, cos, etc.
- **random**: For generating random numbers and performing random operations.
- **os**: Interact with the operating system (file operations, environment variables).
- **datetime**: Work with dates and times.
- **scipy**: Advanced scientific computations.
#### 4. Function Definition and Calling
- **Defining**:
def greet(name):
return f"Hello, {name}!"
- **Calling**:
print(greet("Tanisha")) # Outputs: Hello, Tanisha!
#### 5. The return Statement and Void Functions
- **return**: Used to return a value from a function.
def add(a, b):
return a + b
- **Void Functions**: Do not return a value; implicitly return None.
def say_hello():
print("Hello")
#### 6. Scope and Lifetime of Variables
- **Local Scope**: Variables defined within a function.
- **Global Scope**: Variables defined outside any function.
- **Lifetime**: A variable's lifetime depends on its scope; local variables are destroyed after the
function ends.
#### 7. Default Parameters
- Parameters with default values.
def greet(name="Guest"):
return f"Hello, {name}!"
#### 8. Keyword Arguments
- Explicitly specifying parameter names during function calls.
def person_details(name, age):
print(f"Name: {name}, Age: {age}")
person_details(age=20, name="Tanisha")
#### 9. *args and **kwargs
- **args**: For passing a variable number of positional arguments.
def add(*numbers):
return sum(numbers)
- **kwargs**: For passing a variable number of keyword arguments.
def display_info(**details):
for key, value in details.items():
print(f"{key}: {value}")
#### 10. Command Line Arguments
- Using the sys module to access arguments passed from the command line.
import sys
print(sys.argv) # List of command-line arguments
#### 11. Generating Random Numbers
- Using the random module:
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.random()) # Random float between 0 and 1
---
### Recursion
#### 1. Introduction
- A function that calls itself to solve a problem.
- Base case is necessary to terminate recursion.
#### 2. Problem Solving with Recursion
- Divide the problem into smaller sub-problems.
#### 3. Examples of Recursive Algorithms
- **Factorial**:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
- **Fibonacci**:
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
---
### Files in Python
#### 1. Types of Files
- **Text Files**: Store data in plain text.
- **Binary Files**: Store data in binary format.
#### 2. Creating and Reading Text Data
- **Write**:
with open("file.txt", "w") as f:
f.write("Hello World")
- **Read**:
with open("file.txt", "r") as f:
print(f.read())
#### 3. File Methods to Read and Write Data
- **read()**: Reads entire file.
- **readline()**: Reads one line at a time.
- **write()**: Writes a string to the file.
#### 4. Reading and Writing Binary Files
- **Write Binary**:
with open("file.bin", "wb") as f:
f.write(b"Binary Data")
- **Read Binary**:
with open("file.bin", "rb") as f:
print(f.read())
#### 5. The pickle Module
- Serialize and deserialize Python objects.
import pickle
with open("data.pkl", "wb") as f:
pickle.dump([1, 2, 3], f)
with open("data.pkl", "rb") as f:
print(pickle.load(f))
#### 6. Reading and Writing CSV Files
- Using the csv module:
import csv
with open("data.csv", "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["Tanisha", 20])
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)