Introduction to Python
1.1 What is Python?
Python is a high-level, interpreted, object-oriented, and general-purpose programming
language developed by Guido van Rossum and first released in 1991.
Python is designed to be simple, readable, and easy to learn, making it one of the most
popular programming languages in the world.
Definition
Python is an interpreted programming language that allows programmers to write
programs using simple syntax while supporting procedural, object-oriented, and
functional programming paradigms.
1.2 Features of Python
1. Simple and Easy to Learn
Uses simple English-like syntax.
Requires fewer lines of code.
Example:
print("Hello World")
2. High-Level Language
Programmer does not need to manage memory manually.
Focus is on problem-solving rather than hardware details.
3. Interpreted Language
Python code is executed line by line.
No separate compilation step is required.
4. Object-Oriented
Python supports:
Classes
Objects
Inheritance
Polymorphism
Encapsulation
5. Platform Independent
Python programs run on:
Windows
Linux
macOS
without modifying the source code.
6. Open Source
Python is free to use and distributed under the Python Software Foundation License.
7. Large Standard Library
Python provides thousands of built-in modules for
Mathematics
Networking
File handling
Data processing
Machine Learning
Artificial Intelligence
8. Dynamically Typed
Variable types are decided during execution.
Example
x = 10
x = "Python"
9. Automatic Memory Management
Python automatically performs:
Memory allocation
Garbage collection
10. Extensible
Python can be integrated with
C
C++
Java
1.3 Advantages of Python
Easy syntax
Faster development
Large community support
Huge collection of libraries
Cross-platform
Excellent for beginners
Suitable for AI and Data Science
1.4 Disadvantages of Python
Slower than C/C++
Higher memory consumption
Not ideal for mobile app development
Dynamic typing may cause runtime errors
1.5 Applications of Python
Python is widely used in:
Web Development
Frameworks:
Django
Flask
FastAPI
Artificial Intelligence
Libraries:
TensorFlow
PyTorch
Machine Learning
Libraries:
Scikit-learn
TensorFlow
Data Science
Libraries:
NumPy
Pandas
Matplotlib
Automation
Examples:
File automation
Email automation
Web scraping
Game Development
Library:
Pygame
Cyber Security
Examples:
Password testing
Malware analysis
Network scanning
Desktop Applications
Libraries:
Tkinter
PyQt
Internet of Things (IoT)
Examples:
Raspberry Pi
Arduino
1.6 Python Versions
Python 2
Released in 2000
No longer supported
Python 3
Current and recommended version.
Example
print("Welcome to Python")
1.7 Why Learn Python?
Python is suitable for
Beginners
Software Developers
Data Scientists
AI Engineers
Automation Engineers
Cyber Security Professionals
2. Python Program Execution
Python program execution follows these steps:
Source Code
↓
Python Interpreter
↓
Byte Code (.pyc)
↓
Python Virtual Machine (PVM)
↓
Output
3. Structure of a Python Program
Example
# Program to display greeting
print("Hello Students")
Components:
Comments
Statements
Functions
Output
4. Python Installation
Steps
1. Download Python.
2. Install Python.
3. Select "Add Python to PATH".
4. Verify installation.
Command
python --version
Example Output
Python 3.12.0
5. The IDLE Python Development
Environment
5.1 What is IDLE?
IDLE stands for
Integrated Development and Learning Environment
It is the default editor that comes with Python.
It allows users to
Write Python code
Execute programs
Debug applications
Save Python files
5.2 Features of IDLE
Interactive Python Shell
Script Editor
Syntax Highlighting
Auto Indentation
Debugger
Search and Replace
Auto-completion
Error highlighting
5.3 Components of IDLE
Python Shell
Interactive mode.
Example
>>> 5 + 10
15
Script Editor
Used to create Python files.
Example
File → New File
Run Menu
Execute program
Run → Run Module
Shortcut
F5
Debug Menu
Used for
Breakpoints
Step execution
Variable inspection
5.4 Interactive Mode
Commands are executed immediately.
Example
>>> print("Hello")
Hello
Advantages
Quick testing
Learning syntax
Calculations
5.5 Script Mode
Programs are written inside a file.
Example
name = input("Enter Name: ")
print("Welcome", name)
Save as
[Link]
Run
F5
5.6 Interactive Mode vs Script Mode
Feature Interactive Mode Script Mode
Execution One line at a time Entire program
Saving No Yes
Best for Testing Large programs
Extension None .py
5.7 Creating First Python Program
Step 1
Open IDLE.
Step 2
File → New File
Step 3
Type
print("Welcome to Python")
Step 4
Save as
[Link]
Step 5
Press
F5
Output
Welcome to Python
6. Python Standard Library
6.1 What is the Python Standard Library?
The Python Standard Library is a collection of pre-written modules that come bundled
with Python. It provides ready-to-use functionality for many common programming tasks,
eliminating the need to write code from scratch.
6.2 Advantages of the Standard Library
Saves development time
Well-tested and reliable
Platform independent
Easy to use
Supports a wide range of applications
6.3 Common Standard Library Modules
Module Purpose
math Mathematical operations
random Random number generation
datetime Date and time manipulation
os Operating system interaction
sys Python interpreter and system functions
statistics Statistical calculations
string String constants and helper functions
Module Purpose
collections Specialized container data types
itertools Efficient looping and iterator tools
functools Higher-order functions and operations
pathlib Object-oriented file system paths
json JSON encoding and decoding
csv Reading and writing CSV files
re Regular expressions
time Time-related functions
6.4 Using the math Module
import math
print([Link](25))
print([Link](5))
print([Link])
Output
5.0
120
3.141592653589793
6.5 Using the random Module
import random
print([Link](1, 10))
print([Link](["Apple", "Banana", "Orange"]))
2
Apple
6.6 Using the datetime Module
from datetime import datetime
now = [Link]()
print(now)
o/p
2026-07-31 07:59:29.386462
6.7 Using the os Module
import os
print([Link]())
6.8 Using the sys Module
import sys
print([Link])
6.9 Using the statistics Module
import statistics
marks = [80, 90, 75, 85, 95]
print([Link](marks))
print([Link](marks))
output
85
85
6.10 Using the json Module
import json
student = {
"name": "Alice",
"age": 20
}
json_data = [Link](student)
print(json_data)
o/p
{"name": "Alice", "age": 20}
6.11 Using the csv Module
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)
6.12 Using the re Module
import re
text = "Python Programming"
match = [Link]("Python", text)
print([Link]())
Output
Python
6.13 Importing Modules
Import an entire module:
import math
print([Link](16))
Import a specific function:
from math import sqrt
print(sqrt(16))
Import with an alias:
import math as m
print([Link])
1. Literals in Python
1.1 What are Literals?
Literals are fixed values directly written in the source code. These values do not change
during program execution unless assigned to variables.
Definition
A literal is a constant value assigned to a variable or used directly in a Python program.
Example
print(100)
print("Python")
print(True)
Output
100
Python
True
2. Types of Literals
Python supports several types of literals:
Numeric Literals
String Literals
Boolean Literals
Special Literal (None)
This chapter focuses on Numeric Literals and String Literals.
3. Numeric Literals
Numeric literals represent numerical values.
Python supports four main numeric types:
Integer (int)
Floating Point (float)
Complex (complex)
Boolean (bool) (treated as a subclass of int)
3.1 Integer Literals
Integers are whole numbers without decimal points.
Examples
a = 10
b = -50
c = 0
print(a)
print(b)
print(c)
Output
10
-50
0
3.2 Floating Point Literals
Floating-point literals represent decimal numbers.
Example
pi = 3.14159
temperature = 36.5
print(pi)
print(temperature)
Output
3.14159
36.5
3.3 Scientific Notation
Python supports exponential notation.
Example
distance = 5e3
mass = 7.5e-2
print(distance)
print(mass)
Output
5000.0
0.075
3.4 Complex Literals
Complex numbers consist of a real and an imaginary part.
Example
z = 4 + 5j
print(z)
Output
(4+5j)
3.5 Binary, Octal, and Hexadecimal Literals
Binary
num = 0b1010
print(num)
Output
10
Octal
num = 0o25
print(num)
Output
21
Hexadecimal
num = 0x2A
print(num)
Output
42
4. String Literals
A string literal is a sequence of characters enclosed within quotes.
Python supports
Single quotes
Double quotes
Triple single quotes
Triple double quotes
Single Quotes
name = 'Python'
print(name)
O/P
Python
Double Quotes
course = "Programming"
print(course)
O/P
Programming
Triple Quotes
Useful for multi-line strings.
text = """Python
is
easy"""
print(text)
Output
Python
is
easy
Raw String
A raw string ignores escape sequences.
Example
path = r"C:\Users\Student"
print(path)
Output
C:\Users\Student
5. Control Characters (Escape Sequences)
Control characters begin with a backslash (\) and are used to represent special formatting.
Escape Sequence Meaning
\n New line
\t Horizontal tab
\\ Backslash
\' Single quote
\" Double quote
\b Backspace
\r Carriage return
Example of New Line
print("Python\nProgramming")
Output
Python
Programming
Example of Tab
print("Name\tMarks")
Output
Name Marks
Example of Quotes
print("He said \"Hello\"")
Output
He said "Hello"
The escape character allows you to use double quotes when you normally
would not be allowed:
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
o/p
We are the so-called "Vikings" from the north.
txt = "We are the so-called "Vikings" from the north."
print(txt)
ERROR!
Traceback (most recent call last):
File "<[Link]>", line 1
txt = "We are the so-called "Vikings" from the north."
^^^^^^^
SyntaxError: invalid syntax
=== Code Exited With Errors ===
txt = 'It\'s alright.'
print(txt)
o/p
It's alright.
txt = "This will insert one \\ (backslash)."
print(txt)
This will insert one \ (backslash).
txt = "Hello\nWorld!"
print(txt)
o/p
Hello
World!
txt = "Hello\rWorld!"
print(txt)
o/p
Hello
World!
#This example erases one character (backspace):
txt = "Hello \bWorld!"
print(txt)
HelloWorld!
#A backslash followed by three integers will result in a octal value:
txt = "\110\145\154\154\157"
print(txt)
o/p
Hello
#A backslash followed by an 'x' and a hex number represents a hex value:
txt = "\x48\x65\x6c\x6c\x6f"
print(txt)
Hello
6. String Formatting
String formatting allows values to be inserted into strings dynamically.
Python supports several methods.
6.1 Using Comma in print()
name = "Alice"
age = 20
print("Name:", name)
print("Age:", age)
Output
Name: Alice
Age: 20
6.2 Using % Formatting
name = "John"
print("Hello %s" % name)
Output
Hello John
6.3 Using format() Method
name = "John"
marks = 90
print("Name: {} Marks: {}".format(name, marks))
Output
Name: John Marks: 90
6.4 Using f-Strings (Recommended)
Introduced in Python 3.6.
name = "Alice"
marks = 95
print(f"{name} scored {marks} marks.")
Output
Alice scored 95 marks.
7. Implicit and Explicit Line Joining
Python allows long statements to span multiple lines using implicit or explicit line joining.
7.1 Implicit Line Joining
Statements enclosed within parentheses (), square brackets [], or curly braces {} can
continue onto the next line without a backslash.
Example
total = (100 +
200 +
300)
print(total)
Output
600
Another Example
numbers = [
10,
20,
30,
40
]
print(numbers)
Output
[10, 20, 30, 40]
7.2 Explicit Line Joining
Use a backslash (\) to continue a statement onto the next line.
Example
total = 100 + \
200 + \
300
print(total)
Output
600
Difference Between Implicit and Explicit Line Joining
Implicit Line Joining Explicit Line Joining
Uses (), [], {} Uses \
Preferred and more readable Less preferred
No backslash required Backslash required
8. Variables
8.1 What is a Variable?
A variable is a named memory location used to store data. The value stored in a variable can
change during program execution.
Definition
A variable is an identifier that refers to a value stored in memory.
Example
name = "Alice"
age = 20
print(name)
print(age)
Advantages of Variables
Store data for later use
Improve readability
Reuse values
Simplify program maintenance
9. Variable Assignment
Python uses the assignment operator (=) to assign values to variables.
Single Assignment
x = 100
Multiple Assignment
a, b, c = 10, 20, 30
print(a)
print(b)
print(c)
Assigning Same Value
x = y = z = 50
print(x)
print(y)
print(z)
Swapping Variables
a = 10
b = 20
a, b = b, a
print(a)
print(b)
Output
20
10
10. Keyboard Input
Python uses the input() function to accept user input.
Reading a String
name = input("Enter your name: ")
print("Welcome", name)
Reading an Integer
Since input() returns a string, convert it using int().
age = int(input("Enter your age: "))
print(age)
Reading a Float
salary = float(input("Enter salary: "))
print(salary)
Example Program
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
print(f"{name} scored {marks} marks.")
11. Identifiers
11.1 What is an Identifier?
An identifier is the name given to a variable, function, class, module, or other object in
Python.
Examples
studentName = "Alice"
marks = 95
calculate_sum = 50
Rules for Naming Identifiers
1. Must begin with a letter or underscore (_)
2. Cannot start with a digit
3. Can contain letters, digits, and underscores
4. Case-sensitive
5. Cannot use Python keywords
Valid Identifiers
student
_roll
marks1
total_marks
Invalid Identifiers
1student
student-name
class
my name
Naming Conventions
Use snake_case for variables and functions.
Example
student_name = "John"
total_marks = 450
Use PascalCase for class names.
class StudentRecord:
pass
Use UPPER_CASE for constants.
PI = 3.14159
MAX_SIZE = 100
12. Keywords in Python
Keywords are reserved words that have predefined meanings and cannot be used as
identifiers.
Examples of common Python keywords:
Keyword Purpose
if Conditional statement
else Alternative branch
elif Multiple conditions
for Loop
while Loop
break Exit a loop
continue Skip to next iteration
pass Placeholder statement
def Define a function
return Return a value
class Define a class
import Import a module
try Start exception handling
except Handle exceptions
finally Execute cleanup code
True Boolean value
False Boolean value
None Represents no value
To display all Python keywords:
import keyword
print([Link])
o/p
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
=== Code Execution Successful ===
13. Other Predefined Identifiers (Built-in
Functions)
Python provides many predefined identifiers (built-in functions and constants) that are
available without importing any module.
Examples include:
Identifier Purpose
print() Displays output
Identifier Purpose
input() Accepts user input
len() Returns the length of an object
type() Returns the data type
int() Converts to integer
float() Converts to float
str() Converts to string
bool() Converts to Boolean
list() Creates a list
tuple() Creates a tuple
set() Creates a set
dict() Creates a dictionary
range() Generates a sequence of numbers
max() Returns the largest value
min() Returns the smallest value
sum() Returns the sum of values
abs() Returns the absolute value
round() Rounds a number
sorted() Returns a sorted list
help() Displays documentation
Example:
numbers = [10, 20, 30, 40]
print(len(numbers))
print(max(numbers))
print(sum(numbers))
Output
4
40
100
1. Operators in Python
1.1 What is an Operator?
In Python programming, Operators in general are used to
perform operations on values and variables.
Operators: Special symbols like -, + , * , /, etc.
Operands: Value on which the operator is applied.
Example
a = 10
b = 5
print(a + b)
Here:
a and b are operands
+ is an operator
Types of Operators in Python
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical
operations like addition, subtraction, multiplication and division.
In Python, the division operator (/) returns a floating-point result,
while floor division (//) returns an integer result.
a = 15
b = 4
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
Comparison Operators
Comparison(or Relational) operators compares values. It either
returns True or False according to the condition.
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
Python Logical Operators
Logical operators are used to combine or modify conditions and
return a Boolean result (True or False). They are commonly used
in conditional statements to control the flow of a program based
on multiple logical conditions.
Let's see an example on how logical operators AND, OR, and NOT
work using Boolean variables.
a, b, c = True, False, True
if a and c:
print("Both a and c are True (AND condition).")
if b or c:
print("Either b or c is True (OR condition).")
if not b:
print("b is False (NOT condition).")
Output
Both a and c are True (AND condition).
Either b or c is True (OR condition).
b is False (NOT condition).
Explanation:
a and c returns True because both values are True.
b or c returns True because at least one value is True.
not b reverses False to True, so the condition executes.
The following table summarizes the logical operators, their
purpose, syntax and examples:
Operator Description Syntax Example
Returns True if
both the
and x and y x>7 and x>10
operands are
true
Returns True if
either of the
or x or y x<7 or x>15
operands is
true
Returns True if
not(x>7 and
not the operand is not x
x> 10)
false
Truth Table for Logical Operators
A truth table shows how logical operators behave for all possible
combinations of Boolean values (True and False). It helps in
clearly understanding the output of AND, OR, and NOT
operations.
Truth Table for Python Logical Operators
AND Operator
Boolean AND operator returns True if both the operands are True
else it returns False.
Flowchart of AND Operator
Example 1: Below example shows how the logical AND (and)
operator works by checking if all conditions are true before
executing a statement.
a = 10
b = 10
c = -10
if a > 0 and b > 0:
print("Numbers are greater than 0")
if a > 0 and b > 0 and c > 0:
print("Numbers are greater than 0")
else:
print("Atleast one number is not greater than 0")
Output
Numbers are greater than 0
Atleast one number is not greater than 0
Example 2: The code checks if all variables a, b and c evaluate
to True, printing a message accordingly.
a = 10
b = 12
c = 0
if a and b and c:
print("All the numbers have boolean value as True")
else:
print("Atleast one number has boolean value as False")
Output
Atleast one number has boolean value as False
Note: If the first expression is evaluated to be false while using
the AND operator, then the further expressions are not
evaluated.
OR Operator
Boolean OR operator returns True if either of the operands is
True.
Flowchart of OR Operator
Example 1: Below example demonstrates the logical OR (or)
operator, where the condition becomes true if at least one of the
given expressions evaluates to True.
a = 10
b = -10
c = 0
if a > 0 or b > 0:
print("Either of the number is greater than 0")
else:
print("No number is greater than 0")
if b > 0 or c > 0:
print("Either of the number is greater than 0")
else:
print("No number is greater than 0")
Output
Either of the number is greater than 0
No number is greater than 0
Example 2: The code checks if any of the variables a, b, or c
has a boolean value as True; if so, it prints "At least one number
has boolean value as True".
a = 10
b = 12
c = 0
if a or b or c:
print("Atleast one number has boolean value as True")
else:
print("All the numbers have boolean value as False")
Output
Atleast one number has boolean value as True
Note: If the first expression is evaluated to be True while using
or operator, then the further expressions are not evaluated.
NOT Operator
Boolean NOT operator works with a single boolean value. If the
boolean value is True it returns False and vice-versa.
Flowchart of NOT Operator
Example: Below code checks if a is divisible by either 3 or 5,
otherwise, it prints a message indicating that it is not.
a = 10
if not a:
print("Boolean value of a is True")
if not (a % 3 == 0 or a % 5 == 0):
print("10 is not divisible by either 3 or 5")
else:
print("10 is divisible by either 3 or 5")
Output
10 is divisible by either 3 or 5
Bitwise Operators
Bitwise operators in Python are used to perform operations on the binary representations
(0s and 1s) of integers. Python converts integers into binary format, applies the operator bit
by bit, and returns the result as a standard base-10 integer.
Core Bitwise Operators
Example (5 = 0101₂, 3 =
Operator Name Description
0011₂)
& AND Sets each bit to 1 if both bits are 1. 5 & 3 → 1 (0001)
| OR Sets each bit to 1 if at least one bit is 1. 5 | 3 → 7 (0111)
Sets each bit to 1 if only one of the bits
^ XOR 5 ^ 3 → 6 (0110)
is 1.
~5 → -6 (using 2's
~ NOT Inverts all bits (turns 1 to 0 and 0 to 1).
complement)
Zero-fill left Shifts bits left by pushing zeros from
<< 5 << 1 → 10 (1010)
shift the right.
Signed right Shifts bits right by pushing copies of
>> 5 >> 1 → 2 (0010)
shift the leftmost bit.
How They Work (With Visual Examples)
1. Bitwise AND (&)
Compares each bit. If both are 1, the result is 1. Otherwise, it is 0.
text
0101 (5)
& 0011 (3)
----
0001 (1)
Use code with caution.
2. Bitwise OR (|)
Compares each bit. If at least one bit is 1, the result is 1.
text
0101 (5)
| 0011 (3)
----
0111 (7)
Use code with caution.
3. Bitwise XOR (^)
Compares each bit. If the bits are different, the result is 1. If they are the same, it is 0.
text
0101 (5)
^ 0011 (3)
----
0110 (6)
Use code with caution.
4. Bitwise NOT (~)
Inverts the bits. In Python, this works with signed integers using 2's complement, which
effectively follows the formula: ~x = -(x + 1).
text
~5 -> -(5 + 1) -> -6
5. Shift Operators (<< and >>)
Left Shift (<<): Multiplies a number by 2 for every shift position. Shifting 5 << 1
pushes the bits left, resulting in 10.
Right Shift (>>): Performs floor division by 2 for every shift position. Shifting 5 >> 1
cuts the value down to 2.
Python Code Example
You can test these operators directly in Python:
python
a = 5 # Binary: 0101
b = 3 # Binary: 0011
print(a & b) # Output: 1
print(a | b) # Output: 7
print(a ^ b) # Output: 6
print(~a) # Output: -6
print(a << 1) # Output: 10
print(a >> 1) # Output: 2
Assignment Operators
Assignment operators are used to assign values to the variables.
This operator is used to assign the value of the right side of the
expression to the left side operand. Example:
a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Output
10
20
10
100
102400
Identity Operators
"is" and "is not" are the identity operators and both are used to
check if two values are located on the same part of the memory.
Two variables that are equal do not imply that they are
identical.
is True if the operands are identical
is not True if the operands are not identical
a = 10
b = 20
c = a
print(a is not b)
print(a is c)
Output
True
True
Membership Operators
"in" and "not in" are the membership operators that are used to
test whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
x = 24
y = 20
my_list = [10, 20, 30, 40, 50]
if (x not in my_list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in my_list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output
x is NOT present in given list
y is present in given list
Ternary Operator
Ternary operators also known as conditional expressions are
operators that evaluate something based on a condition being
true or false. It was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the
multiline if-else, making the code compact.
Syntax : [on_true] if [expression] else [on_false]
a, b = 10, 20
min = a if a < b else b
print(min)
Output
10
Precedence and Associativity of Operators
Operator precedence and associativity determine the priorities of
the operator.
Operator Precedence
This is used in an expression with more than one operator with
different precedence to determine which operation to perform
first.
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0
if name == "Alex" or name == "John" and age >= 2:
print("Hello! Welcome.")
else:
print("Good Bye!!")
Output
610
Hello! Welcome.
Operator Associativity
If an expression contains two or more operators with the same
precedence then Operator Associativity is used to determine. It
can either be Left to Right or from Right to Left.
print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)
Output
100.0
6
0
512
2. Relational (Comparison) Operators
Relational operators compare two values and return a Boolean value (True or False).
List of Relational Operators
Operator Meaning Example
== Equal to 5 == 5 → True
!= Not equal to 5 != 3 → True
Operator Meaning Example
> Greater than 8 > 5 → True
< Less than 4 < 2 → False
>= Greater than or equal 7 >= 7 → True
<= Less than or equal 4 <= 6 → True
Example
x = 20
y = 10
print(x == y)
print(x != y)
print(x > y)
print(x < y)
print(x >= y)
print(x <= y)
Output
False
True
True
False
True
False
3. Membership Operators
Membership operators test whether a value exists in a sequence such as a string, list, tuple, or
set.
Membership Operators
Operator Meaning
in Returns True if value exists
not in Returns True if value does not exist
Example using List
numbers = [10,20,30,40]
print(20 in numbers)
print(50 in numbers)
print(60 not in numbers)
Output
True
False
True
Example using String
text = "Python Programming"
print("Python" in text)
print("Java" in text)
Output
True
False
Types of Expressions
Arithmetic Expression
10 + 20
Relational Expression
10 > 5
Logical Expression
(10 > 5) and (20 > 15)
Membership Expression
5 in [1,2,3,4,5]
6. Data Types
Python provides several built-in data types.
Numeric Types
Type Example
int 100
float 15.6
Type Example
complex 5+3j
Sequence Types
Type Example
str "Python"
list [10,20,30]
tuple (10,20,30)
range range(5)
Mapping Type
Type Example
dict {"id":1,"name":"Ram"}
Set Types
Type Example
set {1,2,3}
frozenset frozenset({1,2})
Boolean Type
True
False
None Type
None
Finding Data Type
a = 100
b = 25.5
c = "Python"
print(type(a))
print(type(b))
print(type(c))
Output
<class 'int'>
<class 'float'>
<class 'str'>
7. Operator Precedence
What is Operator Precedence?
Operator precedence determines the order in which operators are evaluated in an expression.
Common Operator Precedence (Highest to Lowest)
Priority Operators
1 ()
2 **
3 +x, -x
4 *, /, //, %
5 +, -
6 Relational (<, >, <=, >=)
7 Equality (==, !=)
8 not
9 and
10 or
Example
result = 5 + 3 * 2
print(result)
Output
11
Using Parentheses
result = (5 + 3) * 2
print(result)
Output
16
8. Boolean Expressions
A Boolean expression evaluates to either True or False.
Example
age = 22
print(age >= 18)
Output
True
Compound Boolean Expression
marks = 75
attendance = 90
print(marks >= 40 and attendance >= 75)
Output
True
9. Operator Associativity
What is Associativity?
Associativity determines the order in which operators of the same precedence are evaluated.
Left-to-Right Associativity
Most operators follow left-to-right evaluation.
Example
result = 20 - 5 - 3
print(result)
Evaluation
20 - 5 = 15
15 - 3 = 12
Output
12
Right-to-Left Associativity
Exponentiation (**) follows right-to-left associativity.
Example
print(2 ** 3 ** 2)
Evaluation
2 ** (3 ** 2)
2 ** 9
512
Output
512
10. Mixed-Type Expressions
What is a Mixed-Type Expression?
A mixed-type expression contains operands of different data types.
Python automatically performs type conversion (type promotion) where possible.
Integer + Float
a = 10
b = 5.5
print(a + b)
Output
15.5
Integer + Complex
a = 10
b = 3 + 4j
print(a + b)
Output
(13+4j)
Explicit Type Conversion
a = "100"
b = int(a)
print(b + 20)
Output
120
Invalid Mixed-Type Expression
print("10" + 5)
Output
TypeError
Correct Way
print(int("10") + 5)
Output
15
11. Virtual Environments
What is a Virtual Environment?
A Virtual Environment is an isolated Python environment that allows each project to have
its own Python interpreter and installed packages.
Definition
A virtual environment is an isolated workspace that keeps project-specific libraries separate
from the system-wide Python installation.
Why Use Virtual Environments?
Prevent package conflicts.
Maintain different package versions for different projects.
Simplify dependency management.
Improve project portability.
Create reproducible development environments.
Creating a Virtual Environment
Windows
python -m venv myenv
Linux/macOS
python3 -m venv myenv
Activating a Virtual Environment
Windows
myenv\Scripts\activate
Linux/macOS
source myenv/bin/activate
When activated, the terminal prompt changes to:
(myenv)
Installing Packages
pip install numpy
Viewing Installed Packages
pip list
Saving Project Dependencies
pip freeze > [Link]
Installing Dependencies from a File
pip install -r [Link]
Deactivating the Virtual Environment
Deactivate
Write a python program to calculate bill amount for the items purchased
given its quantity, amount, discount and tax.
qty=int(input("Enter the quantity of product"))
value=float(input("Enter the value"))
discount=float(input("Enter the discount"))
tax=int(input("Enter the tax amount"))
amount=qty*value
dis=amount*discount/100
amount2=(amount-dis)
tax2=amount2*tax/100
billamt=tax2+amount2
print("amount paid is:",billamt)
Output:
Enter the quantity of product100
Enter the value10
Enter the discount5
Enter the tax amount5
amount paid is: 997.5
Write a python program to demonstrate manipulation of Bitwise operators
Program:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Bitwise AND (&) =", a & b)
print("Bitwise OR (|) =", a | b)
print("Bitwise XOR (^) =", a ^ b)
print("Bitwise NOT (~) of a =", ~a)
print("Bitwise NOT (~) of b =", ~b)
print("Bitwise Left Shift (a << 1) =", a << 1)
print("Bitwise Right Shift (a >> 1) =", a >> 1)
Output :
Enter first number: 5
Enter second number: 3
Bitwise AND (&) = 1
Bitwise OR (|) = 7
Bitwise XOR (^) = 6
Bitwise NOT (~) of a = -6
Bitwise NOT (~) of b = -4
Bitwise Left Shift (a << 1) = 10
Bitwise Right Shift (a >> 1) = 2
Write a python program to solve the two expressions i) x1=a+b/c-a*e**2
ii) x2=1/2^2 + 2/3^2+3/4^2
a = float(input("Enter value of a: "))
b = float(input("Enter value of b: "))
c = float(input("Enter value of c: "))
e = float(input("Enter value of e: "))
x1 = a + b/c - a * e**2
print("Result of expression (i) x = a + b/c - a*e**2 is:", x1)
x2 = (1/(2**2)) + (2/(3**2)) + (3/(4**2))
print("Result of expression (ii) x = 1/2^2 + 2/3^2 + 3/4^2 is:", x2)
output:
Enter value of a: 2
Enter value of b: 6
Enter value of c: 3
Enter value of e: 2
Result of expression (i) x = a + b/c - a*e**2 is: -4.0
Result of expression (ii) x = 1/2^2 + 2/3^2 + 3/4^2 is: 0.6597222222222222
write a python program to evaluate expressions
Program:
a = float(input("Enter value of a: "))
b = float(input("Enter value of b: "))
c = float(input("Enter value of c: "))
exp1 = (a + b) * c
print("Result of (a + b) * c =", exp1)
exp2 = a**2 + b**2 - c
print("Result of a^2 + b^2 - c =", exp2)
exp3 = (a / b) + (b % c)
print("Result of (a / b) + (b % c) =", exp3)
Output
Enter value of a: 4
Enter value of b: 2
Enter value of c: 3
Result of (a + b) * c = 18.0
Result of a^2 + b^2 - c = 17.0
Result of (a / b) + (b % c) = 4.0