Python Notes
Python Notes
Python Course..!!
Introduction to Python
Python was created by Guido van Rossum and first released in 1991, It’s a high-level, interpreted
programming language that is used for a wide range of applications such as web development,
data analysis, machine learning, artificial intelligence, automation, data science and many more.
On 16 October 2000, Python 2.0 was released with many new features.
On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.
The present stable version of Python is 3.13.7. It was released on August 14, 2025.
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and multiple
inheritance.
2. Indentation
Indentation is one of the greatest features in python
3. It’s free (open source)
Downloading python and installing python is free and easy
4. It’s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g., Numeric, NumPy, SciPy)
Automatic memory management
5. It’s Portable
Python runs virtually every major platform used today
As long as you have a compaitable python interpreter installed, python programs will run
in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
No intermediate compile
Python Programs are compiled automatically to an intermediate form called byte code,
which the interpreter then reads.
This gives python the development speed of an interpreter without the performance loss
inherent in purely interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it popular.
PYTHON DOWNLOAD AND INSTALLATION
Downloading Python
You can download the Python software by following these steps:
4. Once you've selected the correct version, click on the “download” link
5. After the download is complete, run the installer and follow the prompts
Note: In windows operating systems, IDLE will be come along with python software, no need to
install explicitly
Once standard Python installation completed in your system, you can run
Choosing and Installing a Code Editor
A code editor is a specialized tool for writing and editing programming code. Choosing the
right one improves productivity, debugging, and workflow. Below is a guide to selecting and
installing popular editors like VS Code, PyCharm, Sublime Text, and others.
1. Download:
2. Install:
3. Extensions (Must-Haves):
Python-coding/
│
├── hello.py # Main python file and Extension is .py
└── README.md #P
Python’s traditional runtime execution model: Source code you type is translated to byte code,
which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled,
but then it is interpreted.
Interactive Mode
Script Mode
Notepad with Command Prompt (.py files)
Without passing python script file to the interpreter, directly execute code to Python prompt.
Once you’re inside the python interpreter, then you can start.
hello world # Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
>>> x
#If a quantity is stored in memory, typing its name will display it. [0, 1, 2]
>>> 2+3
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter replies
8.
Alternatively, programmers can store Python script source code in a file with the .py
extension, and use the interpreter to execute the contents of the file. To execute the script by
the interpreter, you have to tell the interpreter the name of the file. For example, if you have a
script name MyFile.py and you're working on Unix, to run the script you have to type:
python MyFile.py
Working with the interactive mode is better when Python programmers deal with small pieces
of code as you can type and execute them immediately, but when the code is more than 2-4
lines, using the script for coding can help to modify and use the code in future.
Example:
Some of the examples of Python keywords include "if", "else", "while", "for", etc. To display
the all the python keywords.
Note: Collection data type is nothing but an object which holds more than one value.
Fundamental Data types
From the above 14 data types, int, float, str(String), bool(Boolean), complex are treated as
Fundamental data types
int
In Python programming, int is built-in class and it treated as int data type.int data type is used
to represent integer numbers, which are whole numbers without decimal points. Integers can
be positive, negative, or zero, and can have any length, as long as they fit within the memory
available on the computer.
Int data type can also be support Binary, Octal, Hexadecimal, and Decimal Number
# Integer
age = 25
float
In Python programming, float is built-in class and it treated as float data type and the float
data type is used to represent numbers with decimal points or floating-point numbers. Floats
can be positive, negative, or zero, and can have any number of decimal places, as long as they
fit within the memory available on the computer.
# Float
price = 19.99
Float numbers can be represented in scientific notation i.e. “Mantissa e Exponent”. General
format Mantissa e Exponent is converted into normal floating point as “mantissa x 10 to the
power of exponent”.
Note: Float data type does not support Binary, Octal and Hexadecimal number system but it
supports only Decimal number system.
str(string)
In Python programming, str is built-in class and it treated as string data type. str data type is
used to represent strings or text. A string is a sequence of characters, such as letters, numbers,
symbols, and spaces, and is enclosed in quotes, either single quotes (') or double quotes ("). We
will discuss more in Strings
# String
name = "Alice"
bool
In Python programming, bool is built-in class and it treated as Boolean data type and the bool
data type is used to represent Boolean value, which is either True or False. In Python, True and
False are the only Boolean values.
# Boolean
is_student = True
Complex
In Python programming, complex is built-in class and it treated as complex data type. complex
data type is used to represent complex numbers. A complex number is a number that can be
expressed in the form “a + bj”, where a and b are real numbers, and j is the imaginary unit (the
square root of -1). Complex number can be created by “complex ()” function. You can access the
real and imaginary values of a complex number by using “real” and “imag” attributes,
syntax: “complex_object.real”,
“complex_object.imag”
input() and print() function
input() function : The input() function in Python is used to accept input/data/values from
the keyboard by the user, and returns a string data. input() function has two syntaxes,
they are:
Syntax 1: input()
Syntax 2: input(“string”)
print() function: The print() function in Python is used to display output on the console or
terminal. It takes one or more arguments, print() function has mainly three arguments,
they are “end”, “sep” and “file”. “sep” argument separate the values with specified
character, default is ‘ ‘(single space) and “end” argument end the values with specified
characters, default is new line(\n) and “file” argument used to read file from console.
See below Python code screenshot for print() function:
len() function : The len() function in Python is used to get the length or number of items
in an object. It takes a single argument which can be a string, list, tuple, dictionary, or any
iterable object. It returns the number of items of an object.
Comment is a piece of text that is used to provide information or explanation about the code,
but is not executed as part of the program. Comments are used to make the code more readable
and to help other programmers understand the purpose and logic of the code.
Multiline Comment
Single Line Comment: In Python, you can create a single-line comment by using the hash
character (#) at the beginning of the line and everything after the hash symbol on that line will
be ignored by the Python interpreter.
Multiline Comment: You can create a multi-line comment in python by using following quotes
to enclose the comment text.
Three single quotes ‘’’ ‘’’
Three double quotes “”” “””
Four single quotes ‘’’’ ‘’’’
Four double quotes “””” “’””
Built-in Functions on Python
Python has many built-in functions that are available in Python software without import any
module.
Some of the built-in functions are given below:
print(): Used to display output on the console or terminal.
input(): Used to accept user input from the console or terminal.
len(): Used to get the length or number of items in an object.
type(): Used to get the data type of an object.
int(): Used to convert a any data type to an integer.
float(): Used to convert a any data type to float.
str(): Used to convert an object to a string.
range(): Used to generate a sequence of numbers.
list(): Used to convert an object to a list.
tuple(): Used to convert an object to a tuple.
dict(): Used to create a dictionary.
set(): Used to create a set.
sum(): Used to get the sum of all elements in an iterable.
max(): Used to get the maximum value in an iterable.
min(): Used to get the minimum value in an iterable.
sorted(): Used to sort an iterable.
reversed(): Used to reverse of an iterable
bin(): Used to covert in to binary number system
oct(): Used to covert in to octal number system
hex(): Used to convert in to hexadecimal number system
chr(): Used to convert Unicode point to character
ord(): Used to convert character to Unicode point number
complex(): Used to convert in to complex number
Data Type Conversion Functions
Python provide five fundamental data types such as int, float, bool, complex and str. The
purpose of data type convertion functions is that "to convert one data type value into another
data type value". These functions are also called as type casting techniques. Python provide us
five fundamental type casting techniques. They are:
int() function: In Python programming, the int() function is used to convert any data type value
to an integer data type.
Note: In Python, it is not possible to convert a complex number to an integer/float directly
because a complex number has both a real and an imaginary component, whereas an integer
only has a single numeric value and str to int also not possible when string value is
alphabets/special characters because alphabets/special characters don’t have the base value
float() function: In Python programming, the float() function is used to convert any data type
value to a float data type.
str() function: In Python programming, the str() function is used to convert a given any data type
value to a str data type.
bool() function: In Python programming, the bool() function is used to convert a given any data
type value to a bool data type.
complex() function: In Python programming, the complex() function is used to convert any data
type value to a complex data type.
OPERATORS
Operators and Operands
An operator is a symbol that represents a specific operation on one or more operands (values
or variables). Operators are used extensively in Python programming to perform various
operations on data, flow control and many more.
Examples: a+b, x>>y, x**y
# Here a,b,x and are operands/variables and +,>> and ** are operators.
Operator Precedence Order
PEMDAS" or "BEDMAS" is a mnemonic that stands for "Parentheses, Exponents, Multiplication
and Division, Addition and Subtraction". It is a rule that defines the order of operations in
mathematical expressions. In Python, the operator precedence is determined by the order of
the operators in the following list from the highest to the lowest precedence:
Operator Description
() Parentheses
** Exponentiation
*, /, % Multiplication, Division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
==, !=, <,>,<=,>=, in, not in, is, is not Comparison operators
Not Logical NOT
And Logical AND
Or Logical OR
= Assignment operators
+=, -=, *=, /=, %= Compound assignment operators
Types of Operators in Python
Python supports a wide range of operators. We have eight types of Operators.
They are:
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators (and, or, not)
Bitwise Operators (<<, >>, &, |, ^, ~)
Membership Operators (in, not in)
Identity Operators (is, is not)
Ternary Operator
1. Arithmetic Operators: These operators perform the mathematic operation on variables and
return a value. See the following table with example values:
Example:
a = 10
b = 3
print(a + b) # 13 (addition)
print(a - b) # 7 (subtraction)
print(a * b) # 30 (multiplication)
print(a / b) # 3.333... (division)
print(a // b) # 3 (floor division)
print(a % b) # 1 (modulus)
print(a ** b) # 1000 (exponentiation)
x = 5
y = 10
print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x > y) # False
print(x <= y) # True
print(x >= y) # False
3. Relational Operators: These operators performs conditional operations and return a bool
value i.e. either True or False based on the condition satisfied.
See the following table with example values:
age = 25
print(age == 25) # True
print(age != 30) # True
print(age > 18) # True
print(age <= 21) # False
Example:
has_license = True
has_car = False
age = 22
x = 10 # Binary: 1010
y = 4 # Binary: 0100
<< (Left Shift): This operator shift the bits of the first operand(left side) to the left by the
number of positions(bits) specified by the second operand(right side), then add zeros
right side to make it as 16 bits data.
See below example diagram to understand clearly:
Example 1: Simple Shift
Let's shift the number 5 left by 2 positions (5 << 2).
1. Convert 5 to binary (8 bits for clarity): 0000 0101
2. Shift all bits left by 2 positions. The leftmost bits (00) fall off and are lost.
3. Add 2 zeros at the end.
4. The new binary number is: 0001 0100 (which is 20 in decimal).
x = 5
result = x << 2
print(f"Binary of {x}: {bin(x)}") # 0b101
print(f"After << 2: {bin(result)}") # 0b10100
print(f"Decimal result: {result}") # 20
# Mathematical equivalence: 5 * (2 ** 2) = 5 * 4 = 20
Example 2: Visualizing the Process
Shifting 3 left by 3 places (3 << 3).
Decimal: 3
Binary (8-bit): 0000 0011
Shift left by 3:
Step 1: 0000 011? -> The leftmost 0 is lost, a gap (?) is created on the right.
Step 2: 0000 11?? -> Shift again.
Step 3: 0001 1??? -> Shift a third time.
Fill the gaps with 0s: 0001 1000
>> (Right Shift): This operator shift the bits of the first operand(left side) to the right by
the number of positions(bits) specified by the second operand(right side), then add zeros
left side to make it as 16 bits data.
See the below example diagram and Python code to understand clearly:
Example 1: Simple Shift (Positive Number)
Let's shift the number 20 right by 2 positions (20 >> 2).
1. Convert 20 to binary: 0001 0100
2. Shift all bits right by 2 positions. The rightmost bits (00) fall off and are lost.
3. For this positive number, add 2 zeros at the beginning (the most significant bit side).
4. The new binary number is: 0000 0101 (which is 5 in decimal).
x = 20
result = x >> 2
print(f"Binary of {x}: {bin(x)}") # 0b10100
print(f"After >> 2: {bin(result)}") # 0b101
print(f"Decimal result: {result}") # 5
# Mathematical equivalence: 20 // (2 ** 2) = 20 // 4 = 5
Decimal: 29
Binary (8-bit): 0001 1101
Shift right by 2:
Step 1: 0000 1110? -> The rightmost 1 is lost, a gap (?) is created on the left.
Step 2: 0000 0111?? -> Shift again. The rightmost 0 is lost.
Fill the left gaps with 0s (it's positive): 0000 0111
Example:
my_list = [1, 2, 3, 4, 5]
my_string = "Hello World"
1, 2, 3]
b = [1, 2, 3] # A new, separate list with the same values
c = a # c points to the *same object* as a
x = 257
y = 257
print(x is y) # False (This may vary by interpreter)
# The safe bet is to use `is` only for None, True, False.
print(x is None) # Correct usage
# Traditional if-else
age = 20
if age >= 18:
status = "Adult"
else:
status = "Minor"
# Another example
is_raining = True
activity = "Stay inside" if is_raining else "Go for a walk"
print(activity) # Output: Stay inside
LIST
In Python, a list is a collection of items that are ordered and mutable. It is one of the built-in
data types in Python and can hold items of same data types and different data types, such as
Numbers, Strings, Complex numbers, Boolean and other objects.
List holds the same data type values Ex: 10, 30, 50 and
Different data types elements Ex: 10, 'Good', True, 2+3j
List allows unique elements Ex: 10, 20, 50 and
Duplicate elements Ex: 10, 20, 50, 20, 10
List Representation:
List represented by the symbol: [ ] and
Elements separated by, (coma) Ex: [10, 30, 'Good']
Insertion Order: List holds the elements in "insertion order" this means elements never shuffle
their positions
List Indexing: List holds two types of indices
Forward/Positive indexing: 0, 1, 2, 3 ...
Backward/Negative indexing: ......-4, -3, -2, -1
= Operator: List support assignment (=) operation. By using assignment operator, list elements
can be updated by giving the index value.
Example Python code as below:
List Element Searching: List elements can search by using membership operators “in”, “not
in”. If given element is found, it returns the True and element not present it return False
List Indexing Operations
Indexing operation is a way to access individual element at a time in a list object and each
element in the list has a unique index (Positive or Negative). Element can be accessed by
passing the index value
The following Python code screenshot is for built-in functions on list object
List Class Built-in Methods
In Python, List class has many built-in methods that can be used to manipulate. Execute the
following code to display all list class methods
>>>dir(list)
The below table explained you all the list methods with example values
Below screenshots are the Python program with Output for list methods that read the values
from keyboard executed in IDLE script mode
1. append (element)
Adds a single element to the end of the list.
Syntax: list.append (element)
Modifies List: Yes (in-place)
Return Value: None
Syntax:
list.append(element)
Example 1:
print("Before append:", L) # [2, 3, 6, 8, 2, 9, 2, 3]
L.append(7)
print("After append(7):", L) # [2, 3, 6, 8, 2, 9, 2, 3, 7]
Example 2:
2. remove(element)
Removes the first occurrence of the specified element from the list.
Throws a ValueError if the element is not found.
Syntax: list.remove(element)
Modifies List: Yes (in-place)
Return Value: None
Syntax:
list.remove(element)
Example 1:
print("Before remove:", L) # [2, 3, 6, 8, 2, 9, 2, 3]
L.remove(9)
Example 2:
numbers = [1, 2, 3, 2, 4]
numbers.remove(2)
print(numbers) # Output: [1, 3, 2, 4]
3. pop()
Removes and returns the last element from the list.
Syntax: list.pop()
Modifies List: Yes (in-place)
Return Value: The removed element.
Syntax:
Example 2:
numbers = [10, 20, 30, 40]
4. pop(index)
Removes and returns the element at the specified index.
Syntax: list.pop(index)
Modifies List: Yes (in-place)
Return Value: The removed element.
Raises IndexError if the index is out of range.
Syntax:
Example 2:
# Remove element at index 1
second = numbers.pop(1)
print(second) # Output: 20
print(numbers) # Output: [10, 30]
5. insert (index, element)
Inserts an element at a specific position in the list. Elements after this position are shifted to
the right.
Syntax: list.insert (index, element)
Modifies List: Yes (in-place)
Return Value: None
Note: Using an index beyond the list length appends to the end.
Syntax:
list.insert(index, element)
Example 1:
print("Before insert:", L) # [2, 3, 6, 2, 2]
L.insert(3, 9) # Insert the number 9 at index 3
print("After insert(3, 9):", L) # [2, 3, 6, 9, 2, 2]
Example 2:
numbers = [1, 2, 4, 5]
numbers.insert(2, 3) # Insert 3 at index 2
print(numbers) # Output: [1, 2, 3, 4, 5]
6. count(element)
Returns the number of times the specified element appears in the list.
Syntax: list.count(element)
Modifies List: No
Return Value: Integer count.
Syntax:
list.count(element)
Example 1:
print("List L:", L) # [100, 2, 3, 6, 9, 2, 2]
count_of_2 = L.count(2)
count_of_100 = L.count(100)
count_of_999 = L.count(999) # Element not in list
Example 2:
numbers = [1, 2, 3, 2, 4, 2, 5]
count = numbers.count(2)
print(count) # Output: 3
7. index(element)
Returns the index of the first occurrence of the specified element.
Syntax: list.index(element)
Modifies List: No
Return Value: Integer index.
Raises ValueError if the element is not found.
Syntax:
list.index(element)
Example 1:
print("List L:", L) # [100, 2, 3, 6, 9, 2, 2]
index_of_9 = L.index(9)
index_of_2 = L.index(2) # Returns the first occurrence
Example 2:
fruits = ['apple', 'banana', 'cherry', 'banana']
index = fruits.index('banana')
print(index) # Output: 1
8. sort()
Sorts the elements of the list in ascending order by default.
Syntax: list.sort(key=None, reverse=False)
Modifies List: Yes (in-place)
Return Value: None
Parameters:
o reverse = True: Sorts in descending order.
o key: A function to specify sorting criteria (e.g., key=len to sort by length).
Syntax:
L.sort()
print("After sort():", L) # [2, 2, 2, 3, 3, 6, 8, 9]
L.sort(reverse=True)
print("After sort(reverse=True):", L) # [9, 8, 6, 3, 3, 2, 2, 2]
Example 2:
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 9]
numbers.sort(reverse=True)
print(numbers) # Output: [9, 5, 4, 3, 2, 1, 1]
9. reverse()
Reverses the order of elements in the list.
Syntax: list.reverse()
Modifies List: Yes (in-place)
Return Value: None
Syntax:
list.reverse()
Example 1:
L = [2, 3, 6, 8, 2, 9, 2, 3] # Reset the list
print("Before reverse:", L) # [2, 3, 6, 8, 2, 9, 2, 3]
L.reverse()
print("After reverse():", L) # [3, 2, 9, 2, 8, 6, 3, 2]
Example 2:
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # Output: [5, 4, 3, 2, 1]
10.extend(iterable)
Adds all the elements of an iterable (list, tuple, string, etc.) to the end of the list. This is
different from append() which adds the iterable as a single object.
Syntax: list.extend(iterable)
Modifies List: Yes (in-place)
Return Value: None
Syntax:
list.extend(iterable)
Example 1:
L = [2, 3, 6] # Reset the list
LL = [33, 44, 66]
print("List L:", L) # [2, 3, 6]
print("List LL:", LL) # [33, 44, 66]
L.extend(LL)
print("After extend(LL):", L) # [2, 3, 6, 33, 44, 66]
List Comparisons
List objects can be compared with relational operators. It returns bool value either True of False
depends on the logic applied on list objects
List Objects Create from collection or Iterable objects
List objects can be created by using other sequence/collection objects such as range(), tuple,
set. Below Python code is for list creating from range, set, tuple.
Syntax
empty_tuple = ()
print(empty_tuple) # Output: ()
Non empty tuple: Create the tuple object with elements
Tuples Comparisons
These compares the identity/address of tuple objects using identity operators. It returns true
when condition meet other wise false
Built-in Functions on Tuple
Python has many built-in functions that can be used to manipulate the tuple
# Tuple methods
e = input("Enter existing element to find index:")
print("Element ", e, " is at index", t.index(e))
Sample Output