0% found this document useful (0 votes)
3 views

Python Imp

The document covers fundamental concepts of Python programming, including keywords, data types, control flow statements, functions, and operators. It explains the importance of indentation, type conversion, and different types of arguments in functions. Additionally, it introduces advanced topics like frozensets and provides examples for clarity.

Uploaded by

jaish.2805
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 Imp

The document covers fundamental concepts of Python programming, including keywords, data types, control flow statements, functions, and operators. It explains the importance of indentation, type conversion, and different types of arguments in functions. Additionally, it introduces advanced topics like frozensets and provides examples for clarity.

Uploaded by

jaish.2805
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/ 35

Unit - 1

1. Keywords:
Keywords are reserved words in a programming language that have a predefined
meaning. These words cannot be used as variable names or identifiers.
For example, in Python, if, while, for, and return are keywords.
#To Print list of keywords:
import keyword print(keyword.kwlist).

2. Data Types:
Data types define the kind of values a variable can hold, such as integers, floating-
point numbers, strings, and booleans.
For example, in Python, int represents integers (5), float represents decimals (5.2),
and str represents strings ("hello").

3. Indentation and Comments:


Indentation in Python is used to define the structure of code blocks (like functions
and loops), while comments are used to explain the code and are ignored by the
interpreter.
For example:
# This is a comment
if x > 0:
print("Positive number") # Indentation shows code structure.

4. Why Python is Dynamically and Strongly Typed:


Python is called dynamically typed because you don’t need to declare the data type
of variables; the type is determined at runtime. It is strongly typed because once a
variable is assigned a type, you can't perform operations on incompatible types.
For example, you cannot add a string and an integer in Python:
x = "Hello"
y=5
print(x + y) # This would result in an error

5. Break and Continue Statement and pass:


The break statement exits a loop prematurely, while continue skips the current
iteration and continues with the next.
In Python, the pass statement is a placeholder that does nothing when executed. It is
used when a block of code is syntactically required but no action is needed, such as
when defining an empty function, class, or loop, or when you plan to add code later.
Example:
for i in range(5):
if i == 3:
break # Loop breaks when i is 3
print(i)
for i in range(5):
if i == 3:
continue # Skips printing 3
print(i)

def my_function():
pass # Function defined but not implemented yet

6. Slicing and Indexing


Slicing is a technique in Python to extract a portion (substring, sublist, or subtuple) of
a sequence such as strings, lists, tuples, or other iterable objects.
Syntax:
sequence[start:stop:step].
Example:
text = "PythonProgramming"

# Extract a substring
print(text[0:6]) # Output: Python

# Omitting start and stop


print(text[:6]) # Output: Python (start defaults to 0)
print(text[6:]) # Output: Programming (stop defaults to the end)

# Reverse the string


print(text[::-1]) # Output: gnimmargorPnohtyP

Indexing is used to access individual elements of a sequence, such as strings, lists,


tuples, or other iterable objects. Each element in the sequence is assigned a unique
index, allowing direct retrieval of values.

Positive Indexing Starts from 0, moves left to right.

Negative Indexing Starts from -1, moves right to left.

Syntax:
sequence[index]
Example:
text = "Python"

# Positive indexing
print(text[0]) # Output: P
print(text[5]) # Output: n
# Negative indexing
print(text[-1]) # Output: n
print(text[-6]) # Output: P

# Access out-of-range index (error)


# print(text[10]) # IndexError

7. Functions and Strings


A function is a reusable block of code that performs a specific task. Python provides
built-in functions to work with strings as well as the ability to define custom
functions.
Built-in Function

String Methods
String methods are functions called on a string object. They can be used for
transformations, searching, or formatting.
Example:
text = " Hello, Python! "

# Case conversion
print(text.upper()) # Output: " HELLO, PYTHON! "
print(text.lower()) # Output: " hello, python! "
print(text.strip()) # Output: "Hello, Python!"

# Searching and counting


print(text.find("Python")) # Output: 8
print(text.count("o")) # Output: 2

# Replacing and splitting


print(text.replace("Python", "World")) # Output: " Hello, World! "
print(text.split(",")) # Output: [' Hello', ' Python!']
# Joining
words = ["Join", "with", "spaces"]
print(" ".join(words)) # Output: "Join with spaces"

Main Questions
Control flow statements.
1.Sequential Control Flow Statements: This refers to the line by line execution, in which the
statements are executed sequentially, in the same order in which they appear in the
program.
2. Decision Control Flow Statements: Depending on whether a condition is True or False,
the decision
structure may skip the execution of an entire block of statements or even execute one block
of
statements instead of other (if, if…else and if…elif…else).
3. Loop Control Flow Statements: This is a control structure that allows the execution of a
block of
statements multiple times until a loop termination condition is met (for loop and while
loop). LoopControl Flow Statements are also called Repetition statements or Iteration
statements
Nested if Statement
In some situations, you have to place an if statement inside another statement. An if
statement that contains another if statement either in its if block or else block is called a
Nested if statement
Example, Program to Check If a Given Year Is a Leap Year
The code you've written has the right structure for checking leap years, but the indentation
needs to be corrected for it to work properly. Here's the corrected version:
For example
year = int(input('Enter a year: '))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f'{year} is a Leap Year')
else:
print(f'{year} is not a Leap Year')
else:
print(f'{year} is a Leap Year')
else:
print(f'{year} is not a Leap Year')
If we want to execute a group of statements iteratively until some condition false,then we
should go for while loop. The while loop starts with the while keyword and ends with a
colon.
Example 2:
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum)

The for loop starts with for keyword and ends with a colon. The first item in the sequence
gets assigned to the iteration variable iteration_variable. Here, iteration_variable can be any
valid variable name. Then the statement block is executed. This process of assigning items
from the sequence to the iteration_variable and then executing the statement continues
until all the items in the sequence are
completed.
range([start ,] stop [, step])
Both start and step arguments are optional and the range argument value should always be
an integer.
start → value indicates the beginning of the sequence. If the start argument is not
specified, then the sequence of numbers start from zero by default.
stop → Generates numbers up to this value but not including the number itself.
step → indicates the difference between every two consecutive numbers in the
sequence. The step value can be both negative and positive but not zero.
Example:
print("Only ''stop'' argument value specified in range function")
2. for i in range(3):
3. print(f"{i}")
4. print("Both ''start'' and ''stop'' argument values specified in range function")
5. for i in range(2, 5):
6. print(f"{i}")
7. print("All three arguments ''start'', ''stop'' and ''step'' specified in range function")
8. for i in range(1, 6, 3):
9. print(f"{i}").

Type conversion.
Type conversion refers to the process of converting a value from one data type to another.
Python supports both implicit type conversion (automatic) and explicit type conversion
(manual using functions).
1. Implicit Type Conversion (Automatic Conversion):
This happens when Python automatically converts one data type to another during an
operation. For example, when an integer is added to a float, Python converts the integer to a
float to avoid errors.
x=5 # Integer
y = 2.5 # Float
result = x + y # Python converts x to float
print(result) # Output: 7.5 (float)
Key Points
 Happens automatically.
 Maintains data integrity.
 Common in operations involving integers and floats.

2. Explicit Type Conversion (Type Casting):


Explicit conversion is when you manually convert one data type to another using functions
like int(), float(), or str().
x = "10" # String
y=3
result = int(x) + y # Convert string to integer explicitly
print(result) # Output: 13

Operators in python.
Operators are symbols, such as +, –, =, >, and <, that perform certain mathematical or logical
operation to manipulate data values and produce a result based on some rules. An operator
manipulates the data values called operands.

For example,
1. >>> 10+35
45
2. >>> −10+35
25
3. >>> 4*2
8
4. >>> 4**2
16
Assignment Operators
Assignment operators are used for assigning the values generated after evaluating the right
operand
to the left operand. Assignment operation always works from right to left. Assignment
operators are
either simple assignment operator or compound assignment operators. Simple assignment is
done
with the equal sign (=) and simply assigns the value of its right operand to the variable on
the left. For
example,
>>> x = 5
>>> x = x + 1
>>> x
6.
For example,
1. >>>10 == 12
False
2. >>>10 != 12
True
3. >>>10 < 12
True
4. >>>10 > 12
False

Logical Operators
The logical operators are used for comparing or negating the logical values of their operands
and to return the resulting logical value. The values of the operands on which the logical
operators operate evaluate to either True or False. The result of the logical operator is
always a Boolean value, True or False. TABLE shows all the logical operators.

For example,
1. >>> True and False
False
2. >>> True or False
True
3. >>> not(True) and False
False
4. >>> not(True and False)
True
5. >>> (10 < 0) and (10 > 2)
False

Bitwise Operators
Bitwise operators treat their operands as a sequence of bits (zeroes and ones) and perform
bit by bit operation. For example, the decimal number ten has a binary representation.
Types of arguments.
 Positional Arguments:
These are the most common type of arguments passed to a function in the correct
order. The position of arguments matters because they are matched based on the
order in which they are defined in the function.
 Keyword Arguments:
These arguments are passed by explicitly specifying the parameter names in the
function call. The order doesn’t matter, as the names of the parameters are explicitly
stated.
 Default Arguments:
In Python, functions can have default parameter values. If no argument is provided
for a parameter, its default value will be used.
 Variable-length Arguments:
These allow you to pass a variable number of arguments to a function. They are
defined using *args (for non-keyword arguments) and **kwargs (for keyword
arguments).

For Example:
# Function with different types of arguments
def my_function(a, b, c=10, *args, **kwargs):
print("Positional argument a:", a)
print("Positional argument b:", b)
print("Default argument c:", c)
print("Variable-length args:", args)
print("Keyword arguments:", kwargs)
# Calling the function with different types of arguments
my_function(5, 15, 20, 25, 30, name="Alice", age=30)

# Output:
# Positional argument a: 5
# Positional argument b: 15
# Default argument c: 20
# Variable-length args: (25, 30)
# Keyword arguments: {'name': 'Alice', 'age': 30}

DataTypes:
In Python, data types specify the type of data a variable can hold. Python is dynamically
typed, meaning you do not need to declare the type of a variable explicitly. Python
automatically assigns the type based on the value assigned.
Categories of Data Types
Python data types can be divided into the following categories:
1. Standard Data Types
o Numeric
o Sequence
o Mapping
o Set
o Boolean
2. Special Data Types
o NoneType
o File Objects

1. Numeric Data Types


Numeric types represent numerical values.
Type Description Example
int Represents integers (whole numbers). 10, -5
float Represents floating-point numbers (decimal values). 3.14, -0.5
complex Represents complex numbers with a real and imaginary part. 2+3j, 1-4j
Examples
python
Copy code
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex

print(type(a)) # Output: <class 'int'>


print(type(b)) # Output: <class 'float'>
print(type(c)) # Output: <class 'complex'>
2. Sequence Data Types
Sequence types represent ordered collections of items.

Type Description Example

str Represents a sequence of characters. "Hello", 'Python'

list Represents a mutable sequence of items. [1, 2, 3], ['a', 'b']

tuple Represents an immutable sequence of items. (1, 2, 3), ('a', 'b')

range Represents a sequence of numbers. range(5) (0 to 4)

Examples
python
Copy code
s = "Hello" # str
lst = [1, 2, 3] # list
tpl = (4, 5, 6) # tuple
rng = range(3) # range

print(type(s)) # Output: <class 'str'>


print(type(lst)) # Output: <class 'list'>
print(type(tpl)) # Output: <class 'tuple'>
print(type(rng)) # Output: <class 'range'>

3. Mapping Data Type


The mapping type in Python is dict, which represents key-value pairs.

Type Description Example

dict Stores data in key-value pairs. {"name": "Alice", "age": 25}

Examples
python
Copy code
d = {"name": "Alice", "age": 25}
print(type(d)) # Output: <class 'dict'>
print(d["name"]) # Output: Alice

4. Set Data Types


Set types represent collections of unique, unordered items.
Type Description Example

set Mutable, unordered collection of unique elements. {1, 2, 3}

frozenset Immutable version of set. frozenset({1, 2, 3})

Examples
python
Copy code
s = {1, 2, 3} # set
fs = frozenset([4, 5, 6]) # frozenset

print(type(s)) # Output: <class 'set'>


print(type(fs)) # Output: <class 'frozenset'>

5. Boolean Data Type


Boolean values represent True or False.

Type Description Example

bool Represents binary values (True or False). True, False

Examples
python
Copy code
a = True
b = False

print(type(a)) # Output: <class 'bool'>


print(5 > 3) # Output: True
print(5 < 3) # Output: False

6. NoneType
The NoneType represents the absence of a value or a null value.

Type Description Example

NoneType Represents a null or no value. None

Examples
python
Copy code
x = None
print(type(x)) # Output: <class 'NoneType'>
Unit 2

Frozen Set
In Python, a frozenset is an immutable version of a set. Unlike regular sets, which are mutable and
allow elements to be added or removed, a frozenset cannot be modified after creation.
Creating a Frozenset
You create a frozenset using the frozenset() function, passing any iterable (like a list, tuple, or set) as
an argument.
Key Characteristics
1. Immutable: Once created, elements cannot be added or removed.
2. Unordered: Like sets, the order of elements is not guaranteed.
3. Unique Elements: Duplicate elements are automatically removed.
4. Hashable: Can be used as keys in dictionaries or elements in other sets.

# Creating a frozenset from a list


frozen_fruits = frozenset(["apple", "banana", "cherry"])
print(frozen_fruits) # Output: frozenset({'apple', 'banana', 'cherry'})

# Creating a frozenset from a set


normal_set = {"apple", "banana", "cherry"}
frozen_fruits = frozenset(normal_set).

Zip Function
The zip() function in Python is a built-in function that allows you to combine multiple iterables (like
lists, tuples, or strings) into a single iterable of tuples. It pairs elements from each iterable based on
their position.
 Parameters: Accepts one or more iterables (lists, tuples, sets, dictionaries, etc.).
 Return: An iterator of tuples.

Syntax:
zip(iterable1, iterable2, ...)

Examples of Using zip()


1. Basic Example with Two Lists
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 88]

# Using zip to pair names with scores


combined = zip(names, scores)
print(list(combined)) # Output: [('Alice', 85), ('Bob', 90), ('Charlie', 88)].

List In Python
In Python, a list is a mutable, ordered collection that can store elements of any type, such as integers,
strings, floats, other lists, or even custom objects. Lists are versatile and powerful, making them one
of the most commonly used data structures in Python.
1. Creating a List

Lists are created using square brackets [], with elements separated by commas.

# Empty list

empty_list = []

# List with elements

numbers = [1, 2, 3, 4, 5]

mixed = [1, "two", 3.0, [4, 5]]

2. Accessing Elements

You can access elements by their index, with indexing starting at 0.

numbers = [10, 20, 30, 40]

# Access first element

print(numbers[0]) # Output: 10

# Access last element

print(numbers[-1]) # Output: 40

Here’s a list of commonly used list methods in Python:

1. append(item) – Adds an item to the end of the list.

2. extend(iterable) – Adds all items of an iterable (like another list) to the end of the list.

3. insert(index, item) – Inserts an item at a specific index.

4. remove(item) – Removes the first occurrence of an item.

5. pop(index) – Removes and returns the item at the given index (defaults to the last item).

6. clear() – Removes all items from the list.

7. index(item) – Returns the index of the first occurrence of an item.

8. count(item) – Returns the count of occurrences of an item.

9. sort() – Sorts the list in ascending order.

10. reverse() – Reverses the order of the list.

11. copy() – Returns a shallow copy of the list.

# Initialize a list
fruits = ["apple", "banana", "cherry"]

# 1. append(item) - Add an item to the end of the list


fruits.append("date")
print("After append:", fruits) # ['apple', 'banana', 'cherry', 'date']
# 2. extend(iterable) - Add all items from another list
fruits.extend(["elderberry", "fig", "grape"])
print("After extend:", fruits) # ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']

# 3. insert(index, item) - Insert an item at a specific index


fruits.insert(2, "blueberry")
print("After insert:", fruits) # ['apple', 'banana', 'blueberry', 'cherry', 'date', 'elderberry', 'fig', 'grape']

# 4. remove(item) - Remove the first occurrence of an item


fruits.remove("banana")
print("After remove:", fruits) # ['apple', 'blueberry', 'cherry', 'date', 'elderberry', 'fig', 'grape']

# 5. pop(index) - Remove and return an item at the specified index


popped_fruit = fruits.pop(3)
print("After pop:", fruits) # ['apple', 'blueberry', 'cherry', 'elderberry', 'fig', 'grape']
print("Popped item:", popped_fruit) # 'date'

# 6. clear() - Remove all items from the list


fruits_copy = fruits.copy() # Make a copy to demonstrate clear later
fruits.clear()
print("After clear:", fruits) # []

# Reinitialize for remaining examples


fruits = fruits_copy

# 7. index(item) - Find the index of the first occurrence of an item


index_of_cherry = fruits.index("cherry")
print("Index of 'cherry':", index_of_cherry) # 2

# 8. count(item) - Count occurrences of an item


count_of_fig = fruits.count("fig")
print("Count of 'fig':", count_of_fig) # 1

# 9. sort() - Sort the list in ascending order


fruits.sort()
print("After sort:", fruits) # ['apple', 'blueberry', 'cherry', 'elderberry', 'fig', 'grape']

# 10. reverse() - Reverse the order of the list


fruits.reverse()
print("After reverse:", fruits) # ['grape', 'fig', 'elderberry', 'cherry', 'blueberry', 'apple']

# 11. copy() - Make a shallow copy of the list


fruits_copy = fruits.copy()
print("Copy of fruits:", fruits_copy) # ['grape', 'fig', 'elderberry', 'cherry', 'blueberry', 'apple'].

Set
In Python, a set is an unordered, mutable collection of unique elements. Sets are commonly used
when you need to store distinct items and perform operations like union, intersection, and
difference. Here’s an in-depth look at how sets work, their properties, and commonly used methods.

Creating a Set
Sets are created using curly braces {} or the set() function. Duplicate values are automatically
removed.
python
Copy code
# Creating a set with curly braces
fruits = {"apple", "banana", "cherry", "apple"} # "apple" appears only once

# Creating a set using set() function


numbers = set([1, 2, 3, 4, 4, 5]) # Duplicates are removed

print(fruits) # Output: {'apple', 'banana', 'cherry'}


print(numbers) # Output: {1, 2, 3, 4, 5}

Properties of Sets
1. Unordered: Elements do not maintain any particular order.
2. Mutable: Elements can be added or removed, but the set itself cannot store mutable
elements (like lists or dictionaries).
3. Unique Elements: Each element can appear only once.

Common Set Method


# Initialize two sets
fruits = {"apple", "banana", "cherry"}
more_fruits = {"cherry", "date", "elderberry"}

# 1. add() - Add an element


fruits.add("fig")
print("After add:", fruits) # {'apple', 'banana', 'cherry', 'fig'}

# 2. update() - Add multiple elements


fruits.update(["grape", "honeydew"])
print("After update:", fruits) # {'apple', 'banana', 'cherry', 'fig', 'grape', 'honeydew'}

# 3. remove() - Remove an element


fruits.remove("banana")
print("After remove:", fruits) # {'apple', 'cherry', 'fig', 'grape', 'honeydew'}

# 4. discard() - Remove an element (no error if missing)


fruits.discard("banana") # No error even if "banana" isn't present

# 5. pop() - Remove and return an arbitrary element


popped_item = fruits.pop()
print("Popped item:", popped_item)
print("After pop:", fruits)
# 6. clear() - Clear all elements from the set
fruits.clear()
print("After clear:", fruits) # Output: set()

# Reinitialize fruits for the following examples


fruits = {"apple", "banana", "cherry"}

# 7. union() - Combine two sets


combined = fruits.union(more_fruits)
print("Union:", combined) # {'apple', 'banana', 'cherry', 'date', 'elderberry'}

# 8. intersection() - Find common elements


common = fruits.intersection(more_fruits)
print("Intersection:", common) # {'cherry'}

# 9. difference() - Elements in fruits but not in more_fruits


unique_to_fruits = fruits.difference(more_fruits)
print("Difference:", unique_to_fruits) # {'apple', 'banana'}

# 10. symmetric_difference() - Elements in either set, but not both


sym_diff = fruits.symmetric_difference(more_fruits)
print("Symmetric Difference:", sym_diff) # {'apple', 'banana', 'date', 'elderberry'}

# 11. issubset() - Check if a set is a subset of another


subset_check = {"apple"}.issubset(fruits)
print("Is subset:", subset_check) # True

# 12. issuperset() - Check if a set is a superset of another


superset_check = fruits.issuperset({"apple"})
print("Is superset:", superset_check) # True

# 13. copy() - Make a shallow copy of the set


fruits_copy = fruits.copy()
print("Copy of fruits:", fruits_copy) # {'apple', 'banana', 'cherry'}

Tuple:
A tuple is an ordered, immutable collection of elements. Tuples are similar to lists, but unlike lists,
they cannot be modified after creation. This makes tuples useful in situations where you want to
ensure that the data remains constant.
Key Characteristics of Tuples
1. Ordered: The elements in a tuple have a defined order.
2. Immutable: Once a tuple is created, its elements cannot be modified, added, or removed.
3. Allow Duplicates: Tuples can contain duplicate values.
4. Heterogeneous: A tuple can store elements of different data types (e.g., integers, strings,
lists).
5. Indexable: Elements can be accessed using an index, just like lists.
6. Hashable: Since tuples are immutable, they can be used as keys in dictionaries or as
elements in sets.
Syntax:
tuple_name = (element1, element2, element3, ...)

Example:
# 1. Creating a Tuple
person = ("Alice", 25, "Engineer", 5.5)
print(person) # Output: ('Alice', 25, 'Engineer', 5.5)

# 2. Accessing Tuple Elements


print(person[0]) # Output: Alice (Accessing by index)
print(person[-1]) # Output: 5.5 (Accessing last element using negative index)

# 3. Slicing a Tuple
print(person[1:3]) # Output: (25, 'Engineer') (Slicing from index 1 to 2)
print(person[:2]) # Output: ('Alice', 25) (Slicing from the start to index 1)

# 4. Tuple with Single Element


single_element_tuple = (10,)
print(single_element_tuple) # Output: (10)
print(type(single_element_tuple)) # Output: <class 'tuple'>

# 5. Concatenating Tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2
print(combined) # Output: (1, 2, 3, 4, 5, 6)

# 6. Repeating Tuples
repeated = tuple1 * 3
print(repeated) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

# 7. Membership Test
print(3 in tuple1) # Output: True
print(7 in tuple1) # Output: False

# 8. Counting Occurrences and Finding Index


tuple3 = (1, 2, 2, 3, 2, 4)
print(tuple3.count(2)) # Output: 3 (Count how many times 2 appears)
print(tuple3.index(3)) # Output: 3 (Find the index of the first occurrence of 3)

# 9. Tuple Unpacking
name, age, job, height = person
print(name) # Output: Alice
print(age) # Output: 25
print(job) # Output: Engineer
print(height) # Output: 5.5
# 10. Nested Tuple
nested_tuple = (1, 2, (3, 4), 5)
print(nested_tuple[2]) # Output: (3, 4) (Accessing the nested tuple)
print(nested_tuple[2][1]) # Output: 4 (Accessing an element from the nested tuple)

# 11. Immutability
# person[1] = 30 # This would raise a TypeError since tuples are immutable.

Dictionary:
A dictionary is an unordered collection of key-value pairs. In Python, dictionaries are defined using
curly braces {} and consist of keys and values, where each key is unique and associated with a value.

Key Characteristics of Dictionaries


1. Unordered: Dictionaries do not maintain the order of elements (though as of Python 3.7+,
they maintain insertion order).
2. Mutable: You can modify, add, or remove key-value pairs after the dictionary is created.
3. Key-Value Pairs: Each element in a dictionary is a pair consisting of a key and a corresponding
value.
4. Unique Keys: Keys must be unique, but values can be duplicated.
5. Indexing by Key: You access the values in a dictionary by referencing the key.
Syntax:
my_dict = {
key1: value1, key2: value2, key3: value3,
}

Example:

person = {
"name": "Alice",
"age": 25,
"job": "Engineer"
}

# 1. Getting Keys
keys = person.keys()
print(keys) # Output: dict_keys(['name', 'age', 'job'])

# 2. Getting Values
values = person.values()
print(values) # Output: dict_values(['Alice', 25, 'Engineer'])

# 3. Getting Items (key-value pairs)


items = person.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 25), ('job', 'Engineer')])

# 4. Copying a Dictionary
person_copy = person.copy()
print(person_copy) # Output: {'name': 'Alice', 'age': 25, 'job': 'Engineer'}

# 5. Updating a Dictionary
person.update({"city": "New York", "age": 26})
print(person) # Output: {'name': 'Alice', 'age': 26, 'job': 'Engineer', 'city': 'New York'}

Unit-3

Pickiling
In Python, pickling is a process used for serializing and deserializing objects. Serialization (or
"pickling") involves converting a Python object into a byte stream so that it can be saved to a file or
transmitted over a network.
import pickle

# Example complex data structure


project_data = {
"portfolio": ["project1", "project2"],
"contact_info": {"email": "[email protected]", "phone": "123-456-7890"},
"user_preferences": {"theme": "dark", "notifications": True},
}

# Serialize and save data


with open("project_data.pkl", "wb") as file:
pickle.dump(project_data, file)

# Load the data later


with open("project_data.pkl", "rb") as file:
loaded_data = pickle.load(file)

print("Loaded Data:", loaded_data).

Unpickling is the process of loading or restoring a previously pickled (serialized) object back into
its original Python form.
import pickle

# Example of pickling to a byte stream


original_data = {"name": "Alice", "age": 25}
pickled_data = pickle.dumps(original_data)

# Unpickling from the byte stream


unpickled_data = pickle.loads(pickled_data)
print(unpickled_data) # Output: {'name': 'Alice', 'age': 25}.

Types of files:
In Python, files can be categorized based on their format or the way they are used. Here are some of
the most common types of files that you can work with in Python:
1. Text Files
 Description: These are files that contain human-readable text. Each line is typically
terminated with a newline character (\n or \r\n depending on the operating system).
 Extensions: .txt, .csv, .log, .json, etc.
 Example: Reading and writing to a text file.

# Writing to a text file


with open("example.txt", "w") as file:
file.write("Hello, this is a text file.\n")
file.write("This is the second line.")

# Reading from a text file


with open("example.txt", "r") as file:
content = file.read()
print(content)

2. Binary Files
 Description: Binary files store data in a binary format, which may not be human-readable.
These files can contain any type of data, such as images, executable programs, or audio files.
 Extensions: .bin, .jpg, .png, .exe, .mp3, .pdf, etc.
 Example: Reading and writing to a binary file.

# Writing to a binary file


with open("image.jpg", "rb") as binary_file:
binary_data = binary_file.read()

# Writing binary data to a new file


with open("copy_image.jpg", "wb") as copy_file:
copy_file.write(binary_data)

3. CSV Files (Comma-Separated Values)


 Description: CSV files are a common format used for storing tabular data in plain text. Each
line represents a row, and the values are separated by commas (or other delimiters like
semicolons).
 Extensions: .csv
 Example: Reading and writing CSV files using Python's csv module.

import csv

# Writing to a CSV file


with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 30, "New York"])
writer.writerow(["Bob", 25, "Los Angeles"])

# Reading from a CSV file


with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)

4. JSON Files (JavaScript Object Notation)


 Description: JSON files are used to store structured data in a human-readable format. It is
widely used for data interchange between different systems.
 Extensions: .json
 Example: Reading and writing to a JSON file using Python's json module.
import json

# Writing to a JSON file


data = {"name": "Alice", "age": 30, "city": "New York"}
with open("data.json", "w") as json_file:
json.dump(data, json_file)

# Reading from a JSON file


with open("data.json", "r") as json_file:
data_read = json.load(json_file)
print(data_read)

5. XML Files (Extensible Markup Language)


 Description: XML files are used for storing hierarchical data in a plain text format. It uses tags
to define elements and attributes.
 Extensions: .xml
 Example: Reading and writing XML files using Python's xml.etree.ElementTree module.
import xml.etree.ElementTree as ET

# Writing to an XML file


root = ET.Element("person")
name = ET.SubElement(root, "name")
name.text = "Alice"
age = ET.SubElement(root, "age")
age.text = "30"
tree = ET.ElementTree(root)
tree.write("data.xml")

# Reading from an XML file


tree = ET.parse("data.xml")
root = tree.getroot()
for child in root:
print(child.tag, child.text)

Files and Modes:


Python supports two types of files – text files and binary files. These two file types may look the
same on the surface but they encode data differently. While both binary and text files contain data
stored as a series of bits (binary values of 1s and 0s), the bits in text files represent characters, while
the its in binary files represent custom data.
file_handler = open("Path….")
print("Printing each line in the text file")
for each_line in file_handler:
print(each_line)
file_handler.close()

#Using With
print("Printing each line in text file")
with open("Path…..") as file_handler:
for each_line in file_handler:
print(each_line, end="").

# Write data to file


with open("example.txt", "w") as file:
file.write("This is the first line.\n")
file.write("This is the second line.\n")

# Append data to the same file


with open("example.txt", "a") as file:
file.write("This line is appended.\n")

# Read the contents of the file


with open("example.txt", "r") as file:
content = file.read()
print("File Content:\n", content)

Classes in Python
A class in Python is a blueprint for creating objects (instances). A class defines the properties
(attributes) and behaviors (methods) that the objects created from the class will have.

Syntax:

class ClassName:

# Constructor

def __init__(self, attribute1, attribute2):

self.attribute1 = attribute1

self.attribute2 = attribute2

# Method

def method_name(self):

# Do something

Example:

class Person:

# Constructor

def __init__(self, name, age):

self.name = name

self.age = age

# Method to display information

def greet(self):

print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an object (instance) of the Person class

person1 = Person("Alice", 30)

# Accessing attributes and calling the method

print(person1.name) # Output: Alice

print(person1.age) # Output: 30

person1.greet() # Output: Hello, my name is Alice and I am 30 years old.


2. Object

An object is an instance of a class. Once a class is defined, you can create multiple objects from that
class. Each object has its own set of attributes and methods, but they all share the same structure as
defined by the class.

 Definition: An object is an instance of a class containing attributes (data) and methods


(functions) that define its behavior.

 Example:

python

Copy code

person1 = Person("Alice", 30) # person1 is an object of the Person class

person2 = Person("Bob", 25) # person2 is another object

3. Inheritance

Inheritance is a mechanism in OOP that allows one class (child or subclass) to inherit attributes and
methods from another class (parent or superclass). This promotes code reusability and the creation
of a hierarchy of classes.

 Definition: Inheritance allows a class (child class) to inherit the attributes and methods of
another class (parent class), enabling the child class to reuse, modify, or extend the
functionality of the parent class.

 Example:

python

Copy code

class Animal:

def speak(self):

print("Animal speaks")

class Dog(Animal): # Dog inherits from Animal

def speak(self):

print("Dog barks")

dog = Dog()

dog.speak() # Output: Dog barks


4. Encapsulation

Encapsulation is the concept of wrapping data (attributes) and methods that operate on the data
into a single unit called a class. It also involves restricting access to some of an object's components,
which is typically done by making some attributes or methods private.

 Definition: Encapsulation is the bundling of data and methods that operate on that data into
a single unit and restricting access to some of the object's components to protect the
integrity of the data.

 Example:

python

Copy code

class BankAccount:

def __init__(self, balance):

self.__balance = balance # Private variable

def deposit(self, amount):

self.__balance += amount

def get_balance(self):

return self.__balance

account = BankAccount(1000)

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

# print(account.__balance) # This will raise an AttributeError

5. Polymorphism

Polymorphism allows different classes to have methods with the same name but potentially different
implementations. It enables one interface to be used for different underlying forms (data types),
allowing for flexible and reusable code.

 Definition: Polymorphism is the ability to use the same method name in different classes
with different implementations, allowing objects of different classes to be treated uniformly.

 Example:

python

Copy code
class Animal:

def speak(self):

print("Animal speaks")

class Dog(Animal):

def speak(self):

print("Dog barks")

class Cat(Animal):

def speak(self):

print("Cat meows")

animals = [Dog(), Cat()]

for animal in animals:

animal.speak() # Output: Dog barks, Cat meows

Unit - 4
Data Visualization
Data Visualization is the graphical representation of data and information. By using visual elements
like charts, graphs, and maps, data visualization tools provide an accessible way to see and
understand trends, outliers, and patterns in data.

Common Types of Data Visualizations


1. Bar Chart:
o Usage: Used to compare quantities across different categories.
o Example: Comparing sales across different regions.

import matplotlib.pyplot as plt

categories = ['East', 'West', 'North', 'South']


values = [23, 45, 56, 78]

plt.bar(categories, values)
plt.title('Sales by Region')
plt.xlabel('Region')
plt.ylabel('Sales')
plt.show()

2. Line Chart:
o Usage: Shows trends over time or continuous data.
o Example: Tracking a stock’s price over time.

import matplotlib.pyplot as plt

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']


sales = [10, 20, 15, 30, 40]

plt.plot(months, sales, marker='o')


plt.title('Sales Over Time')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.show()

3. Pie Chart:
o Usage: Displays the proportion of categories as parts of a whole.
o Example: Market share of different products in a company.

import matplotlib.pyplot as plt

labels = ['Product A', 'Product B', 'Product C', 'Product D']


sizes = [40, 25, 20, 15]

plt.pie(sizes, labels=labels)
plt.title('Market Share')
plt.show()

Popular Libraries for Data Visualization in Python


1. Matplotlib:

o Description: A versatile library for creating static, animated, and interactive


visualizations in Python.

o Use Case: Line charts, bar charts, scatter plots, histograms, etc.

o Example:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])

plt.show()

2. Seaborn:

o Description: Built on top of Matplotlib, Seaborn provides a high-level interface for


drawing attractive and informative statistical graphics.

o Use Case: Advanced statistical plots like heatmaps, pair plots, and violin plots.

o Example:
import seaborn as sns

sns.heatmap([[1, 2], [3, 4]], annot=True)

3. Plotly:

o Description: A powerful library for creating interactive visualizations, including 3D


plots and dashboards.

o Use Case: Interactive graphs for web applications, dashboards, or presentations.

o Example:

import plotly.express as px

df = px.data.iris()

fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")

fig.show()

Random Walk
A random walk is a mathematical concept that describes a sequence of steps, where each step is
determined randomly.

Types of Random Walks


1. One-Dimensional Random Walk: In this case, the "walker" moves either left or right along a
line, with each step being independent and random.

2. Two-Dimensional Random Walk: The walker moves randomly in any direction in a two-
dimensional plane (e.g., up, down, left, or right).

3. Multi-Dimensional Random Walk: The walker moves randomly in more than two
dimensions, such as in three-dimensional space.

Applications of Random Walks

 Physics: Simulating the movement of particles in a fluid (Brownian motion).

 Finance: Modeling stock prices (random walk hypothesis).

 Biology: Tracking the movement of animals or molecules.

 Computer Science: Used in algorithms and simulations, such as Monte Carlo methods.

Random Walk in Python (1D and 2D)


1D
import numpy as np
import matplotlib.pyplot as plt

# Parameters
steps = 1000 # Number of steps
walk = np.random.choice([-1, 1], size=steps) # Random steps (either -1 or 1)
position = np.cumsum(walk) # Cumulative sum to get the position at each step

# Plotting the random walk


plt.plot(position)
plt.title("1D Random Walk")
plt.xlabel("Step")
plt.ylabel("Position")
plt.show()
2D
import numpy as np
import matplotlib.pyplot as plt

# Parameters
steps = 1000
x = np.zeros(steps)
y = np.zeros(steps)

# Directions: up, down, left, right


directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]

# Perform the random walk


for i in range(1, steps):
move = directions[np.random.choice(4)] # Randomly choose one of the four directions
x[i] = x[i-1] + move[0]
y[i] = y[i-1] + move[1]

# Plotting the 2D random walk


plt.plot(x, y)
plt.title("2D Random Walk")
plt.xlabel("X Position")
plt.ylabel("Y Position")
plt.show()

Difference between json, csv, xml


Key Differences

Feature JSON CSV XML

Key-value pairs, Flat, tabular (rows and


Structure Tag-based, hierarchical
hierarchical columns)

Supports different data


Supports text-based data and
Data Types types (string, number, All data is string-based
attributes
array, object)

Complexity Can represent complex Simple, flat structure Can represent complex, nested data
Feature JSON CSV XML

data structures

Larger due to key-value Smaller, simple


File Size Larger due to tags and hierarchy
pairs and nested data structure

Human- Easy to read, especially


Very easy to read Readable, but verbose
Readability for nested data

Support for Yes, supports nested


No, flat format Yes, supports nested structures
Hierarchy structures

Data exchange in
Web APIs, configuration Data exchange, document storage,
Use Cases tabular format,
files, data exchange web services
spreadsheets

Easy to parse with built- Easy to parse with built- More complex parsing, requires
Parsing in libraries (e.g., json in libraries (e.g., csv specific parsers (e.g.,
module in Python) module in Python) xml.etree.ElementTree in Python)

1. API (Application Programming Interface)


Definition: An API is a set of rules and protocols that allows one software application to interact with
another. It defines the way that different software components should interact and communicate.

2. Git
Definition: Git is a distributed version control system that helps developers track changes in their
source code during software development. It allows multiple developers to work on the same project
simultaneously without overwriting each other's changes.

3. GitHub
Definition: GitHub is a cloud-based hosting platform for Git repositories. It provides a web interface
for managing Git repositories and offers additional features like issue tracking, pull requests, and
collaborative tools.

You might also like