Python Imp
Python Imp
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").
def my_function():
pass # Function defined but not implemented yet
# Extract a substring
print(text[0:6]) # Output: Python
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
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!"
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.
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
Examples
python
Copy code
s = "Hello" # str
lst = [1, 2, 3] # list
tpl = (4, 5, 6) # tuple
rng = range(3) # range
Examples
python
Copy code
d = {"name": "Alice", "age": 25}
print(type(d)) # Output: <class 'dict'>
print(d["name"]) # Output: Alice
Examples
python
Copy code
s = {1, 2, 3} # set
fs = frozenset([4, 5, 6]) # frozenset
Examples
python
Copy code
a = True
b = False
6. NoneType
The NoneType represents the absence of a value or a null value.
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.
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, ...)
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 = []
numbers = [1, 2, 3, 4, 5]
2. Accessing Elements
print(numbers[0]) # Output: 10
print(numbers[-1]) # Output: 40
2. extend(iterable) – Adds all items of an iterable (like another list) to the end of the list.
5. pop(index) – Removes and returns the item at the given index (defaults to the last item).
# Initialize a list
fruits = ["apple", "banana", "cherry"]
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
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.
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)
# 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)
# 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
# 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.
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'])
# 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
Unpickling is the process of loading or restoring a previously pickled (serialized) object back into
its original Python form.
import pickle
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.
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.
import csv
#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="").
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
self.attribute1 = attribute1
self.attribute2 = attribute2
# Method
def method_name(self):
# Do something
Example:
class Person:
# Constructor
self.name = name
self.age = age
def greet(self):
print(person1.age) # Output: 30
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.
Example:
python
Copy code
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")
def speak(self):
print("Dog barks")
dog = Dog()
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:
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
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")
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.
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.
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.
plt.pie(sizes, labels=labels)
plt.title('Market Share')
plt.show()
o Use Case: Line charts, bar charts, scatter plots, histograms, etc.
o Example:
plt.show()
2. Seaborn:
o Use Case: Advanced statistical plots like heatmaps, pair plots, and violin plots.
o Example:
import seaborn as sns
3. Plotly:
o Example:
import plotly.express as px
df = px.data.iris()
fig.show()
Random Walk
A random walk is a mathematical concept that describes a sequence of steps, where each step is
determined randomly.
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.
Computer Science: Used in algorithms and simulations, such as Monte Carlo methods.
# 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
# Parameters
steps = 1000
x = np.zeros(steps)
y = np.zeros(steps)
Complexity Can represent complex Simple, flat structure Can represent complex, nested data
Feature JSON CSV XML
data 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)
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.