Conditional Statements: If Statement
Conditional Statements: If Statement
Control structures in Python are the statements that control the flow of execution in a program.
They enable the code to make decisions, repeat actions, and manage complex logic.
Each control structure serves a specific purpose and helps to organize code efficiently and logically.
Here’s an overview of the main types of control structures in Python:
1. Conditional Statements
Conditional statements allow the program to execute certain blocks of code only if certain conditions
are met.
```python
if condition:
```
```python
if condition:
else:
```
```python
if condition1:
elif condition2:
else:
```
2. Loops
for loop: Iterates over items of a collection (like a list or tuple) or a sequence of numbers.
```python
```python
for i in range(5):
```
```python
while condition:
```
```python
for i in range(5):
if i == 3:
print(i)
```
```python
for i in range(5):
if i == 3:
print(i)
```
3. List Comprehensions
A concise way to create lists using `for` loops and conditional expressions.
```python
```
4. Exception Handling
```python
try:
except ExceptionType:
```
```python
try:
except ExceptionType:
finally:
```
5. Functions
Functions provide a way to encapsulate code logic into reusable components and control execution
by calling the function.
```python
def my_function(param):
# Code to execute
return result
```
```python
def find_even_squares(numbers):
even_squares = []
if num % 2 == 0:
square = num ** 2
even_squares.append(square)
else:
continue
return even_squares
try:
result = find_even_squares(range(10))
print(result)
except Exception as e:
```
custom functions
1. Defining a Function
● To define a function, use the `def` keyword, followed by the function name, parentheses for
parameters (if any), and a colon.
● The function body is indented under the definition line.
```python
def greet():
print("Hello, world!")
```
2. Calling a Function
● Once a function is defined, you can call it by using its name followed by parentheses.
```python
```
3. Function Parameters
```python
def greet(name):
print(f"Hello, {name}!")
```
```python
```
4. Default Parameters
```python
def greet(name="Guest"):
print(f"Hello, {name}!")
```
```python
```
5. Return Values
● Functions can return values using the `return` keyword, allowing you to store or use the result in other
parts of your code.
```python
return a + b
result = add(5, 3)
print(result) # Outputs: 8
```
● A function can return multiple values as a tuple, allowing for multiple outputs.
```python
def get_person():
name = "Alice"
age = 30
print(age) # Outputs: 30
```
7. Keyword Arguments
● Keyword arguments allow you to pass arguments to a function by name, which makes the function call
clearer and allows for arguments to be passed in any order.
```python
```
8. Variable-Length Arguments
```python
def print_numbers(*args):
print(number)
print_numbers(1, 2, 3) # Outputs: 1 2 3
```
```python
def print_details(**kwargs):
print(f"{key}: {value}")
# Outputs:
# name: Alice
# age: 30
```
9. Lambda Functions
● Lambda functions are small, anonymous functions defined with the `lambda` keyword.
● They are useful for simple operations that need to be defined quickly.
```python
square = lambda x: x * x
print(square(5)) # Outputs: 25
```
● You can also use lambda functions within other functions, such as with `map`, `filter`, or `sorted`
functions.
```python
def greet(name):
print(f"Hello, {name}!")
```
```python
area = calculate_area(5, 3)
```
Summary
Custom functions
● Custom functions make your code modular, reusable, and help manage complexity by dividing tasks
into manageable sections.
● Let's dive into each of these Python modules along with an explanation of how to create a custom
module.
1. random Module
● The `random` module provides functions to generate random numbers and to perform random
selections.
● Commonly used functions include:
- random.randint(a, b): Returns a random integer between `a` and `b` (inclusive).
```python
import random
```
2. math Module
```python
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
```
3. time Module
```python
import time
print("Start")
```
4. os Module
● The `os` module provides functions for interacting with the operating system.
```python
import os
```
5. shutil Module
● The `shutil` module offers high-level file operations, like copying and removing files.
```python
import shutil
```
6. sys Module
```python
import sys
7. glob Module
```python
import glob
```
8. re Module
- re.sub(pattern, repl, string): Replaces occurrences of the pattern in the string with `repl`.
```python
import re
```
9. statistics Module
```python
import statistics
print(statistics.mean(data)) # 22.5
print(statistics.median(data)) # 20
print(statistics.mode(data)) # 20
```
● You can create your own module by writing a Python file and saving it with a `.py` extension.
● Then, you can import it into other Python scripts.
● Modules can contain any Python code, including variables, classes, and other imported modules.
● Step-by-Step Example:
```python
# mymodule.py
def greet(name):
return x + y
```
```python
# main.py
import mymodule
```
```python
```
OOP
```python
class Dog:
# Initializer (constructor)
# Instance method
def bark(self):
my_dog = Dog("Buddy", 5)
```
2.Encapsulation
● Encapsulation is the bundling of data and methods that operate on that data within a class.
● It also restricts direct access to some components (using private attributes).
- Private Attributes:
● Use an underscore `_` prefix (e.g., `_attribute`) to suggest that an attribute or method is intended for
internal use only.
● A double underscore (`__`) triggers name mangling to make it harder to access from outside.
```python
class BankAccount:
self.owner = owner
if amount > 0:
self.__balance += amount
self.__balance -= amount
return amount
def get_balance(self):
return self.__balance
account.deposit(50)
```
3. Abstraction
● Abstraction hides complex details from the user and exposes only the essentials.
● In Python, this is achieved by defining public methods that provide meaningful and simplified
interfaces.
```python
class Car:
self.make = make
self.model = model
def start(self):
self.__check_fuel()
print("Car is starting")
```
4. Inheritance
● Inheritance allows a class (child or subclass) to inherit attributes and methods from another class
(parent or superclass).
● It enables code reusability.
```python
class Animal:
self.name = name
def speak(self):
def speak(self):
return "Woof!"
def speak(self):
return "Meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
```
5. Polymorphism
● Polymorphism allows methods in different classes to have the same name but behave differently
depending on the class.
● It allows the use of a single interface for different types.
```python
class Bird:
def fly(self):
class Penguin(Bird):
def fly(self):
def bird_action(bird):
print(bird.fly())
sparrow = Bird()
penguin = Penguin()
```
- super() function: Calls the parent class’s method within an overridden method.
```python
class Vehicle:
self.brand = brand
self.speed = speed
def drive(self):
class ElectricVehicle(Vehicle):
super().__init__(brand, speed)
self.battery_capacity = battery_capacity
def drive(self):
super().drive()
ev.drive()
```
```python
class Book:
self.author = author
```
File handling
● File handling in Python allows you to read from, write to, and manage files, making it a crucial tool
for interacting with external files in various formats.
● Here's an overview of the main concepts and methods.
Use the open() function to open a file, which returns a file object.
The general syntax is:
```python
```
- Modes:
r - Read (default mode): Opens the file for reading. The file must exist.
w - Write: Opens the file for writing. Creates a new file if it doesn’t exist or overwrites an existing file.
a - Append: Opens the file for appending. Data is added to the end of the file without truncating it.
b - Binary mode: Used with other modes like `rb` or `wb` for binary files (e.g., images, executable files).
To ensure files are closed after use, always use `file.close()` or the **with statement**, which closes
the file automatically:
```python
data = file.read()
```
2. Reading Files
data = file.read()
print(data)
```
```python
line = file.readline()
while line:
print(line.strip())
line = file.readline()
```
```python
lines = file.readlines()
print(line.strip())
```
3. Writing to Files
```python
file.write("Hello, world!\n")
```
```python
file.writelines(lines)
```
4. Appending to Files
Opening a file in `'a'` mode adds content to the end of the file without overwriting existing data.
```python
```
The file pointer represents the current position in the file where reading or writing will occur.
```python
print(data)
```
Binary files (e.g., images, videos) are opened in binary mode (`'rb'` or `'wb'`).
```python
data = file.read()
file.write(data)
```
```python
import os
if os.path.exists("example.txt"):
print("File exists.")
else:
```
Deleting a File
```python
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
else:
```
Renaming a File
```python
import os
os.rename("old_name.txt", "new_name.txt")
```
Using `with` is recommended because it automatically closes the file, even if an error occurs.
```python
data = file.read()
print(data)
```
3. Writing:
4. Appending: Use `'a'` mode to add data without deleting existing content.
5. Seek and File Pointer: `seek(offset, whence)` to move the file pointer.
7. File Management: `os.path.exists()`, `os.remove()`, and `os.rename()` for file checks and management.
These operations provide essential control over reading, writing, and managing files in Python.
Writing and parsing text files in Python is simple and can be done using basic file handling techniques.
Here’s a breakdown of how to write data to text files and then parse them to read and process the
contents.
You can write data to a file using the `open()` function with write (`"w"`) or append (`"a"`) modes.
```python
```
This code opens `example.txt` for writing, writes two lines, and automatically closes the file when done.
If you have a list of strings, you can use `writelines()` to write all lines at once:
```python
file.writelines(lines)
```
To add content without deleting what’s already in the file, use the append mode `"a"`.
```python
```
Reading a file allows you to extract its content and perform processing.
Reading the Entire Content: Use the `read()` method to read the entire content as a single string.
```python
content = file.read()
print(content)
```
Reading Line by Line :The `readline()` method allows you to read a file line by line, which is useful for
large files.
```python
line = file.readline()
while line:
line = file.readline()
```
Reading All Lines into a List : The `readlines()` method reads all lines into a list, where each element is a
line from the file.
```python
lines = file.readlines()
print(line.strip())
```
If your file has structured data, such as CSV format (comma-separated values), you can use Python’s
`csv` module for parsing, or simply split each line by a delimiter.
For a text file with a specific delimiter, you can use `split()` to break down each line.
```python
print(parts)
```
```
Alice,24,Engineer
Bob,30,Doctor
```
```
```
```python
import csv
data = [
]
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
```
```python
import csv
reader = csv.reader(file)
print(row)
```
```python
import json
data = {
"name": "Alice",
"age": 24,
"occupation": "Engineer"
```
```python
import json
data = json.load(file)
print(data)
```
Summary
Writing to Files:
With these techniques, you can easily write and parse text files for various data handling needs.