UNIT - I
Introduction to Python: Installing and Using Jupyter Notebook – Creating and
Executing Python Programs – Variables – Data Types – Operators – Statements –
Expressions – Type Conversions – Control Flow Statements – Exception Handling.
1. INTRODUCTION TO PYTHON
What is Python?
Python is a high-level, general-purpose, interpreted programming language
designed with an emphasis on code readability, simplicity, and programmer
productivity.
Python supports several programming paradigms, including:
• Procedural programming
• Object-oriented programming
• Functional programming
• Event-driven programming
Python programs are generally shorter and easier to understand than equivalent
programs written in many lower-level languages.
Example
name = "Kamal"
age = 25
print("Name:", name)
print("Age:", age)
History of Python
Python was created by Guido van Rossum and was first released in 1991.
The name "Python" was inspired by the British comedy series Monty Python's
Flying Circus, rather than the snake.
Major versions
• Python 1.x – early development
• Python 2.x – widely used older generation
• Python 3.x – modern Python generation
Python 3 introduced several improvements over Python 2, including cleaner
syntax and better Unicode support.
FEATURES OF PYTHON
1 Simple and Readable
Python uses a relatively simple syntax.
a = 10
b = 20
print(a + b)
2 High-Level Language
Python allows programmers to work at a high level of abstraction without
directly managing memory addresses or processor instructions.
3 Interpreted
Python code is executed by the Python runtime.
In the standard CPython implementation, source code is compiled to bytecode,
which is then executed by the Python virtual machine.
Therefore, describing Python simply as "interpreted" is useful for beginners,
but internally Python execution involves a compilation-to-bytecode step.
4 Dynamically Typed
A variable does not need an explicit type declaration.
x = 100
x = "Python"
The same variable name can refer to objects of different types at different
times.
5 Object-Oriented
Python supports:
• Classes
• Objects
• Inheritance
• Encapsulation
• Polymorphism
6 Portable
Python programs can generally run on different operating systems with little or
no modification.
7 Open Source
Python is freely available and has a large global developer community.
8 Extensive Library Support
Python provides a large standard library and a huge ecosystem of third-party
packages.
Examples include:
• NumPy
• Pandas
• Matplotlib
• Scikit-learn
• TensorFlow
• PyTorch
APPLICATIONS OF PYTHON
Python is widely used in:
1. Web Development
Frameworks include Django and Flask.
2. Data Science
Python is widely used for:
• Data analysis
• Data visualization
• Statistical computing
3. Artificial Intelligence and Machine Learning
Python is extensively used for:
• Machine learning
• Deep learning
• Natural language processing
• Computer vision
4. Automation
Python can automate repetitive tasks such as:
• File processing
• Data collection
• Report generation
• System administration
5. Scientific Computing
Python is used for numerical and scientific applications.
6. Education
Its simple syntax makes Python suitable for teaching programming concepts.
2. INSTALLING AND USING JUPYTER NOTEBOOK
What is Jupyter Notebook?
Jupyter Notebook is an interactive computational environment that allows users
to create and execute code while combining:
• Program code
• Output
• Documentation
• Mathematical expressions
• Tables
• Visualizations
A notebook is particularly useful for data science, teaching, experimentation,
and research.
2 Installing Jupyter Notebook
Jupyter can be installed using Python's package manager, pip.
pip install notebook
After installation, launch it using:
jupyter notebook
The notebook interface normally opens through a web browser.
3 Using Jupyter Notebook
A typical workflow is:
1. Install Python.
2. Install Jupyter Notebook.
3. Launch Jupyter.
4. Create a new Python notebook.
5. Enter Python code.
6. Execute the cell.
7. Observe the output.
8. Save the notebook.
4 Notebook Cells
A notebook consists of cells.
Code Cell
Used to write and execute Python code.
x = 10
print(x)
Markdown Cell
Used for:
• Headings
• Explanations
• Lists
• Documentation
• Mathematical notation
5 Executing a Cell
The commonly used shortcut is:
Shift + Enter
It executes the current cell and moves to the next cell.
6 Advantages of Jupyter Notebook
• Interactive execution
• Immediate output
• Easy experimentation
• Supports visualization
• Combines code and documentation
• Useful for teaching and research
• Easy to share computational work
3. CREATING AND EXECUTING PYTHON PROGRAMS
Python programs can be developed in different environments.
1 Interactive Mode
Python statements can be entered directly into the interpreter.
Example:
>>> 10 + 20
30
The result is displayed immediately.
Advantages
• Quick experimentation
• Useful for learning
• Useful for testing small expressions
2 Script Mode
A Python program can be stored in a file with a .py extension.
Example:
# [Link]
a = 10
b = 20
c=a+b
print(c)
The program can be executed using:
python [Link]
3 Basic Structure of a Python Program
# Input
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
# Processing
result = a + b
# Output
print("Result =", result)
This demonstrates:
Input → Processing → Output
4. INDENTATION IN PYTHON
Indentation refers to spaces or tabs at the beginning of a line.
Python uses indentation to define code blocks.
Example
if x > 0:
print("Positive")
The indented statement belongs to the if block.
Incorrect example
if x > 0:
print("Positive")
This causes an indentation-related syntax error.
Important point
Python conventionally uses four spaces for each indentation level.
5. COMMENTS IN PYTHON
Comments explain program code and are ignored during normal execution.
1 Single-Line Comment
# This is a comment
x = 10
2 Documentation Strings
Python uses strings as docstrings to document modules, functions, classes, and
methods.
def add(a, b):
"""Return the sum of two numbers."""
return a + b
6. VARIABLES
1 Definition
A variable is a name bound to an object.
Example:
x = 100
Here:
• x is the variable name.
• 100 is an integer object.
• = performs assignment.
Python variables do not require explicit declaration before assignment.
2 Dynamic Typing
Python determines the type of the object at runtime.
x = 100
print(type(x))
x = "Python"
print(type(x))
The variable x first refers to an integer object and later to a string object.
3 Variable Naming Rules
A variable name:
• Can contain letters.
• Can contain digits.
• Can contain underscore.
• Cannot start with a digit.
• Cannot be a Python keyword.
• Is case-sensitive.
Valid
student_name = "Ravi"
marks2 = 90
_total = 100
Invalid
2marks = 90
student-name = "Ravi"
4 Multiple Assignment
Python allows multiple assignment.
a, b, c = 10, 20, 30
5 Swapping Variables
Python supports direct swapping.
a = 10
b = 20
a, b = b, a
7. DATA TYPES
A data type specifies the nature of an object and determines what operations
are supported.
Python provides several built-in data types.
1 Numeric Data Types
Integer – int
Represents whole numbers.
x = 100
Python integers can represent arbitrarily large values subject to available
memory.
Floating Point – float
Represents real numbers.
x = 10.5
Complex – complex
Represents numbers with real and imaginary components.
z = 3 + 4j
The real and imaginary components can be accessed using:
[Link]
[Link]
2. BOOLEAN DATA TYPE
The Boolean type is bool.
It contains two values:
True
False
Example:
x = 10
print(x > 5)
Output:
True
3. STRING DATA TYPE
A string is a sequence of Unicode characters.
name = "Python"
Strings can be written using:
"Python"
'Python'
String indexing
text = "Python"
print(text[0])
Output:
P
String slicing
print(text[0:3])
Output:
Pyt
Strings are immutable.
4. LIST
A list is an ordered and mutable collection.
numbers = [10, 20, 30, 40]
Elements can be modified:
numbers[0] = 100
Lists can contain different data types:
data = [10, "Python", 3.14, True]
5. TUPLE
A tuple is an ordered and immutable collection.
coordinates = (10, 20)
Once created, tuple elements cannot be modified.
6. SET
A set is an unordered collection of unique elements.
numbers = {10, 20, 30, 20}
print(numbers)
Duplicate values are removed.
Sets support operations such as:
• Union
• Intersection
• Difference
• Symmetric difference
7. DICTIONARY
A dictionary stores data as key-value pairs.
student = {
"name": "Ravi",
"age": 22,
"cgpa": 8.5
}
Accessing a value:
print(student["name"])
Dictionaries are mutable.
8. MUTABLE AND IMMUTABLE OBJECTS
Mutable
An object whose contents can be changed after creation.
Examples:
• list
• dict
• set
Immutable
An object whose contents cannot be changed after creation.
Examples:
• int
• float
• bool
• str
• tuple
Example
x = [10, 20]
x[0] = 100
The list is modified.
But:
x = "Python"
The string itself cannot be modified character by character.
8. OPERATORS
Operators perform operations on operands.
Python operators can be classified as:
1. Arithmetic
2. Comparison
3. Assignment
4. Logical
5. Bitwise
6. Membership
7. Identity
1. ARITHMETIC OPERATORS
Operator Meaning Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
Operator Meaning Example
// Floor division a//b
% Modulus a%b
** Exponentiation a**b
Example:
a = 10
b=3
print(a + b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
2. COMPARISON OPERATORS
Comparison operators produce Boolean results.
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Example:
a = 10
b = 20
print(a < b)
Output:
True
3. LOGICAL OPERATORS
Python provides:
• and
• or
• not
Example:
age = 25
print(age >= 18 and age <= 60)
4. ASSIGNMENT OPERATORS
Basic assignment:
x = 10
Augmented assignments:
x += 5
x -= 2
x *= 3
x /= 2
x //= 2
x %= 2
They provide a compact way of updating a variable.
5. BITWISE OPERATORS
Bitwise operators work on integer bit representations.
Operator Meaning
& AND
` `
^ XOR
~ NOT
<< Left shift
>> Right shift
Example:
a=5
b=3
print(a & b)
6. MEMBERSHIP OPERATORS
Membership operators are:
• in
• not in
Example:
numbers = [10, 20, 30]
print(20 in numbers)
Output:
True
7. IDENTITY OPERATORS
Identity operators:
• is
• is not
They test whether two references refer to the same object, rather than merely
containing equal values.
Example:
a = [1, 2]
b=a
print(a is b)
Output:
True
8. == VS is
This distinction is particularly important at PG level.
==
Tests value equality.
a = [1, 2]
b = [1, 2]
print(a == b)
Result:
True
is
Tests object identity.
print(a is b)
Normally:
False
because a and b are separate list objects.
9. OPERATOR PRECEDENCE
Operator precedence determines the order in which operators are evaluated.
Example:
result = 10 + 5 * 2
Multiplication is evaluated before addition.
Therefore:
10 + (5 * 2) = 20
Parentheses can be used to explicitly control evaluation order.
10. STATEMENTS
A statement is an instruction that performs an action.
Examples:
x = 10
print(x)
Python has several categories of statements.
Common statements
• Assignment statements
• Conditional statements
• Loop statements
• Import statements
• Function definitions
• Class definitions
• break
• continue
• pass
• return
• raise
1. SIMPLE AND COMPOUND STATEMENTS
Simple Statement
Usually occupies one logical line.
x = 10
Compound Statement
Contains a header followed by an indented block.
if x > 0:
print("Positive")
Examples include:
• if
• for
• while
• try
• def
• class
11. EXPRESSIONS
An expression is a combination of literals, variables, operators, function calls, and
other constructs that evaluates to a value.
Examples:
10 + 20
x*y
x > 10
1. TYPES OF EXPRESSIONS
Arithmetic Expression
a+b*c
Relational Expression
a>b
Logical Expression
a > 0 and b > 0
Assignment Expression
Python also supports the assignment expression operator :=, commonly called the
walrus operator.
if (n := len("Python")) > 5:
print(n)
It assigns a value as part of an expression.
Conditional Expression
result = a if a > b else b
12. STATEMENT VS EXPRESSION
Statement Expression
Performs an action Produces/evaluates to a value
Controls program execution Computes a result
Example: if Example: a+b
Example: assignment statement Example: x > 10
Some Python constructs can combine expression evaluation with other effects, so the
distinction is conceptual rather than simply based on whether a line contains =.
13. TYPE CONVERSION
Type conversion means changing an object or value from one data type to another.
There are two major forms:
1. Implicit conversion
2. Explicit conversion
1. IMPLICIT TYPE CONVERSION
Python may automatically perform compatible numeric conversions during
operations.
Example:
x = 10
y = 2.5
z=x+y
print(z)
print(type(z))
The result is a floating-point value.
2. EXPLICIT TYPE CONVERSION
The programmer explicitly requests conversion using functions.
Integer conversion
x = int(10.8)
Result:
10
Float conversion
x = float(10)
String conversion
x = str(100)
Boolean conversion
x = bool(1)
3. COMMON TYPE CONVERSION FUNCTIONS
Function Purpose
int() Convert to integer
float() Convert to floating point
complex() Convert to complex
str() Convert to string
bool() Convert to Boolean
Function Purpose
list() Convert to list
tuple() Convert to tuple
set() Convert to set
dict() Create/convert compatible data to dictionary
14. CONTROL FLOW STATEMENTS
Control flow determines the order in which program statements are executed.
Python's control flow can be broadly divided into:
1. Sequential execution
2. Selection/decision
3. Iteration
4. Jump/control-transfer statements
1. SEQUENTIAL CONTROL
Statements execute from top to bottom.
a = 10
b = 20
c=a+b
print(c)
Execution occurs in sequence.
2. if STATEMENT
The if statement executes a block when a condition is true.
Syntax
if condition:
statement
Example
marks = 80
if marks >= 50:
print("Pass")
3. if-else STATEMENT
Used when there are two alternatives.
if condition:
statement1
else:
statement2
Example:
marks = 40
if marks >= 50:
print("Pass")
else:
print("Fail")
4. if-elif-else
Used for multiple conditions.
marks = 75
if marks >= 90:
grade = "A+"
elif marks >= 75:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "C"
print(grade)
5. NESTED if
An if statement can appear inside another if.
age = 25
citizen = True
if age >= 18:
if citizen:
print("Eligible")
Nested conditions should be used carefully to maintain readability.
6. FOR LOOP
The for loop iterates over an iterable.
Syntax
for variable in iterable:
statements
Example:
for i in [10, 20, 30]:
print(i)
7. RANGE() FUNCTION
range() is commonly used to generate an integer sequence for loops.
for i in range(5):
print(i)
Output:
0
1
2
3
4
Forms include:
range(stop)
range(start, stop)
range(start, stop, step)
8. WHILE LOOP
A while loop executes as long as its condition is true.
i=1
while i <= 5:
print(i)
i += 1
Important
The loop variable or condition must eventually change when necessary; otherwise an
infinite loop may occur.
9. NESTED LOOPS
A loop inside another loop is called a nested loop.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Nested loops are frequently used for:
• Matrix processing
• Pattern generation
• Searching multidimensional data
10. BREAK STATEMENT
break terminates the nearest enclosing loop.
for i in range(10):
if i == 5:
break
print(i)
11. CONTINUE STATEMENT
continue skips the remaining statements of the current iteration.
for i in range(5):
if i == 2:
continue
print(i)
12. PASS STATEMENT
pass performs no operation.
It is useful as a placeholder.
if x > 0:
pass
13. CONTROL FLOW SUMMARY
Control Flow
│
├── Sequential
│
├── Selection
│ ├── if
│ ├── if-else
│ └── if-elif-else
│
├── Iteration
│ ├── for
│ └── while
│
└── Jump
├── break
├── continue
└── pass
15. EXCEPTION HANDLING
What is an Exception?
An exception is an event raised during program execution that interrupts the normal
flow of instructions.
Example:
a = 10
b=0
print(a / b)
This produces a ZeroDivisionError.
1. EXCEPTION VS SYNTAX ERROR
Syntax Error
Occurs when Python cannot parse the program because the code violates Python's
syntax rules.
Example:
if x > 10
print(x)
Exception
Occurs after the program has been successfully parsed and an abnormal condition
arises during execution.
Example:
10 / 0
2. NEED FOR EXCEPTION HANDLING
Without exception handling, an unexpected runtime condition may terminate program
execution.
Exception handling allows programs to:
• Detect errors
• Handle errors
• Display meaningful messages
• Continue execution where appropriate
• Perform cleanup
• Improve reliability
3. TRY-EXCEPT
Syntax
try:
risky_code
except ExceptionType:
handling_code
Example
try:
a = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
4. MULTIPLE EXCEPT BLOCKS
Different exceptions can be handled separately.
try:
x = int(input("Enter number: "))
result = 10 / x
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
5. ELSE BLOCK
The else block executes only when no exception occurs in the try block.
try:
x = int(input("Enter number: "))
except ValueError:
print("Invalid input")
else:
print("Valid number:", x)
6. FINALLY BLOCK
The finally block executes regardless of whether an exception occurs.
It is useful for cleanup operations.
try:
file = open("[Link]")
data = [Link]()
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed")
When working with files, a with statement is generally preferred because it handles
resource cleanup automatically.