Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python

Uploaded by

myprojectai9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python

Uploaded by

myprojectai9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

Conditional Statements (if, elif, else)

Conditional statements are used to execute certain blocks of code based on logical conditions.

 if: Executes a block if the condition is True.

 elif (else if): Used to test multiple expressions for True.

 else: Executes if all preceding conditions are False.

➤ Syntax:

python

if condition:

# code block

elif another_condition:

# another block

else:

# fallback block

These constructs are fundamental for flow control in any decision-making logic.

2. Looping Constructs

Loops allow repetitive execution of a block of code.

 for Loop

Used for iterating over a sequence such as a list, tuple, or string.

Example:

for i in range(5):

print(i)

 while Loop

Repeats a block of code as long as a condition is true.

Example:

i=0

while i < 5:

print(i)
i += 1

 Nested Loops

A loop within a loop. Useful in multidimensional data processing.

Example:

for i in range(3):

for j in range(2):

print(i, j)

3. Functions and Parameters

Functions are blocks of reusable code that perform a specific task.

 Definition: Using the def keyword.

 Parameters: Variables defined in the function header.

 Arguments: Actual values passed to functions.

Syntax:

def function_name(parameters):

# function body

Example:

def greet(name):

print("Hello", name)

4. Return Statements

The return statement is used to send results back to the caller.

➤ Purpose:

 Exit the function.

 Optionally pass data back.

Example:

def add(a, b):

return a + b

You can also return multiple values as a tuple.


5. Lambda Functions and Higher-Order Functions

Lambda Functions

Anonymous functions defined using the lambda keyword. Used for short operations.

Syntax:

lambda arguments: expression

Example:

square = lambda x: x * x

🔹 Higher-Order Functions

Functions that take other functions as arguments or return them.

Examples:

 map(): Apply a function to all items in a sequence.

 filter(): Filter items based on a condition.

 reduce() (from functools): Apply rolling computation.

6. Recursion and Function Scope

Recursion

A function calling itself to solve sub-problems.

Example:

def factorial(n):

if n == 1:

return 1

return n * factorial(n - 1)

Important: Must include a base case to stop recursion.

Function Scope

Scope determines the accessibility of variables.

 Local Scope: Inside a function.

 Global Scope: Outside all functions.


LEGB Rule:

1. Local

2. Enclosing

3. Global

4. Built-in

7. Built-in Functions and Custom Function Creation

Built-in Functions

Predefined functions that Python provides.

Common examples:

 print(), input(), len(), type(), sum(), max(), min()

Example:

print(len("Python")) # Output: 6

Custom Functions

User-defined functions for specific tasks.

Syntax:

def my_function():

# code

Python Data Structures & Functional Operations

1. Lists: Creation, Manipulation & Methods

➤ What is a List?

A list is a mutable, ordered collection of items. It can contain elements of different data types.

➤ List Creation:

my_list = [1, 2, 3, "hello", 5.5]

➤ List Manipulation:

 Access: my_list[0] – returns first element

 Update: my_list[1] = 10

 Delete: del my_list[2] or my_list.remove(value)


 Common List Methods:
1.Adds x
append(x) to the end
of the list
insert(i, x)
2.Inserts x
at index i
3.Removes
pop() and returns
last item
4.Removes
remove(x)
first
occurrence
of x
5.Sorts the
sort()
list in
ascending
order
6.Reverses
reverse() the list in
place
7.Adds all
extend()
elements
from
another list

2. Tuples: Immutable Collections and Use Cases


What is a Tuple?
A tuple is an immutable, ordered collection. Once defined, its elements cannot be changed.
Tuple Creation:
my_tuple = (1, 2, 3)
 Use () or tuple() to define.
 A single-item tuple: (1,) — comma is mandatory.
Use Cases:
 Representing fixed data (e.g., coordinates, RGB values).
 Can be used as dictionary keys if elements are immutable.
 Slightly faster than lists due to immutability.

3. Sets: Unique Data Handling & Operations


What is a Set?
A set is an unordered, mutable collection of unique elements.
Set Creation:
python
CopyEdit
my_set = {1, 2, 3, 3} # duplicates are removed
Common Set Operations:
Operation Syntax
Union `A
Intersection A & B or A.intersection(B)
Difference A-B
Symmetric Diff A ^ B
Use Cases:
 Removing duplicates
 Membership testing (x in set)
 Set theory applications

4. Dictionaries: Key-Value Pair Manipulation


What is a Dictionary?
A dictionary is a mutable, unordered collection of key-value pairs.
Dictionary Creation:
my_dict = {"name": "Alice", "age": 25}
Access & Modify:
 my_dict["name"] – Access value
 my_dict["age"] = 26 – Modify
 my_dict["city"] = "NY" – Add new key-value pair
Common Dictionary Methods:
Method Description
get(key) Returns value or None if key is absent
keys() Returns all keys
values() Returns all values
items() Returns key-value pairs as tuples
update() Updates dictionary with another dict
pop(key) Removes item with given key

5. List Comprehensions and Dictionary Comprehensions


List Comprehensions:
A concise way to create lists using a single line.
python
CopyEdit
squares = [x**2 for x in range(5)]
Dictionary Comprehensions:
Used to construct dictionaries dynamically.
python
CopyEdit
squared_dict = {x: x**2 for x in range(5)}
With Conditionals:
python
CopyEdit
even_squares = [x**2 for x in range(10) if x % 2 == 0]

6. Sorting, Filtering, and Mapping Functions


 sorted() Function:
Returns a new sorted list from an iterable.
sorted_list = sorted([5, 2, 3])
 filter() Function:
Filters elements based on a condition (function returning True/False).
evens = list(filter(lambda x: x % 2 == 0, range(10)))
 map() Function:
Applies a function to every item in an iterable.
squares = list(map(lambda x: x**2, range(5)))

*****************************************************************************

Python File Operations, Exception Handling, and Debugging


1. Reading and Writing Files (Text, CSV, JSON, Excel)

Text Files:

 Use the built-in open() function.

 Modes: 'r' (read), 'w' (write), 'a' (append), 'rb', 'wb' (binary modes).

 Always use with for safer file handling (auto-closes files).

Example:

with open('file.txt', 'r') as f:

content = f.read()

CSV Files:

 Use the csv module for reading and writing tabular data.

 Rows are read as lists or written from lists.

Example:

import csv

with open('data.csv', 'r') as f:

reader = csv.reader(f)

for row in reader:

print(row)

JSON Files:

 Use the json module to read/write structured data.

 Works with dictionaries and lists.

Example:

import json

with open('data.json') as f:

data = json.load(f)

Excel Files:

 Use the openpyxl module or pandas for reading/writing .xlsx files.

Example using pandas:


import pandas as pd

df = pd.read_excel('file.xlsx')

2. Working with os and shutil Modules

os Module:

Provides functions for interacting with the operating system.

Common Functions:

 os.getcwd() – current working directory

 os.listdir() – list files in a directory

 os.rename(old, new) – rename file/folder

 os.remove(file) – delete a file

 os.path.exists(path) – check existence

3. Exception Handling using try-except-finally

Purpose:

Used to manage errors during program execution and prevent crashes.

Syntax:

try:

# risky code

except ValueError:

# handle ValueError

except Exception as e:

# handle other exceptions

finally:

# code that always runs

finally Block:

Used for cleanup operations like closing a file or database connection.

4. Raising Custom Exceptions

raise Statement:
Used to throw an exception manually.

Example:

if age < 0:

raise ValueError("Age cannot be negative")

Custom Exception Class:

You can define your own exceptions by subclassing Exception.

class MyError(Exception):

pass

raise MyError("This is a custom error")

5. Logging in Python and Debugging Techniques

Logging:

Better than print statements for tracing program execution and debugging.

Example:

import logging

logging.basicConfig(level=logging.INFO)

logging.info("Program started")

Log Levels:

 DEBUG – detailed information

 INFO – confirmation messages

 WARNING – something unexpected happened

 ERROR – due to a serious issue

 CRITICAL – serious error, program may not continue

1. Classes and Objects

 Class: A class is a blueprint for creating objects. It defines attributes (data) and methods (functions)
that are common to all objects of that type.

 Object: An object is an instance of a class. It represents a real-world entity with attributes and
behaviors.
Example:

class Dog:

def bark(self):

print('Woof')

# Creating an object (instance) of the Dog class

dog1 = Dog()

dog1.bark() # Output: Woof

2. Instance and Class Variables

 Instance Variables: These are variables defined inside the constructor (__init__) using self keyword
and are specific to each object (instance) of the class.

 Class Variables: These are shared across all instances of the class. They are declared inside the class
but outside of any method.

Example:

class Car:

wheels = 4 # Class variable (shared by all instances)

def __init__(self, color):

self.color = color # Instance variable (specific to each object)

# Creating two Car objects

car1 = Car("Red")

car2 = Car("Blue")

print(car1.color) # Output: Red

print(car2.color) # Output: Blue

print(car1.wheels) # Output: 4 (shared class variable)

3. Constructors (__init__ method)

The __init__ method is a special method in Python, known as a constructor. It is automatically invoked
when a new object of the class is created. It is used to initialize the attributes of the object.

Example:

class Person:
def __init__(self, name, age):

self.name = name

self.age = age

# Creating an object

person1 = Person("Alice", 25)

print(person1.name) # Output: Alice

print(person1.age) # Output: 25

4. Inheritance: Single, Multiple, Multilevel, Hierarchical

 Inheritance: Inheritance allows a class to inherit methods and attributes from another class.

Types of Inheritance:

 Single Inheritance: A class inherits from a single base class.

 Multiple Inheritance: A class inherits from more than one base class.

 Multilevel Inheritance: A class inherits from another class, which is already derived from a third
class.

 Hierarchical Inheritance: Multiple classes inherit from a single base class.

Example:

Single Inheritance:

class Animal:

def speak(self):

print("Animal speaking")

class Dog(Animal):

def bark(self):

print("Woof")

dog = Dog()

dog.speak() # Inherited method

dog.bark() # Child class method

Multiple Inheritance:

class Animal:
def speak(self):

print("Animal speaking")

class Dog:

def bark(self):

print("Woof")

class DogAnimal(Dog, Animal):

pass

dog_animal = DogAnimal()

dog_animal.speak() # Inherited from Animal class

dog_animal.bark() # Inherited from Dog class

5. Polymorphism and Method Overriding

 Polymorphism: Polymorphism refers to the ability of a single function or method to behave


differently depending on the context. It allows different classes to have methods with the same
name but different implementations.

 Method Overriding: Method overriding is the process of redefining a method in a derived class that
already exists in the base class, allowing for specialized behavior in the derived class.

Example:

class Animal:

def sound(self):

print("Some generic animal sound")

class Dog(Animal):

def sound(self):

print("Bark")

# Demonstrating Polymorphism and Method Overriding

animal = Animal()

dog = Dog()

animal.sound() # Output: Some generic animal sound

dog.sound() # Output: Bark


6. Encapsulation and Private Variables

 Encapsulation: Encapsulation is the concept of restricting access to some of the object's attributes
or methods to protect the object’s internal state. This is achieved by using private variables and
methods.

 Private Variables: Variables that are meant to be inaccessible from outside the class are prefixed
with double underscores (__). These variables can still be accessed using special methods, but it's
not recommended.

Example:

class Account:

def __init__(self):

self.__balance = 0 # Private variable

def deposit(self, amount):

self.__balance += amount

def get_balance(self):

return self.__balance

# Creating an Account object

account = Account()

account.deposit(1000)

print(account.get_balance()) # Output: 1000

Accessing Private Variable:

# Direct access to private variable will result in an error

# print(account.__balance) # AttributeError: 'Account' object has no attribute '__balance'

You can still access it indirectly using getter methods like get_balance()

You might also like