ovbject orientedprogramming(oops)

In Python, object-oriented programming (OOP) is supported, and it utilizes several key concepts known as the “four pillars of OOP” or “OOP principles.” These principles, also known as OOPs concepts, are:

  1. Encapsulation: It refers to the bundling of data and methods/functions that operate on that data within a single unit called a class. Encapsulation provides data hiding and protects the internal implementation of an object. Access to the data is restricted to the methods defined in the class.Example:
    • class Car:
    • def init(self, brand, color):
    • self.brand = brand
    • self.color = color
    • self.speed = 0
    • my_car = Car(“Tesla”, “red”)
    • my_car.accelerate(20)
    • print(my_car.speed) # Output: 20
  2. Inheritance: It allows creating a new class (derived class) by inheriting the properties and methods of an existing class (base or parent class). The derived class can extend or modify the behavior of the base class. Inheritance facilitates code reuse and supports the concept of hierarchical classification.
    • Example:
    • class Animal:
    • def init(self, name):
    • self.name = name
    • class Dog(Animal):
    • def speak(self):
    • print(“Dog barks”)
    • my_dog = Dog(“Buddy”)
    • my_dog.speak() # Output: Dog barks
  3. Polymorphism: It allows objects of different classes to be treated as objects of a common base class. Polymorphism allows methods/functions to be written to accept objects of a base class and automatically work with objects of any derived class.Example:
    • class Shape:
    • def area(self):
    • pass
    • class Rectangle(Shape):
    • def init(self, length, width):
    • self.length = length
    • self.width = width
    • class Circle(Shape):
    • def init(self, radius):
    • self.radius = radius
    • def print_area(shape):
    • print(“Area:”, shape.area())
    • rectangle = Rectangle(5, 3)
    • circle = Circle(4)
    • print_area(rectangle) # Output: Area: 15
    • print_area(circle) # Output: Area: 50.24
  4. Abstraction: It involves hiding unnecessary implementation details and exposing only the essential features to the users. Abstraction helps in managing complexity by providing a simplified interface to interact with objects.Example:
    • from abc import ABC, abstractmethod
    • class Vehicle(ABC):
    • @abstractmethod
    • def start(self):
    • pass
    • class Car(Vehicle):
    • def start(self):
    • print(“Car started”)
    • class Bike(Vehicle):
    • def start(self):
    • print(“Bike started”)
    • car = Car()
    • car.start() # Output: Car started
    • bike = Bike()
    • bike.start() # Output: Bike started

file handling

In Python, file handling refers to reading and writing data to files. Here are some common operations and functions related to file handling in Python:

  1. Opening a File: To open a file, you can use the open() function and specify the file name and mode (read, write, append, etc.).
    • file = open("myfile.txt", "r")
    • # Opens the file in read mode
  2. Reading from a File: Once a file is opened, you can read its contents using methods like read(), readline(), or readlines().pythonCopy code
    • content = file.read() # Reads the entire file content
    • line = file.readline() # Reads a single line from the file
    • lines = file.readlines() # Reads all lines and returns a list
  3. Writing to a File: To write data to a file, you need to open it in write mode ("w") or append mode ("a"), and then use the write() method.
    • file = open("myfile.txt", "w") # Opens the file in write mode file.write("Hello, World!") # Writes data to the file
    • file.close() # Closes the file
  4. Appending to a File: If you want to add content to an existing file without overwriting its contents, open the file in append mode ("a") and use the write() method.
    • file = open("myfile.txt", "a") # Opens the file in append mode file.write("New content") # Appends data to the file
    • file.close() # Closes the file
  5. Closing a File: It’s important to close the file after you’re done with it to release system resources.
    • file.close()
    • # Closes the file
  6. Using Context Managers (Recommended): A better practice is to use the with statement, which automatically closes the file after the block of code.
    • with open("myfile.txt", "r") as file:
    • content = file.read()
    • # File is automatically closed outside the 'with' block
  7. Error Handling: When working with files, errors can occur. To handle exceptions, you can use try and except blocks.
    • try:
    • file = open(“myfile.txt”, “r”)
    • # Perform file operations
    • except FileNotFoundError:
    • print(“File not found!”)
    • finally:
    • file.close() # Close the file regardless of an exception

These are some of the fundamental file handling operations in Python. It’s important to handle file operations properly, close files after use, and handle potential exceptions to ensure clean and error-free file handling.

Tuples

In Python, tuples are immutable objects, which means they cannot be modified once created. However, there are several built-in functions and methods that you can use with tuples. Here are some commonly used functions and methods for working with tuples in Python:

  1. len(): Returns the number of elements in a tuple.
    • fruits = ("apple", "banana", "cherry")
    • length = len(fruits)
    • print(length) # Output: 3
  2. index(): Returns the index of the first occurrence of a specified element in the tuple.
    • fruits = ("apple", "banana", "cherry", "banana")
    • index = fruits.index("banana")
    • print(index) # Output: 1
  3. count(): Returns the number of occurrences of a specified element in the tuple.
    • fruits = ("apple", "banana", "cherry", "banana")
    • count = fruits.count("banana")
    • print(count) # Output: 2
  4. sorted(): Returns a new sorted list of elements from the tuple (not modifying the original tuple).
    • numbers = (3, 1, 4, 2, 5)
    • sorted_numbers = sorted(numbers)
    • print(sorted_numbers) # Output: [1, 2, 3, 4, 5]
  5. tuple(): Converts an iterable object (such as a list or string) into a tuple.
    • my_list = [1, 2, 3]
    • my_tuple = tuple(my_list)
    • print(my_tuple) # Output: (1, 2, 3)

These functions and methods can help you perform various operations on tuples in Python. Remember that since tuples are immutable, you cannot modify them directly. However, you can utilize these functions and methods to manipulate and work with tuples effectively.

lists

  1. len(): Returns the number of elements in a list.
    • numbers = [1, 2, 3, 4, 5]
    • length = len(numbers)
    • print(length) # Output: 5
  2. append(): Adds an element to the end of a list.
    • fruits = ["apple", "banana"]
    • fruits.append("cherry")
    • print(fruits) # Output: ["apple", "banana", "cherry"]
  3. insert(): Inserts an element at a specific index in the list.
    • fruits = ["apple", "banana", "cherry"]
    • fruits.insert(1, "grape")
    • print(fruits) # Output: ["apple", "grape", "banana", "cherry"]
  4. remove(): Removes the first occurrence of a specified element from the list.
    • fruits = ["apple", "banana", "cherry"]
    • fruits.remove("banana")
    • print(fruits) # Output: ["apple", "cherry"]
  5. pop(): Removes and returns the last element of the list or an element at a specific index.
    • fruits = ["apple", "banana", "cherry"]
    • popped = fruits.pop()
    • print(popped) # Output: "cherry"
  6. index(): Returns the index of the first occurrence of a specified element in the list.
    • fruits = ["apple", "banana", "cherry"]
    • index = fruits.index("banana")
    • print(index) # Output: 1
  7. count(): Returns the number of occurrences of a specified element in the list.
    • fruits = ["apple", "banana", "cherry", "banana"]
    • count = fruits.count("banana")
    • print(count) # Output: 2
  8. sort(): Sorts the list in ascending order (in-place modification).
    • numbers = [3, 1, 4, 2, 5]
    • numbers.sort()
    • print(numbers) # Output: [1, 2, 3, 4, 5]
  9. reverse(): Reverses the order of elements in the list (in-place modification).
    • numbers = [1, 2, 3, 4, 5]
    • numbers.reverse()
    • print(numbers) # Output: [5, 4, 3, 2, 1]

These are just a few examples of the functions and methods available for manipulating lists in Python. Python provides many more built-in functions and additional methods to work with lists effectively.

packages

In Python, packages are a way to organize related modules into a hierarchical directory structure. They help in organizing and managing large codebases and promote code reusability. Python’s standard library and the broader Python ecosystem offer a wide range of packages for various purposes. Here are some commonly used packages in Python along with examples:

  1. numpy – Provides support for large, multi-dimensional arrays and mathematical functions.
    • import numpy as np
    • array = np.array([1, 2, 3, 4, 5])
    • print(array) # Output: [1, 2, 3, 4, 5]
  2. pandas – Offers high-performance, easy-to-use data structures and data analysis tools.
    • import pandas as pd
    • data = {'Name': ['John', 'Alice', 'Bob'], 'Age': [25, 30, 35]}
    • df = pd.DataFrame(data)
    • print(df) # Output: A tabular representation of the data
  3. matplotlib – Enables data visualization with a wide range of plotting options.
    • import matplotlib.pyplot as plt
    • x = [1, 2, 3, 4, 5]
    • y = [2, 4, 6, 8, 10]
    • plt.plot(x, y)
    • plt.show() # Displays the plot
  4. requests – Simplifies making HTTP requests and interacting with APIs.
    • import requests
    • response =requests.get('https://api.example.com/data')
    • print(response.json()) # Output: JSON response from the API
  5. datetime – Provides classes for working with dates, times, and time intervals.
    • import datetime
    • current_time = datetime.datetime.now()
    • print(current_time) # Output: Current date and time
  6. sqlite3 – Enables interaction with SQLite databases.
    • import sqlite3
    • conn = sqlite3.connect('mydatabase.db')
    • cursor = conn.cursor()
    • cursor.execute('SELECT * FROM users')
    • rows = cursor.fetchall()
    • print(rows) # Output: Data retrieved from the database
  7. tkinter – Provides a GUI toolkit for creating desktop applications.
    • import tkinter as tk
    • window = tk.Tk()
    • label = tk.Label(window, text="Hello, World!")
    • label.pack()
    • window.mainloop() # Displays the GUI window

modules

Python has a rich ecosystem of modules that provide additional functionality beyond what is available in the core language. These modules can be imported and used in your Python scripts to perform specific tasks. Here are some commonly used modules in Python along with examples:

  1. math – Provides mathematical functions and operations
    • import math
    • result = math.sqrt(25)
    • print(result) # Output: 5.0
  2. random – Generates random numbers and performs random selections.
    • import random
    • random_num = random.randint(1, 10)
    • print(random_num) # Output: Random number between 1 and 10
  3. datetime – Manipulates dates and times.
    • import datetime
    • current_time = datetime.datetime.now()
    • print(current_time) # Output: Current date and time
  4. os – Provides functions for interacting with the operating system.
    • import os
    • current_directory = os.getcwd()
    • print(current_directory) # Output: Current working directory
  5. json – Allows encoding and decoding JSON data.
    • import json
    • data = {‘name’: ‘John’, ‘age’: 25}
    • json_data = json.dumps(data)
    • print(json_data) # Output: JSON representation of the data
  6. requests – Simplifies making HTTP requests.
  7. csv – Provides functionality for reading and writing CSV files.
    • import csv
    • with open(‘data.csv’, ‘r’) as file:
    • reader = csv.reader(file)
    • for row in reader:
    • print(row) # Output: Each row of the CSV file
  8. time – Performs time-related operations and sleeps.
    • import time
    • current_time = time.time()
    • print(current_time) # Output: Current timestamp in seconds

functions

In Python, functions are an essential part of the language and provide a way to encapsulate reusable blocks of code. Here are some built-in functions in Python along with examples:

  1. print() – Displays output to the console.
    • print("Hello, World!")
  2. len() – Returns the length of an object.
    • fruits = ["apple", "banana", "orange"]
    • print(len(fruits)) # Output: 3
  3. input() – Reads user input from the console.
    • name = input("Enter your name: ")
    • print("Hello, " + name + "!")
  4. range() – Generates a sequence of numbers.
    • for num in range(5):
    • print(num) # Output: 0, 1, 2, 3, 4
  5. type() – Returns the type of an object.
    • x = 5
    • print(type(x)) # Output: <class 'int'>
  6. str() – Converts an object into a string representation.
    • num = 10 num_str = str(num)
    • print(num_str) # Output: "10"
  7. sum() – Returns the sum of elements in an iterable.
    • numbers = [1, 2, 3, 4, 5]
    • total = sum(numbers)
    • print(total) # Output: 15
  8. sorted() – Returns a new sorted list from an iterable.
    • fruits = ["orange", "banana", "apple"]
    • sorted_fruits = sorted(fruits)
    • print(sorted_fruits) # Output: ["apple", "banana", "orange"]
  9. max() and min() – Returns the maximum and minimum values from an iterable.
    • numbers = [5, 3, 9, 1, 7]
    • max_num = max(numbers)
    • min_num = min(numbers)
    • print(max_num, min_num) # Output: 9 1
  10. abs() – Returns the absolute value of a number
    • x = -5
    • abs_value = abs(x)
    • print(abs_value) # Output: 5

These are just a few examples of built-in functions in Python. Python provides a rich library of functions for various purposes. Additionally, you can define your own functions to perform custom operations and tasks.

operators

In Python, operators are special symbols or keywords that perform various operations on operands (values or variables). Python provides a wide range of operators for different purposes, such as arithmetic operations, comparison, logical operations, assignment, and more. Here are some commonly used operators in Python:

  1. Arithmetic Operators:
    • Addition: +
    • Subtraction: -
    • Multiplication: *
    • Division: /
    • Modulus (remainder): %
    • Exponentiation: **
    • Floor Division (integer division): /
    • Example:

x = 10

y = 3

sum_result = x + y

difference_result = x - y

product_result = x * y

quotient_result = x / y

remainder_result = x % y

power_result = x ** y

floor_division_result = x // y

print(sum_result) # Output: 13

print(difference_result) # Output: 7

print(product_result) # Output: 30

print(quotient_result) # Output: 3.3333333333333335 print(remainder_result) # Output: 1

print(power_result) # Output: 1000

print(floor_division_result) # Output: 3

  1. Comparison Operators:
    • Equal to: ==
    • Not equal to: !=
    • Greater than: >
    • Less than: <
    • Greater than or equal to: >=
    • Less than or equal to: <=

python Ex code

x = 5

y = 10

print(x == y) # Output: False

print(x != y) # Output: True

print(x > y) # Output: False

print(x < y) # Output: True

print(x >= y) # Output: False

print(x <= y) # Output: True

  1. Logical Operators:
    • Logical AND: and
    • Logical OR: or
    • Logical NOT: not

pythonCopy code

x = True

y = False

print(x and y) # Output: False

print(x or y) # Output: True

print(not x) # Output: False

  1. Assignment Operators:
    • Assignment: =
    • Compound assignment: +=, -=, *=, /=, %=, **=, //=

pythonCopy code

x = 10
x += 5 # Equivalent to x = x + 5
print(x) # Output: 15

y = 7
y **= 2 # Equivalent to y = y ** 2
print(y) # Output: 49

These are just a few examples of operators in Python. Python supports many more operators, including bitwise operators, membership operators, identity operators, and more. Understanding and using operators is crucial for performing operations, comparisons, and assignments in Python.

control satatements

Control statements in Python are used to control the flow of program execution based on certain conditions. They allow you to make decisions, iterate over sequences, and execute different blocks of code based on specific conditions. The main control statements in Python include:

  1. if-elif-else Statements:
    • These statements are used to perform different actions based on different conditions.
    • Example:

code:

x = 10

if x > 0:
print(“Positive”)
elif x < 0:
print(“Negative”)
else:
print(“Zero”)

  1. for Loops:
    • for loops are used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects.
    • Example:

fruits = [“apple”, “banana”, “orange”]

for fruit in fruits:
print(fruit)

  1. while Loops:
    • while loops are used to repeatedly execute a block of code as long as a condition is true.
    • Example:

count = 0

while count < 5:
print(count)
count += 1

  1. break Statement:
    • The break statement is used to terminate the loop prematurely and skip the remaining iterations.
    • Example:

fruits = [“apple”, “banana”, “orange”]

for fruit in fruits:
if fruit == “banana”:
break
print(fruit)

  1. continue Statement:
    • The continue statement is used to skip the current iteration of a loop and move to the next iteration.
    • Example:

fruits = [“apple”, “banana”, “orange”]

for fruit in fruits:
if fruit == “banana”:
continue
print(fruit)

  1. pass Statement:
    • The pass statement is used as a placeholder when a statement is syntactically required but does not need any code execution.
    • Example:

x = 5

if x > 0:
pass # No code execution needed
else:
print(“Negative”)

Control statements provide the ability to make decisions, perform repetitive tasks, and control the flow of execution in your Python programs. They are essential for implementing conditional logic and loops to handle different scenarios.

variables

In Python, a variable is a name that refers to a value stored in the computer’s memory. It acts as a container to store data of various types. You can think of variables as labeled storage locations that hold values.

Here’s an example that demonstrates the use of variables in Python:

python code:

# Assigning values to variables

name = "John"

age = 25

height = 1.75

is_student = True

# Printing the values stored in variables

print("Name:", name)

print("Age:", age)

print("Height:", height)

print("Is Student:", is_student)

In this example, we declare and assign values to four different variables: name, age, height, and is_student. The name variable stores a string value “John”, the age variable stores an integer value 25, the height variable stores a float value 1.75, and the is_student variable stores a boolean value True.

We then use the print() function to output the values stored in these variables.

The output will be:

output:

Name: John

Age: 25

Height: 1.75

Is Student: True

Variables in Python are dynamically typed, meaning you don’t need to explicitly declare their types. The type of a variable is determined based on the value assigned to it. You can assign new values to variables, and their types can change dynamically during the execution of a program.