FUNDAMENTALS OF
PYTHON
PROGRAMMING
FOR BEGINNERS
UNIT-1
INTRODUCTION TO PYTHON
As per the syllabus of
Dr. A.P.J. Abdul Kalam Technical University, UTTAR PRADESH.
Mr. Rahul Kumar Gupta Dr. Arun Kumar. G
Assistant Professor Professor & HOD
Department of Electronics & Communication Engg.
JSS Academy of Technical Education , Noida, UP.
Unit-1: Introduction to Python
UNIT
1
Introduction to Python
UNIT-1: Introduction to Python: Python variables, Python basic Operators,
Understanding python blocks. Python Data Types, Declaring and using Numeric data
types: int, float etc.
1.1 INTRODUCTION TO PYTHON
• Python is a high-level, easy-to-learn, versatile programming language. It is
widely used in web development, software, data science, AI/ML, automation,
and scientific research.
• It’s simple, English-like syntax makes it popular among both beginners and
professionals.
• Developed by Guido Van Rossum, first released in 1991.
• Focuses on readability and simplicity.
1.1 PYTHON KEY FEATURES
1. Easy to learn : The code looks like plain English, so it’s simple to
understand and write.
2. Line-by-Line : Easier debugging and testing.
Execution
3. Large Standard : Python comes with many ready-made functions to help
Library you do all kinds of tasks like handling files, working with
math, or connecting to the internet.
4. Portable : Runs on multiple platforms (Windows, Linux, macOS).
5. Flexible Coding Styles : Supports procedural, object-oriented, and functional
programming styles.
Key Points:
1. Free and open-source : Anyone can use/modify.
2. Cross-platform : Works on Windows, Mac, Linux, and other operating
systems.
3. Interpreted : The code runs line-by-line, making it easy to debug and
test.
4. Multi-paradigm : Anyone can use/modify.
Fundamentals of Python Programming for Beginners 1
Unit-1: Introduction to Python
Simple example Program
print("Hello, JSS ECE STUDENTS!")
OUTPUT:
Hello, JSS ECE STUDENTS!
Explanation:
This simple program uses the print ( ) function to display a message on the screen.
Anything inside the quotes is treated as text (string). In Python, you don’t need complex
setup just write the code and run it.
1.3 PYTHON APPLICATIONS
Python is versatile and used in many fields:
1. Web Development : Websites, web apps.
2. Data Science : Analyze large datasets and create charts (e.g., Pandas,
Matplotlib).
3. AI & ML : Models, predictions, automation.
4. Automation : Automate repetitive tasks like file handling, data
scraping, and more.
5. Scientific Computing : Solve complex mathematical problems and simulations.
6. Scripting : Write small programs to perform quick tasks or control
other software.
Example Program: Adding Two Numbers
x=3
y=5
print("The sum is:", x + y)
OUTPUT:
The sum is: 8
Explanation:
Here, x and y are variables holding numbers. The print ( ) function displays their sum.
Python can handle numbers, text and lists.
COMMENT LINES IN PYTHON
A comment in Python is a line (or part of a line) in the code that is completely ignored by
the Python during execution. It's used to explain what the code does, making it easier to
understand for others (or yourself later!).
Types of Comments
Type Symbol Description
Single-line # Starts with #, used for brief notes
Multi-line ''' or """ Used for longer explanations or documentation
Example: Single-line Comment
# This program adds two numbers
a=5
b=3
print(a + b) # Output will be 8
Explanation:
• The first line explains the program.
• The comment after print() describes the output.
Fundamentals of Python Programming for Beginners 2
Unit-1: Introduction to Python
Example: Multi-line Comment
'''
This program demonstrates
how to use multi-line comments
in Python.
'''
print("Hello, Python!")
Explanation:
• The triple quotes enclose a block of text.
• Useful for longer descriptions or documentation.
Example: Inline Comment
x = 10 # Initial value
x=x+5 # Add 5 to x
print(x) # Should print 15
Explanation:
• Comments are placed beside code lines to explain each step.
1.4 PYTHON SYNTAX COMPARED TO OTHER PROGRAMMING LANGUAGES
Python is designed for readability and simplicity:
No Semicolons : Most programming languages use; to end a statement.
Python uses a new line instead.
Indentation for Blocks : Other languages use curly brackets {} to group code.
Python uses indentation (spaces or tabs) to define loops,
functions, and classes. This makes Python code look clean
and organized.
Dynamic Typing : You don’t need to declare variable types. Python figures it
out automatically.
TABLE: PYTHON SYNTAX VS OTHER LANGUAGES
Feature Python C/Java/C++
End of Statement New line Semicolon (;)
Code Blocks Indentation (spaces/tabs) Curly brackets {}
Variable Declaration Dynamic (no declaration) Static (must declare)
Readability High (like English) Lower (more symbols)
Example Program: Printing Numbers in a Loop
for i in range (5):
print(i)
OUTPUT:
0
1
2
3
4
Explanation:
The for loop runs 5 times (0 to 4). Each time, it prints the value of i. Notice
the indentation this is how Python knows which lines belong to the loop.
Fundamentals of Python Programming for Beginners 3
Unit-1: Introduction to Python
SUMMARY
Topic Key Point Example
What is Python? Easy, general-purpose language Print ("Hello, World!")
What can Python do? Web, data, AI, Automation, Scripting a = 5; b = 7; print(a+b)
No semicolons; indentation for blocks; dynamic for i in range (5):
Syntax
typing print(i)
1.5 PYTHON VARIABLES
A variable in Python is a name that refers to a value stored in the computer’s memory.
Variables are used to store information that your program can use and modify.
• Variables do not need to be declared with a specific type (int, float, etc.). Python
determines the type automatically.
• The value of a variable can change during program execution (hence the name
variable).
• In Python, you assign a value to a variable using the = operator.
RULES FOR NAMING VARIABLES
Allowed:
• Must start with a letter or an underscore.
• Can contain letters, digits, and underscores.
• Are case sensitive (Value ≠ value).
Not allowed:
• Cannot contain spaces or special characters (@, $, %, -).
• Cannot use Python keywords (if, for, True, etc.).
Valid example
• student_name
• marks_obtained
• _temp
• roll_number10
Invalid example
• 1student (can’t start with a number)
• my-name (hyphen not allowed)
• for (reserved keyword)
1.6 VARIABLE TYPES IN PYTHON
Python is a dynamically typed language, which means you do not have to declare the type
of the variable.
Some common types:
Type Example
int num = 42
float weight = 65.3
str country = "India"
bool is_active = False
Example Program: How to Create Variables
student_name = "Rahul" # student_name is assigned the string "Rahul"
marks = 87 # marks is assigned the integer 87
_pi = 3.14 # _pi is assigned the float 3.14
Fundamentals of Python Programming for Beginners 4
Unit-1: Introduction to Python
x = 10 # x is assigned the integer 10
name = "Virat" # name is assigned the string "Virat"
price = 8.99 # price is assigned the float 8.99
# Numeric values
age = 24
height = 1.75
# String values
person = "Bharat"
language = 'Python'
# Boolean values
is_valid = True
# Multiple Assignment
a, b, c = 1, 2, 3
OUTPUT:
Rahul 87 3.14 10 Virat 8.99 24 1.75 Bharat Python True 1 2 3
Explanation:
• Different variables are created and printed.
• Python automatically assigns types (int, float, str, bool).
• Multiple assignment (a, b, c = 1, 2, 3) stores values in order.
Example Program: Changing Variable Values
score = 5
score = score + 10 # score is now 15
OUTPUT:
Updated Score: 15
Explanation:
• Initially, score = 5.
• After update: score = 5 + 10 = 15.
• The new value (15) replaces the old value.
Example Program: Storing and Printing Values
# Store values in variables
city = "NOIDA"
temperature = 44
print("City:", city)
print("Temperature:", temperature, "°C")
OUTPUT:
City: NOIDA
Temperature: 44 °C
Explanation:
• city stores "NOIDA".
• temperature stores 44.
• print() displays both values with text.
Example Program: Changing Variable Values
# Assign initial value
score = 70
Fundamentals of Python Programming for Beginners 5
Unit-1: Introduction to Python
# Print the original score
print("Original Score:", score)
# Change the value of score
score = 80
#Print the updated score
print("Updated Score:", score)
OUTPUT:
Original Score: 70
Updated Score: 80
EXPLANATION:
• At first, score = 70.
• The value is reassigned to 80.
• Printing shows the updated value.
Example Program: Swap Two Variables
a = 10
b = 22
a, b = b, a # Swap values
print("a:", a)
print("b:", b)
OUTPUT:
a: 22
b: 10
Explanation:
• Initially, a = 10, b = 22.
• After swapping, a = 22, b = 10.
• Python allows swapping in a single line.
Program 4: Calculate Area of a Circle
radius = 5
pi = 3.14159
area = pi * radius * radius
print("Area of the circle:", area)
OUTPUT:
Area of the circle: 78.53975
Explanation:
• Formula for area = π × r².
• Here, 3.14159 × 5 × 5 = 78.53975.
• Printed result shows the calculated area.
Fundamentals of Python Programming for Beginners 6
Unit-1: Introduction to Python
Example Program: User Input and Output
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello", name, "you are", age, "years old.")
OUTPUT:
Enter your name: Arun
Enter your age: 25
Hello Arun you are 25 years old.
Explanation:
• input() takes values from the user (always as string).
• First input stores "Arun" in name.
• Second input stores "25" in age.
• print() combines and displays them.
Write Python program to swap two numbers without using
Intermediate/Temporary variables. Prompt the user for input.
Solution:
# Program to swap two numbers without using a temporary variable
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Before swapping: num1 =", num1, ", num2 =", num2)
# Swapping using tuple unpacking
num1, num2 = num2, num1
print("After swapping: num1 =", num1, ", num2 =", num2)
Output:
Enter first number: 10
Enter second number: 25
Before swapping: num1 = 10 , num2 = 25
After swapping: num1 = 25 , num2 = 10
Explanation:
1. Input from User:
• input() prompts the user to enter two numbers.
• int() converts the input strings to integers.
• These values are stored in num1 and num2.
2. Before Swapping:
• The original values of num1 and num2 are printed so the user can see the initial
state.
3. Swapping Logic:
• num1, num2 = num2, num1 is a Python feature called tuple unpacking.
• It swaps the values in a single line:
• The right-hand side creates a tuple (num2, num1)
• The left-hand side unpacks it back into num1 and num2, effectively swapping
them.
Fundamentals of Python Programming for Beginners 7
Unit-1: Introduction to Python
4. After Swapping:
• The new values of num1 and num2 are printed, showing that the swap was
successful.
Write a Python program to construct the following pattern, using a nested for loop.
*
**
***
****
*****
****
***
**
*
Solution:
Method-1 Method-2
# Simple star pattern # Simple star pattern
for i in range(1, 6): n=5
print("* " * i)
for i in range(1, n + 1):
for i in range(4, 0, -1): print("* " * i)
print("* " * i)
for i in range(n - 1, 0, -1):
print("* " * i)
Explanation: Explanation:
• The first loop (range(1, 6)) prints • n = 5 → The pattern will go up to 5 stars in
increasing stars from 1 to 5. the middle.
• The second loop (range(4, 0, -1)) • First loop (for i in range(1, n+1)):
prints decreasing stars from 4 to 1. • Prints stars from 1 star up to 5 stars
• print("* " * i) uses string (increasing order).
multiplication to repeat "* " i times. • Second loop (for i in range(n-1, 0, -1)):
• Prints stars from 4 stars down to 1 star
(decreasing order).
• print("* " * i) → Prints "* " repeated i times.
What do you understand by local and global variables in Python? Give the
difference between them.
Local Variables:
• Defined inside a function i.e., belongs only to its function.
• Can be accessed only within that function.
• Created when the function starts and destroyed when the function ends.
Example:
def greet():
message = "Hello!" # local variable
print(message)
Fundamentals of Python Programming for Beginners 8
Unit-1: Introduction to Python
greet()
# print(message)
# This would cause an error: message is not defined outside the function
OUTPUT:
Hello!
Global Variables:
• Defined outside all functions i.e. belongs to the whole program.
• Can be accessed throughout the program, including inside functions (unless a local
variable with the same name exists).
• Useful for values that need to be shared across multiple functions.
Example:
name = "Rahul" # global variable
def greet():
print("Hello,", name)
greet()
print("Welcome,", name)
OUTPUT:
Hello, Rahul
Welcome, Rahul
Note:
• Local variable → exists only inside the function.
• Global variable → can be used anywhere in the program.
Table: Difference between local and global variables
Feature Local Variable Global Variable
Scope Inside the function only Entire program
Declaration location Inside a function Outside all functions
Exists only while the Exists as long as the
Lifetime
function runs program runs
Not accessible outside its Accessible both inside and
Accessibility
function outside functions
Cannot modify a global
Modification inside a No keyword needed
variable unless you use the
function (already global)
global keyword
1.7 PYTHON BASIC OPERATORS
Python provides a rich set of operators to perform operations on variables and data.
Operators are special symbols or keywords that tell the interpreter to carry out specific
operations such as arithmetic, assignment, comparison, logical, and more.
1. Arithmetic Operators
Arithmetic operators are used for mathematical operations.
Operator Description Example (a=10, b=3) Result
+ Addition a+b 13
Fundamentals of Python Programming for Beginners 9
Unit-1: Introduction to Python
Operator Description Example (a=10, b=3) Result
- Subtraction a-b 7
* Multiplication a*b 30
/ Division a/b 3.333...
// Floor Division a // b 3
% Modulus (Remainder) a%b 1
** Exponentiation a ** b 1000
Example Program: Basic Arithmetic Operations
a = 10
b=3
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: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus: 1
Exponentiation: 1000
2. Assignment Operators
Basic Assignment Operator
Assignment operators are used to assign values to variables and modify them.
Operator Description Example
= Assigns value x = 10
Augmented Assignment Operators
These combine an operation with assignment
Operator Description Example Equivalent to
+= Add and assign x += 3 x=x+3
-= Subtract and assign x -= 2 x=x-2
*= Multiply and assign x *= 5 x=x*5
Fundamentals of Python Programming for Beginners 10
Unit-1: Introduction to Python
Operator Description Example Equivalent to
/= Divide and assign x /= 2 x=x/2
//= Floor divide assign x //= 3 x = x // 3
%= Modulus and assign x %= 4 x=x%4
**= Exponentiate assign x **= 2 x = x ** 2
Example Program: Augmented Assignment Operators
x=5
x += 3
print("After += :", x) # Output: 8
x *= 2
print("After *= :", x) # Output: 16
x //= 3
print("After //= :", x) # Output: 5
Explanation:
1. Initial assignment
x = 5 sets x to 5.
2. Addition assignment (+=)
x += 3 is shorthand for x = x + 3.
New value: 5 + 3 = 8.
3. Multiplication assignment (*=)
x *= 2 is shorthand for x = x * 2.
New value: 8 * 2 = 16.
4. Floor-division assignment (//=)
x //= 3 is shorthand for x = x // 3.
Floor division discards the remainder: 16 // 3 = 5.
Each augmented assignment updates x in place and then prints the current value.
3. Comparison Operators
These compare two values and return a Boolean (True or False).
Example
Operator Description Result
(a = 5, b = 3)
== Equal to a == b False
!= Not equal to a != b True
> Greater than a>b True
< Less than a<b False
>= Greater than or equal to a >= b True
Fundamentals of Python Programming for Beginners 11
Unit-1: Introduction to Python
Example
Operator Description Result
(a = 5, b = 3)
<= Less than or equal to a <= b False
Example Program: Comparison Between Two Numbers
a=5
b=3
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a <= b) # False
4. Logical Operators
Logical operators are used to combine conditional statements.
Example
Operator Description Result
(a=4 & b=2)
and Logical AND (a > 2 and b < 5) True
or Logical OR (a > 10 or b < 5) True
not Logical NOT not(a == b) True
Example Program: Logical Operators in Action
a=4
b=2
print(a > 2 and b > 1) # True
print(a < 2 or b < 1) # False
print(not(a == b)) # True
5. Identity Operators
They check if two variables point to the same memory location (object).
Operator Description Example Result
is Same object in memory x is y True/False
is not Different objects x is not y True/False
Example Program: Lists (Different Objects, Same Values)
# Assign values
x = [1, 2, 3]
y=x
z = [1, 2, 3]
# Check identity
print(x is y) # True (y refers to the same object as x)
print(x == z) # True (same values)
print(x is z) # False (z has the same values, but is a different object)
Fundamentals of Python Programming for Beginners 12
Unit-1: Introduction to Python
print(x is not z) # True (x and z are not the same object)
OUTPUT:
True
True
False
True
Explanation:
• x and y → point to the same object in memory, so x is y → True.
• x and z → contain the same values but are different objects, so x is z → False.
• Hence, x is not z → True.
• == → compares values
• is → compares memory reference (identity)
Example Program: Integers (Caching in Python)
a = 100
b = 100
c = 500
d = 500
print(a is b) # True (small integers are cached in Python)
print(c is d) # False (large integers may not be cached, different objects)
OUTPUT:
True
False
Explanation:
• a is b → True, Python internally caches small integers (typically from −5 to
256). So, a and b both point to the same memory location for the value 100.
• c is d → False, Larger integers like 500 are not always cached. So c and d may
refer to different memory locations, even though their values are the same.
Example Program: Strings (Immutable and Cached Sometimes)
s1 = "hello"
s2 = "hello"
s3 = "".join(["he", "llo"]) # creates a new string object
print(s1 == s2) # True (same value)
print(s1 is s2) # True (Python reuses same object for small strings)
print(s1 is s3) # False (s3 is a different object even though value is same)
OUTPUT:
True
True
False
Explanation:
1. s1 = "hello" and s2 = "hello"
• In Python, strings are immutable (cannot be changed after creation).
• For efficiency, Python caches small strings (called string interning).
• So both s1 and s2 point to the same memory location.
• That’s why:
✓ s1 == s2 → True (values are same).
✓ s1 is s2 → True (same object in memory).
Fundamentals of Python Programming for Beginners 13
Unit-1: Introduction to Python
2. s3 = "".join(["he", "llo"])
• Here we build the string dynamically using "".join().
• Even though the value of s3 is "hello", Python creates a new object in memory.
• That’s why:
✓ s1 == s3 → would be True (same value).
✓ s1 is s3 → False (different objects in memory).
6. Membership Operators
Test whether a sequence contains a value.
Operator Description Example Result
in Value found 20 in [10, 20, 30] True
not in Value not found 15 not in [10, 20, 30] True
Example with List Example with String
nums = [10, 20, 30] word = "apple"
print(20 in nums) print("a" in word)
# True → because 20 is inside the list # True → "a" is in "apple"
print(15 not in nums) print("z" not in word)
# True → because 15 is not inside the list # True → "z" is not in "apple"
OUTPUT: OUTPUT:
True True
True True
7. Bitwise Operators
Bitwise operators operate on the binary bits of numbers and perform operations bit by
bit at a time.
Operator Description Example Result
& Bitwise AND 5&3 1
| Bitwise OR 5|3 7
^ Bitwise XOR 5^3 6
~ Bitwise NOT ~5 -6
<< Bitwise left shift 5 << 1 10
>> Bitwise right shift 5 >> 1 2
Example Program:
a=5 # Binary: 0101
b=3 # Binary: 0011
print(a & b) #1
print(a | b) #7
print(a ^ b) #6
print(~a) # -6
Fundamentals of Python Programming for Beginners 14
Unit-1: Introduction to Python
print(a << 1) # 10
print(b >> 1) #1
Explanation: NOT (~) Operation
1. 5 = 00000101 B → Apply NOT (~) → flip every bit: 11111010
2. Now, this binary value (11111010) represents a negative number in Python (and in
most computers) because of two’s complement representation.
3. Two’s Complement Rule:
Invert all bits again: 11111010 → 00000101
Add 1 → 00000101 + 1 = 00000110 (6 in decimal)
Put a negative sign → -6
So ~5 = -6
Table: Summary of all the operators
Operator
Operators Explanation Example
Type
Perform mathematical
+ , - , * , / , // , % , 10 + 3 → 13
Arithmetic calculations (addition,
** 10 // 3 → 3
subtraction, etc.)
Assignment = Assign values to variables x = 10
x = 5;
Augmented += , -= , *= , /= , //= Combine operation with
x += 3 → 8
Assignment , %= , **= assignment
x *= 2 → 16
== , != , > , < , >= , Compare values and return 5 > 3 → True
Comparison
<= Boolean (True/False) 5 == 3 → False
Combine conditional (4 > 2 and 2 < 5) →
Logical and , or , not
expressions True
Check if two objects share x is y ,
Identity is , is not
the same memory location x is not z
Check whether a value "a" in "apple" → True
Membership in , not in exists inside a sequence 15 not in [10,20,30] →
(list, string, tuple, etc.) True
5&3→1
5^3→6
Operate at the binary level
Bitwise `& , ^ , ~ , << , >>` ~5 → -6
(bit-by-bit operations)
5 << 1 → 10
3 >> 1 → 1
1.7.1 OPERATOR PRECEDENCE
• Operator precedence means the priority order in which Python evaluates
different operators in an expression.
• When an expression has multiple operators, Python follows precedence rules to
decide which operation to perform first.
Example: Operator Precedence
x = 10 + 2 * 3
print(x)
OUTPUT:
16
Explanation:
1. According to Python's precedence rules, multiplication (*) is evaluated before
addition (+).
Fundamentals of Python Programming for Beginners 15
Unit-1: Introduction to Python
2. So, 2 * 3 = 6 is calculated first.
3. Then, 10 + 6 = 16 is evaluated.
Thus, the final value of x is 16.
Table: Operator Precedence
Precedence
Operator(s) Description Associativity
Level
1 (Highest) () Parentheses (grouping) Left → Right
2 ** Exponentiation (power) Right → Left
Unary plus, Unary minus,
3 +x, -x, ~x Right → Left
Bitwise NOT
Multiplication, Division,
4 *, /, //, % Left → Right
Floor division, Modulus
5 +,- Addition, Subtraction Left → Right
6 << , >> Bitwise shift operators Left → Right
7 & Bitwise AND Left → Right
8 ^ Bitwise XOR Left → Right
9 ` ` Bitwise OR
10 < , <= , > , >= , == , != Comparison operators Left → Right
11 not Logical NOT Right → Left
12 and Logical AND Left → Right
13 or Logical OR Left → Right
`= , += , -= , *= , /= , //= , %= , Assignment
14 (Lowest) = , <<= , >>=`
**= , &= , ^= , operators
1.7.2 ASSOCIATIVITY IN PYTHON
• Associativity defines the direction of evaluation (left → right or right → left)
when two or more operators of the same precedence appear in an expression.
• It comes into play only when two or more operators with equal precedence
are used in a single expression.
Types of Associativity
1. Left-to-Right Associativity
2. Right-to-Left Associativity
1. Left-to-Right Associativity
• Most operators in Python (arithmetic, comparison, bitwise, logical and/or)
follow this rule.
• Python evaluates them from left to right.
Example:
x = 10 - 5 + 2
# (10 - 5) + 2 = 5 + 2 = 7
print(x) # Output: 7
y = 20 / 5 * 2
# (20 / 5) * 2 = 4 * 2 = 8.0
print(y) # Output: 8.0
2. Right-to-Left Associativity
• Some Python operators like ** (exponentiation), = (assignment), and not (logical
NOT) follow this rule.
• Python evaluates them from right to left.
Fundamentals of Python Programming for Beginners 16
Unit-1: Introduction to Python
Example:
# Example 1: Exponentiation (**)
x = 2 ** 3 ** 2
print(x)
# Python does: 2 ** (3 ** 2) = 2 ** 9 = 512
Example:
Example 2: Assignment (=)
a = b = 10 print(a, b)
Python does: b = 10, then a = b
OUTPUT:
10 10
Table: Summary of Associativity Type
Associativity Type Operators Evaluation Direction
Left-to-right +, -, *, /, %, ==, <, > Left to right
Right-to-left **, =, not Right to left
Discuss various categories of operators in python. Find and explain stepwise
solution of following expressions if a=3, b=5, c=10.
i. a &b<<2//5**2+c^b
ii. b>>a**2<<2>>b**2^c**3
AKTU 2022–23, Even Sem., Marks: 10
Solution:
i. a &b<<2//5**2+c^b
Given: a = 3, b = 5, c = 10
Step Operation Expression
Step 1 Exponentiation: 5**2 = 25 a & b << 2 // 25 + c ^ b
Step 2 Floor division: 2 // 25 = 0 a & b << 0 + c ^ b
Step 3 Addition: 0 + c = 10 a & b << 10 ^ b
Step 4 Left shift: b << 10 = 5 << 10 = 5120 a & 5120 ^ b
Step 5 Bitwise AND: 3 & 5120 = 0 0^b
Step 6 Bitwise XOR: 0 ^ 5 = 5 5
Final Answer: 5
Note:
a & b << 2 // 5**2 + c ^ b
= 3 & 5 << 2 // 25 + 10 ^ 5
= 3 & 5 << 0 + 10 ^ 5
= 3 & 5 << 10 ^ 5
= 3 & 5120 ^ 5
=0^5
=5
Fundamentals of Python Programming for Beginners 17
Unit-1: Introduction to Python
ii. b >> a ** 2 << 2 >> b ** 2 ^ c ** 3
Given: a = 3, b = 5, c = 10
Step Operation Result / Expression
Step 1 Exponentiation: a**2 = 9, b**2 = 25, c**3 = 1000 b >> 9 << 2 >> 25 ^ 1000
Step 2 Right Shift: 5 >> 9 = 0 0 << 2 >> 25 ^ 1000
Left Shift: 0 << 2 = 0 0 >> 25 ^ 1000
Right Shift: 0 >> 25 = 0 0 ^ 1000
Step 3 Bitwise XOR: 0 ^ 1000 = 1000 1000
Final Answer: 1000
Note:
b >> a ** 2 << 2 >> b ** 2 ^ c ** 3
= 5 >> 9 << 2 >> 25 ^ 1000
= 0 << 2 >> 25 ^ 1000
= 0 >> 25 ^ 1000p
= 0 ^ 1000
= 1000
What is short circuit evaluation? What is printed by the following Python program?
a=0
b=2
c=3
x = c or a
print(x)
Solution:
• Short circuit evaluation means Python stops evaluating a logical expression
as soon as the result is known.
• It applies to the logical operators: and and or.
• Evaluated left to right.
• For or:
✓ Returns the first truthy value it finds.
✓ If the first operand is truthy, Python does not evaluate the rest.
• For and:
✓ Returns the first falsy value it finds.
✓ If the first operand is falsy, Python does not evaluate the rest.
• This improves performance and avoids unnecessary or unsafe operations.
NOTE:
• Short circuit with OR → stops at the first truthy.
• Short circuit with AND → stops at the first falsy.
What is printed by the following Python program?
a=0
b=2
c=3
x = c or a
print(x)
OUTPUT:
3
Fundamentals of Python Programming for Beginners 18
Unit-1: Introduction to Python
Explanation:
• c = 3 → This is a truthy value (non-zero).
• a = 0 → This is a falsy value.
• x = c or a → Since c is truthy, Python does not evaluate a.
• So, x = 3
Example with or
a=0
b=5
result = a or b
print(result)
OUTPUT:
5
Explanation:
✓ a = 0 → falsy.
✓ Python checks next operand b.
✓ b = 5 (truthy), so result = 5.
Example with and
a=0
b=5
result = a and b
print(result)
OUTPUT:
0
Explanation:
✓ a = 0 → falsy.
✓ Since the first operand is falsy, Python stops and returns 0 immediately.
Example Program with or & and
a=0
b=5
c = 10
# Using OR
result1 = a or b
print("Result of a or b:", result1)
# Using AND
result2 = a and c
print("Result of a and c:", result2)
OUTPUT:
Result of a or b: 5
Result of a and c: 0
Explanation:
• a or b
✓ a = 0 (falsy), so Python checks b.
✓ b = 5 (truthy) → result = 5.
• a and c
✓ a = 0 (falsy), so Python stops immediately.
✓ result = 0.
Fundamentals of Python Programming for Beginners 19
Unit-1: Introduction to Python
1.8 UNDERSTANDING PYTHON BLOCKS
In Python, blocks are sections of code grouped together. These blocks are crucial for
defining the structure of programs such as functions, loops, conditionals, and classes.
Unlike languages such as C, C++ or Java (which use { } braces), Python uses indentation
(spaces or tabs) to denote blocks of code.
1.8.1 BLOCK IN PYTHON
A block is a group of statements that are executed together. For example, the body of a
loop, function, or class forms a block. The beginning and end of a block are defined by the
level of indentation.
Key Points
• Indentation is used to define blocks instead of braces or begin/end keywords.
• All statements within the same block must have the same indentation level.
• Python enforces indentation strictly, making the code more readable.
INDENTATION RULES
• A colon : at the end of a line signals the start of an indented block.
• Common examples: if, for, while, def, class, try.
• Indentation should be consistent (preferably 4 spaces).
• Don’t mix tabs and spaces.
EXAMPLE: Simple Block with if
keyword condition/definition:
statement1
statement2
...
statement_outside_block
Explanation:
• keyword → if, for, while, def, class, try, etc.
• : → colon marks the start of the block.
• Indented lines (4 spaces recommended) → form the block.
• Once indentation ends → the block is finished.
EXAMPLE: Simple Block with if
if True:
print("This is inside the block")
print("Still inside the block")
print("This is outside the block")
Output:
This is inside the block
Still inside the block
This is outside the block
Explanation:
• The two indented print statements belong to the if block.
• The last print (no indentation) is outside the block.
Fundamentals of Python Programming for Beginners 20
Unit-1: Introduction to Python
EXAMPLE: Block in if Statement
x = 10
if x > 5:
print("x is greater than 5") # inside block
print("Condition is True") # inside block
print("Program completed") # outside block
Output:
x is greater than 5
Condition is True
Program completed
Explanation:
• Both print statements with indentation belong to the if block.
• The last print is outside (no indentation).
EXAMPLE: if-else Block
x = 15
if x > 10:
print("x is greater than 10")
else:
print("x is 10 or less")
print("Program completed")
Output:
x is greater than 10
Program completed
Explanation:
• First two lines form one block (under if).
• The else block has its own indented statement.
EXAMPLE: Block in if-else
num = 3
if num % 2 == 0:
print("Even number") # inside if block
else:
print("Odd number") # inside else block
print("Check completed") # outside block
Output:
Odd number
Check completed
Explanation:
• The first print belongs to the else block because num=3.
• The last print runs outside both blocks.
1.8.2 BLOCKS IN FUNCTIONS
• In Python, a function groups a set of statements into a block so that they can be
reused whenever the function is called.
• A function block begins after def funcname(): and includes all indented lines
inside.
Fundamentals of Python Programming for Beginners 21
Unit-1: Introduction to Python
SYNTAX:
def function_name(parameters):
# Block starts here (indented statements)
statement1
statement2
...
return value # (optional)
Explanation:
• def → keyword used to define a function.
• function_name → user-defined name for the function.
• (parameters) → input values (optional).
• : → colon signals the start of a function block.
• Indented statements → form the function’s block.
• return → used to send back a value (optional).
Example: Function Block without Return
def greet(name):
print("Hello,", name)
print("Welcome to Python!")
greet("JSS")
Output:
Hello, JSS
Welcome to Python!
Explanation:
• All statements inside def greet(name): are in the function block.
• def greet(name):
This line is calling the greet function and giving it "JSS" as the input. So, when the
function runs, it prints:
Example: Function Block with Return
def add(a, b):
result = a + b
return result # block ends here
print(add(5, 10))
Output:
15
Explanation:
• The indented lines are the block inside the function.
• The function ends when indentation returns to normal (no spaces).
1.8.3 Blocks in Loops
A loop block contains all indented statements under for or while.
digits = [1, 2, 3]
for value in digits:
print("Value:", value)
square = value ** 2
print("Square:", square)
print("Process completed")
Fundamentals of Python Programming for Beginners 22
Unit-1: Introduction to Python
Output:
Value: 1
Square: 1
Value: 2
Square: 4
Value: 3
Square: 9
Process completed
Explanation:
• The two print statements are part of the loop block.
• The last print executes after the loop (outside block).
1.8.4 Nested Blocks
In Python, a nested block means placing one block of code inside another block.
Examples include:
• A loop inside a function.
• An if block inside a for loop.
• Functions inside classes.
General Syntax of Nested Blocks
outer_block_statement:
# statements of outer block
inner_block_statement:
# statements of inner block
# back to outer block
# outside both blocks
Explanation:
• An outer block starts after a colon :
• The inner block is indented further inside the outer block.
• When indentation reduces, control goes back to the outer block.
Example: If inside a For (Nested Block)
for i in range(3):
print("i:", i)
if i % 2 == 0:
print("Even")
else:
print("Odd")
Output:
i: 0
Even
i: 1
Odd
i: 2
Even
Explanation:
• The if-else block is inside the for loop block.
Fundamentals of Python Programming for Beginners 23
Unit-1: Introduction to Python
Example: Function with Nested Loop
def multiplication_table(n):
for i in range(1, 6):
print(n, "x", i, "=", n*i)
multiplication_table(3)
Output:
3x1=3
3x2=6
3x3=9
3 x 4 = 12
3 x 5 = 15
Explanation:
• The function defines a block.
• The for loop inside it forms a nested block.
Invalid Indentation (Error Example)
Python raises an error if the indentation is wrong.
Example: Indentation Error
# This will cause an Indentation Error
if True:
print("Hello")
print("World”) # Incorrect indentation
Output:
IndentationError: unindent does not match any outer indentation level
Explanation: Mixing spaces and tabs or misaligning indentation causes errors.
Block Usage in Python
Block Type Starts With Example Syntax Usage Description
Runs different code based
Conditional if, elif, else if x > 5:
on condition
Repeats a set of
Loop for, while for i in range(5):
statements
Groups reusable
Function def func(): def add(a,b):
instructions
Defines objects (variables
Class class MyClass: class Student:
+ methods)
Handles errors during
Exception try, except try: ... except:
execution
Note:
• Python uses indentation (spaces or tabs) to define blocks of code.
• It’s very important to use correct indentation if it’s wrong, Python will give an
error.
Fundamentals of Python Programming for Beginners 24
Unit-1: Introduction to Python
• Every control structure (like if, for, while, def, class) needs a block under it with
indented lines.
1.9 PYTHON DATA TYPES
Python has several built-in data types used to store different kinds of data. These data
types are automatically assigned based on the value.
The main categories of python data types
• Numeric Types: int, float, complex
• Text Type: str
• Sequence Types: list, tuple, range
• Mapping Type: dict
• Set Types: set, frozenset
• Boolean Type: bool
• Binary Types: bytes, byte array, memory view
• None Type: None Type
Table: Python Data Types general syntax
Type General Syntax Example
int variable = integer_value x = 10
float variable = decimal_value pi = 3.14
complex variable = real + imaginaryj z = 2 + 3j
variable = "text" variable = 'text' variable = name = "Python"
str
"""multi-line text"""
list variable = [item1, item2, item3] fruits = ["apple", "banana", "cherry"]
tuple variable = (item1, item2, item3) point = (3, 4, 5)
range variable = range(start, stop, step) nums = range(1, 6)
dict variable = {key1: value1, key2: value2} student = {"name": "Raj", "age": 20}
set variable = {item1, item2, item3} numbers = {1, 2, 3}
frozenset variable = frozenset([item1, item2, item3]) fs = frozenset([1, 2, 3])
bool variable = True variable = False is_active = True
bytes variable = b"text" b = b"Hello"
bytearray variable = bytearray([value1, value2, value3]) ba = bytearray([65, 66, 67])
memoryview variable = memoryview(b"binary_data") mv = memoryview(b"Python")
NoneType variable = None x = None
PYTHON DATA TYPES WITH EXAMPLES
1. Numeric Data Types
a. Integers (int): int → Whole numbers (positive, negative, zero).
• Store whole numbers (e.g., 23, -1000)
• Unlimited length
Example Program: Integer Data Type
x = 20
print(type(x)) # Output: <class 'int'>
Output:
<class 'int'>
Fundamentals of Python Programming for Beginners 25
Unit-1: Introduction to Python
Explanation:
• The variable x is assigned an integer value 20.
• The type() function confirms that it is of class int, meaning it can store integers of
any length.
b. Floating-Point Numbers (float): float → Decimal or real numbers.
• Store real numbers with decimal points (e.g., 3.14, -30.8)
• Can also be written in scientific notation (e or E for powers of 10).
Example Program: Floating-Point Data Type
x = 3.14
print(type(x)) # Output: <class 'float'>
Output:
<class 'float'>
Explanation:
• Here, x is assigned 3.14, a decimal number.
• The type() function shows it is of the float type, which can store real numbers with
fractional parts.
Example Program: Division vs Floor Division
a=5
b=2
print(a / b) # Division → float
print(a // b) # Floor Division → int
Output:
2.5
2
Explanation:
• / always returns float
• // returns integer (floor value)
c. Complex (complex)
• Numbers with real and imaginary parts.
• Written as real + imag j (where j is the imaginary unit).
Example Program: Complex Number Properties
c = 1 + 2j
print(type(c)) # Output: <class 'complex'>
print([Link]) # Output: 1.0
print([Link]) # Output: 2.0
Output:
<class 'complex'>
1.0
2.0
Explanation:
• Variable c is a complex number with a real part (1) and an imaginary part (2).
• [Link] gives the real part, and [Link] gives the imaginary part.
Note:
• int: Integer numbers (e.g., 3, -4, 200)
• float: Floating-point numbers (e.g., 1.14, -0.01)
• complex: Complex numbers (e.g., 3 + 4j)
Fundamentals of Python Programming for Beginners 26
Unit-1: Introduction to Python
Example Program: int, float, and complex Together
x = 20 # int
y = 3.14 # float
z = 1 + 2j # complex
print("x:", x)
print("y:", y)
print("z:", z)
Output:
x: 20
y: 3.14
z: (1+2j)
Explanation:
• Python automatically assigns int, float, and complex based on the values.
• z is a complex number where 1 is the real part and 2 is the imaginary part.
2. Text Type
String (str): str → Sequence of characters inside single, double, or triple quotes.
• Stores a sequence of characters
• Written within single, double, or triple quotes (' ' or " " or “’ “’).
• Cannot be changed after creation (Immutable)
Example Program: Single and Double Quoted Strings
name = "Rahul"
message = 'Welcome to Phon!'
print(name)
print(message)
Output:
Rahul
Welcome to Python!
Explanation:
• Strings can be single or double quoted.
• They are used for storing text.
Example Program: String Methods and Indexing
name = "Hello, Rahul!" name = "Hello, Rahul!"
print(type(name)) # Output: <class 'str'> print(type(name)) # Output: <class 'str'>
print([Link]( )) # Output: hello, rahul! print([Link]()) # Output: HELLO, RAHUL!
print(name [0:5]) # Output: Hello print(name[7:13]) # Output: Rahul
Output: Output:
<class 'str'> <class 'str'>
hello, rahul! HELLO, RAHUL!
Hello Rahul!
Explanation: Explanation:
• name = "Hello, Rahul!" • name = "Hello, Rahul!"
→ A string is stored in the variable name. → Variable name stores a string value.
• print(type(name)) • print(type(name))
→ Shows the data type of name, which is a → Shows the data type of name, which is <class
string → <class 'str'>. 'str'> (string).
Fundamentals of Python Programming for Beginners 27
Unit-1: Introduction to Python
• print([Link]()) • print([Link]())
→ Converts the whole text into small letters → Converts all letters of the string into capital
→ hello, rahul!. letters → HELLO, RAHUL!.
• print(name[0:5]) • print(name[7:13])
→ Takes characters from index 0 to 4 → → Takes characters from index 7 up to 12 →
"Hello". "Rahul!".
Example Program: String Immutability Error
text = "Python"
# Attempting to change the first character
# text[0] = "J" # This will raise an error: 'str' object does not support item
assignment
print(text) # Output: Python
Output:
Rahul
Welcome to Python!
Explanation:
• In Python, strings are immutable, which means once a string is created, it
cannot be changed.
• You cannot modify individual characters of a string using indexing like text[0] = "J"
this will raise an error.
• If you want to change the string, you must create a new string.
Example Program: Correct Way to Modify a String
text = "Python"
new_text = "J" + text[1:] # Replace first character with 'J'
print(new_text) # Output: Jython
Output:
Jython
Explanation:
• Here, we create a new string by combining "J" with the rest of the original string
(text[1:]).
• This is how string modification is done in Python by creating a new string, not
by changing the original.
3. Sequence Types
a. List (list):
• A list is an ordered, mutable (changeable) collection.
• You can add, remove, or update elements.
• Lists can store items of different data types (e.g., numbers, strings, etc.).
• Defined using square brackets [ ].
Example Program: Append to list Example Program: remove from the list
fruits_list = ["banana", "orange"] fruits_list = ["banana", "orange"]
fruits_list.append("apple") fruits_list.remove("orange")
print(fruits_list) print(fruits_list)
Output: Output:
['banana', 'orange', 'apple'] ['banana']
Fundamentals of Python Programming for Beginners 28
Unit-1: Introduction to Python
Explanation: Explanation:
• We start with a list: ["banana", "orange"]. • We start with a list: ["banana", "orange"].
• The .append("apple") function adds "apple" • The .remove("orange") function removes "orange"
to the end of the list. from the list.
• After appending, the list becomes: ['banana', • After removal, the list becomes: ['banana'].
'orange', 'apple'].
Example Program: Accessing List Elements
fruits = ["apple", "banana", "mango"]
print(fruits)
print(fruits[1]) # Access second item
Output:
['apple', 'banana', 'mango']
banana
Explanation:
• Lists use indexing.
• Index starts from 0. So fruits[1] → "banana".
Example Program: Updating List Elements
fruits = ["apple", "banana", "mango"]
print("Original List:", fruits)
# Change the second item
fruits[1] = "orange"
print("Modified List:", fruits)
Output:
Original List: ['apple', 'banana', 'mango']
Modified List: ['apple', 'orange', 'mango']
Explanation:
• The original list is ['apple', 'banana', 'mango'].
• Using fruits[1] = "orange", we replace "banana" with "orange".
• The updated list becomes ['apple', 'orange', 'mango'].
b. Tuple (tuple)
• A tuple is like a list, but it is immutable (cannot be changed).
• Ordered, but elements cannot be added, removed, or updated.
• Defined using parentheses ( ).
Example Program: Tuple Indexing
my_tuple = (1, 2, 3)
print(type(my_tuple)) # <class 'tuple'>
print(my_tuple[1]) #2
Output:
<class 'tuple'>
2
Fundamentals of Python Programming for Beginners 29
Unit-1: Introduction to Python
Explanation:
• my_tuple is of type tuple.
• my_tuple[1] → value at index 1, which is 2.
Example Program: Tuple with Mixed Data Types
my_info = ("Rahul", 21, 5.9)
print(my_info)
Output:
('Rahul', 21, 5.9)
Explanation:
• A tuple can store different types of values (string, int, float).
• Order is preserved, but values cannot be changed.
Example Program: Accessing Last Element
fruits = ("apple", "banana", "mango")
print(fruits[-1]) # Access last item
Output:
mango
Explanation:
• Negative indexing works with tuples.
• -1 gives the last element.
Example Program: Tuple Packing and Unpacking
numbers = (10, 20, 30) # Packing
a, b, c = numbers # Unpacking
print(a, b, c)
Output:
10 20 30
Explanation:
• A tuple (10, 20, 30) is created.
• Values are unpacked into variables a, b, c.
Example Program: Single-Element Tuple
single = (5,) # Notice the comma
print(type(single))
Output:
<class 'tuple'>
Explanation:
• Without the comma, (5) is just an integer.
• (5,) with a comma makes it a tuple.
Example Program: Nested Tuple
nested = (1, (2, 3), 4)
print(nested[1]) # Access second element
print(nested[1][0]) # Access first element of the inner tuple
print(nested[1][1]) # Access second element of the inner tuple
print(nested[2]) # Access third element
Fundamentals of Python Programming for Beginners 30
Unit-1: Introduction to Python
Output:
(2, 3)
2
3
4
Explanation:
1. nested = (1, (2, 3), 4) → a tuple with three elements: 1, (2, 3), and 4.
2. nested[1] → second element → (2, 3)
3. nested[1][0] → first element of (2, 3) → 2
4. nested[1][1] → second element of (2, 3) → 3
5. nested[2] → third element of nested → 4
Example Program: Attempt to modify the first element of a tuple (will result in an
error).
# Trying to Modify a Tuple
fruits = ("apple", "banana", "mango")
fruits[0] = "orange" # Attempt to change first element
print(fruits)
Output:
TypeError: 'tuple' object does not support item assignment
Explanation: You cannot update tuple elements because tuples are immutable.
Example Program: Attempt to Append to a tuple (will result in an error).
# Trying to Append to a Tuple
fruits = ("apple", "banana", "mango")
[Link]("grape") # Attempt to add a new item
print(fruits)
Output:
AttributeError: 'tuple' object has no attribute 'append'
Explanation: Tuples have no .append() method — only lists support appending.
Example Program: Attempt to Remove an Item to a tuple (will result in an error).
# Trying to Remove an Item
fruits = ("apple", "banana", "mango")
[Link]("banana") # Attempt to remove an item
print(fruits)
Output:
AttributeError: 'tuple' object has no attribute 'remove'
Explanation: Tuples don’t support .remove().
Example Program: Attempt to Remove an Item to a tuple (will result in an error).
# Trying to Delete a Specific Element
fruits = ("apple", "banana", "mango")
del fruits[1] # Attempt to delete second element
print(fruits)
Fundamentals of Python Programming for Beginners 31
Unit-1: Introduction to Python
Output:
TypeError: 'tuple' object doesn't support item deletion
Explanation: You cannot delete individual tuple elements.
Note: Only deleting the entire tuple using del fruits is possible.
Comparison: List vs Tuple
Feature List Tuple
Defined with square brackets → [ ]
Defined with parentheses → ( )
Syntax Example: fruits = ["apple", "banana",
Example: coordinates = (10, 20, 30)
"mango"]
No → Cannot be changed after
Yes → Can be changed (add, remove,
creation.
Mutable update items). Example:
Example: coordinates[0] = 50 → is
[Link]("grapes") → modifies list
Error
Ordered Yes (items stay in same sequence). Yes (but values cannot be modified).
Best when data is expected to change Best when data should remain
Use Case frequently (e.g., shopping cart, student fixed/constant (e.g., coordinates,
names). days of week).
c. Range (range)
• Represents a sequence of numbers, often used for loops.
Syntax of range(stop)
range(stop)
Syntax of range(start, stop)
range(start, stop)
Syntax of range(start, stop, step)
range(start, stop, step)
Example of range(stop)
# Example: range(stop) # Example: range(stop)
r = range(5) r = range(5)
print(list(r)) print(r)
OUTPUT: OUTPUT:
[0, 1, 2, 3, 4] range(0, 5)
Explanation: Explanation:
Starts at 0 and ends at stop-1 → here • range(5) generates numbers from 0 to 4 (stop is
0 to 4. exclusive).
• Printing r directly shows the range object
(range(0, 5)), not the actual numbers.
• To see the numbers as a list, use:
Example of range(start, stop)
# Example: range(start, stop)
r = range(2, 7)
print(list(r))
Fundamentals of Python Programming for Beginners 32
Unit-1: Introduction to Python
OUTPUT:
[2, 3, 4, 5, 6]
Explanation: Starts at 2 and ends at 6 (stop-1).
Example of range(start, stop, step) (positive step)
# Example: range(start, stop, step)
r = range(1, 10, 2)
print(list(r))
OUTPUT:
[1, 3, 5, 7, 9]
Explanation: Starts at 1, ends at 9, increments by 2.
Example of range(start, stop, step) (negative step → backward counting)
r = range(10, 0, -2)
print(list(r))
OUTPUT:
[10, 8, 6, 4, 2]
Explanation: Starts at 10, decreases by 2, stops just before 0.
Example of range(stop)
r = range(6)
print(type(r)) # <class 'range'>
print(list(r)) # [0, 1, 2, 3, 4, 5]
Output:
<class 'range'>
[0, 1, 2, 3, 4, 5]
Explanation:
• range(6) creates a range object from 0 up to 5. Converting it to a list displays the
numbers generated.
Table: range( ) in Python with examples Table
Syntax Code Example Output Explanation
Starts at 0, ends at 4
range(stop) list(range(5)) [0, 1, 2, 3, 4]
(stop-1).
Starts at 2, ends at 6
range(start, stop) list(range(2, 7)) [2, 3, 4, 5, 6]
(stop-1).
Starts at 1, increments
range(start, stop, step) (positive) list(range(1, 10, 2)) [1, 3, 5, 7, 9]
by 2, stops before 10.
Starts at 10,
range(start, stop, step) (negative) list(range(10, 0, -2)) [10, 8, 6, 4, 2] decrements by 2, stops
before 0.
4. Mapping Type
Dictionary (dict):
• Unordered collection of key-value pairs
• Keys must be unique and immutable
• Defined with curly braces { }
Fundamentals of Python Programming for Beginners 33
Unit-1: Introduction to Python
Example Program: Dictionary Access and Update
student = {"name": "Rahul", "age": 35}
print(type(student)) # <class 'dict'>
print(student["name"]) # Rahul
student["age"] = 38 # Update value
print(student["age"])
Output:
<class 'dict'>
Rahul
38
Explanation:
• The student dictionary contains keys "name" and "age". It is of type dict. Accessing
student["name"] returns "Rahul", and updating student["age"] changes its value to
38.
Example Program: Dictionary with Multiple Keys
student = {"name": "Rahul", "age": 35, "branch": "ECE"}
print(student) # Prints the entire dictionary
print(student["name"]) # Access the value corresponding to the key "name"
Output:
{'name': 'Rahul', 'age': 35, 'branch': 'ECE'}
Rahul
Explanation:
• Dictionaries in Python are defined using curly braces {}.
• Each item is a key-value pair, written as "key": value.
• You can access a value using its key: student["name"] returns "Rahul".
Example Program: Dictionary with Marks
student = {"name": "Rahul", "marks": 90}
print(student)
Output:
{'name': 'Rahul', 'marks': 90}
Explanation:
• student holds related data as key-value pairs.
Example Program: Add & Remove Keys in Dictionary
student = {
"name": "Rahul",
"age": 20,
"course": "[Link]"
}
# Add a new key-value pair
student["branch"] = "ECE" # Adds 'branch': 'ECE'
# Remove an existing key
del student["age"] # Deletes the 'age' key
Fundamentals of Python Programming for Beginners 34
Unit-1: Introduction to Python
# Display the updated dictionary
print(student)
Output:
{'name': 'Rahul', 'course': '[Link]', 'branch': 'ECE'}
Explanation:
• Dictionaries in Python store data as key-value pairs.
• You can add a new key by assigning a value to it: student["branch"] = "ECE"
• You can remove a key using the del statement: del student["age"]
• The print(student) statement shows the updated dictionary after changes.
5. Set Types
a. Set (set):
• A set is an unordered collection of unique items.
• Defined using curly braces {} or the set( ) constructor.
• Sets do not allow duplicate values.
• Sets are mutable, meaning you can add or remove elements after creation.
Example Program: Set with Duplicates
list = {1, 2, 3, 1}
print(type(list)) # <class 'set'>
print(list) # {1, 2, 3}
[Link](5)
print(list) # {1, 2, 3, 5}
Output:
<class 'set'>
{1, 2, 3}
{1, 2, 3, 5}
Explanation:
• list is created with some duplicate values (1 appears twice). Sets only keep unique
values. Adding 5 demonstrates mutability.
Example Program: Unique Numbers in Set
unique_numbers = {1, 2, 3, 2, 1, 2}
print(unique_numbers)
Output:
{1, 2, 3}
Explanation: Duplicates are automatically removed and their order may change.
Example Program: To demonstrate adding, deleting, and modifying a set
# Creating a set
my_set = {1, 2, 3}
print("Original set:", my_set)
# Adding an item
my_set.add(4)
print("After adding 4:", my_set)
# Removing an item
my_set.remove(2)
print("After removing 2:", my_set)
Fundamentals of Python Programming for Beginners 35
Unit-1: Introduction to Python
# Modifying by adding multiple items
my_set.update([5, 6])
print("After adding 5 and 6:", my_set)
Output:
Original set: {1, 2, 3}
After adding 4: {1, 2, 3, 4}
After removing 2: {1, 3, 4}
After adding 5 and 6: {1, 3, 4, 5, 6}
Explanation:
1. add() → Adds one element to the set.
2. remove() → Removes the specified element.
3. update() → Adds multiple elements at once.
4. Sets are unordered and do not allow duplicates.
b. Frozen Set (frozenset)
• A frozenset is just like a set, but immutable once created, its elements cannot
be changed, added, or removed.
• Useful when you need a set that should not be modified.
Example Program: Simple Frozen Set
fs = frozenset([1, 2, 3])
print(type(fs))
print(fs)
Output:
<class 'frozenset'>
frozenset({1, 2, 3})
Explanation:
• frozenset([1, 2, 3]) creates an immutable set.
• You cannot add or remove items from fs later.
Example Program: Frozen Set with Duplicates
fset = frozenset([4, 5, 6, 4])
print(fset)
Output:
frozenset({4, 5, 6})
Explanation:
• Duplicate elements (4) are automatically removed.
• The frozenset is immutable, so no changes are allowed after creation.
Example Program: set and Frozenset
# Normal set
s = {1, 2, 3}
[Link](4)
print("Set:", s)
# Frozenset
fs = frozenset([1, 2, 3])
print("Frozenset:", fs)
Fundamentals of Python Programming for Beginners 36
Unit-1: Introduction to Python
# Trying to modify frozenset
# [Link](4) # Error: frozenset object has no attribute 'add'
Output:
Set: {1, 2, 3, 4}
Frozenset: frozenset({1, 2, 3})
Explanation:
• Sets allow adding/removing elements.
• Frozensets are immutable → once created, they cannot be changed.
Example Program: Frozen Set (Immutable)
# Creating a frozenset
my_fset = frozenset([1, 2, 3])
print("Original frozenset:", my_fset)
# Trying to add an item (will cause error)
# my_fset.add(4) # Not allowed, will raise AttributeError
# Trying to remove an item (will cause error)
# my_fset.remove(2) # Not allowed, will raise AttributeError
# The frozenset remains unchanged
print("Frozenset after trying to modify:", my_fset)
Output:
Original frozenset: frozenset({1, 2, 3})
Frozenset after trying to modify: frozenset({1, 2, 3})
Explanation:
• frozenset([1, 2, 3]) creates an immutable set.
• Methods like add() and remove() do not exist for frozensets trying them will raise
an error.
• Even if you try to modify it, the frozenset remains unchanged, unlike a regular set.
• Use frozenset when you need a set that should never be modified, e.g., as a
dictionary key.
Table: Comparison between Set and Frozen Set
Feature Set (set) Frozen Set (frozenset)
Mutable (can add or remove
Mutability Immutable (cannot change elements)
elements)
Syntax {1, 2, 3} or set([1,2,3]) frozenset([1,2,3])
Duplicates Removed automatically Removed automatically
fs = frozenset([1,2,3]) →
Example s = {1,2,3}; [Link](4) → {1,2,3,4}
frozenset({1,2,3})
When an unchangeable set is needed
Use Case Regular set operations
(e.g., as dictionary key)
Example Program: Demonstration of List, Tuple, Set, and Frozenset in Python
# List
fruits = ["apple", "banana"]
[Link]("mango")
print(fruits) # ['apple', 'banana', 'mango']
Fundamentals of Python Programming for Beginners 37
Unit-1: Introduction to Python
# Tuple
t = (10, 20, 30)
print(t[1]) # 20
# Set
s = {1, 2, 2, 3}
print(s) # {1, 2, 3}
# Frozenset
fs = frozenset([4, 5, 6, 4])
print(fs) # frozenset({4, 5, 6})
Output:
['apple', 'banana', 'mango']
20
{1, 2, 3}
frozenset({4, 5, 6})
Explanation:
1. List:
• A list is mutable (can be changed).
• We added "mango" using .append().
• Output → ['apple', 'banana', 'mango'].
2. Tuple:
• A tuple is immutable (cannot be changed).
• Accessed index 1 (second element).
• Output → 20.
3. Set:
• A set stores unique values (no duplicates).
• {1, 2, 2, 3} → duplicates (2) removed automatically.
• Output → {1, 2, 3}.
4. Frozenset:
• A frozenset is like a set but immutable (cannot be modified after creation).
• Duplicates (4) are removed.
• Output → frozenset({4, 5, 6}).
Table: Comparison: List vs Tuple vs Set vs Frozenset
Feature List Tuple Set Frozenset
Syntax [ ] → [1, 2, 3] ( ) → (1, 2, 3) { } → {1, 2, 3} frozenset([1, 2, 3])
Mutable Yes No Yes No
Ordered Yes Yes No (unordered) No (unordered)
Duplicates Allowed Allowed Not allowed Not allowed
Unique &
Use Case Changeable data Fixed/constant data Unique & constant
modifiable
6. Boolean Type (bool)
• Booleans hold one of two values: True or False.
• Used in conditions, comparisons, and logical operations.
Fundamentals of Python Programming for Beginners 38
Unit-1: Introduction to Python
Example Program: Boolean Variable in Condition
flag = True
print(type(flag)) # <class 'bool'>
if flag:
print("Yes!") # Output: Yes!
Output:
<class 'bool'>
Yes!
Explanation:
• flag is a boolean variable.
• Since flag is True, the if condition runs and prints "Yes!".
Example Program: Boolean Comparison
a=5
b = 10
print(a > b) # False
print(a < b) # True
Output:
False
True
Explanation:
• a > b → 5 > 10 → False.
• a < b → 5 < 10 → True.
Example Program: Password Check using Boolean
password = "1234"
print(password == "1234") # True
print(password == "abcd") # False
Output:
True
False
Explanation:
• The == operator checks whether two values are equal.
• In this example, password is set to "1234".
• password == "1234" → True, because the value matches exactly.
• password == "abcd" → False, because the value does not match.
Key Points:
1. Boolean values are case-sensitive (True and False with capital letters).
2. Used extensively in if conditions, loops, and logical checks.
7. Binary Types
• Used to handle binary data (e.g., files, images, network data).
• Python provides three binary types:
✓ Bytes
✓ Bytearray
✓ Memoryview
Fundamentals of Python Programming for Beginners 39
Unit-1: Introduction to Python
Type Mutable Description
bytes No Immutable sequence of bytes (cannot be changed).
bytearray Yes Mutable sequence of bytes (can be modified).
memoryview N/A A view object to access memory of bytes objects.
Example Program: Bytes (Immutable)
# Bytes cannot be changed
b = bytes([1, 2, 3])
print("Bytes:", b) # Prints the whole bytes object
# Accessing individual elements
print("First element:", b[0])
print("Second element:", b[1])
print("Third element:", b[2])
# Trying to change an element will give an error
# b[0] = 10 # Not allowed, bytes are immutable
Output:
Bytes: b'\x01\x02\x03'
First element: 1
Second element: 2
Third element: 3
Explanation:
• bytes([1, 2, 3]) creates an immutable sequence of bytes: b'\x01\x02\x03'.
✓ The prefix b indicates it is a bytes object.
✓ Each element represents a byte value (0–255).
• You can access individual elements using indexing:
✓ b[0] → 1
✓ b[1] → 2
✓ b[2] → 3
• You cannot modify elements of a bytes object:
✓ b[0] = 10 would raise an error because bytes are immutable.
Example Program: Bytearray (Mutable)
# Creating a bytearray
ba = bytearray([1, 2, 3])
print("Bytearray:", ba) # Prints the whole bytearray
# Accessing individual elements
print("First element:", ba[0])
print("Second element:", ba[1])
print("Third element:", ba[2])
# Modifying elements
ba[0] = 10
ba[1] = 20
print("Modified Bytearray:", ba)
Output:
Bytearray: bytearray(b'\x01\x02\x03')
First element: 1
Fundamentals of Python Programming for Beginners 40
Unit-1: Introduction to Python
Second element: 2
Third element: 3
Modified Bytearray: bytearray(b'\n\x14\x03')
Explanation:
• bytearray([1, 2, 3]) creates a mutable sequence of bytes.
• You can access individual elements using indexing:
✓ ba[0] → 1
✓ ba[1] → 2
✓ ba[2] → 3
• Unlike bytes, you can modify elements of a bytearray:
✓ ba[0] = 10 changes the first element.
✓ ba[1] = 20 changes the second element.
• The output shows the modified byte values in bytes format:
✓ \n is the byte representation of 10
✓ \x14 is the byte representation of 20
Example Program: Using bytearray and memoryview
# Create a bytearray (mutable data)
data = bytearray([10, 20, 30, 40])
# Create memoryview of the bytearray
mv = memoryview(data)
print("Original data:", data)
# Access elements using memoryview
print("First element:", mv[0])
print("Second element:", mv[1])
# Modify data using memoryview
mv[2] = 99
print("Modified data:", data)
print("Updated data:", list(data))
Output:
Original data: bytearray(b'\n\x14\x1e(')
First element: 10
Second element: 20
Modified data: bytearray(b'\n\x14c(')
Updated data: [10, 20, 99, 40]
Explanation:
• bytearray([10, 20, 30, 40]) Creates a mutable sequence of bytes. Each number
represents a byte value.
• memoryview(data) Creates a view into the bytearray. Allows direct access and
modification without copying.
• mv[0], mv[1] Accesses the first- and second-byte values: 10 and 20.
• mv[2] = 99 Modifies the third byte (originally 30) to 99. Since memoryview is
linked to data, the change reflects in the original bytearray.
Fundamentals of Python Programming for Beginners 41
Unit-1: Introduction to Python
• list(data) Converts the bytearray into a regular list for easier viewing: [10, 20, 99,
40].
Notes:
• \n → 10, \x14 → 20, \x1e → 30, ( → 40 (ASCII byte representations).
• After modifying mv[2] = 99, \x1e becomes c (ASCII for 99).
8. None Type
• Represents nothing / no value.
• Its type is NoneType.
• Often used as a default value in variables or function parameters.
Example Program: None Type Variable
# Variable with None
result = None
print("Value:", result)
print("Type:", type(result))
Output:
Value: None
Type: <class 'NoneType'>
Explanation:
• result has no value, so it is None.
• Its type is NoneType.
Example Program: Print None Value
data = None
print(data)
Output:
None
Explanation: None literally means nothing.
Example Program: Function with Default Argument (None)
def greet(name=None):
if name:
print("Hello", name)
else:
print("Hello Guest")
greet()
greet("Rahul")
Output:
Hello Guest
Hello Rahul
Explanation:
• The function greet() takes one optional parameter: name.
• If no name is provided, name defaults to None.
• Inside the function:
✓ If name has a value, it prints "Hello" followed by the name.
✓ If name is None, it prints "Hello Guest".
Fundamentals of Python Programming for Beginners 42
Unit-1: Introduction to Python
Note:
• Mutable (changeable) → list, dict, set, bytearray
• Immutable (fixed) → int, float, str, tuple, frozenset, bytes, bool, None
1.10 Declaring and Using Numeric Data Types in Python
• Python supports several numeric data types, mainly int, float, and complex.
• Each type is used to store different kinds of numbers, and Python automatically
assigns the correct type based on the value you provide.
1. Integer (int)
• Used for whole numbers (positive, negative, or zero) without any decimal
component.
Example Program: Integer Declaration
a = 10
print(a)
print(type(a))
Output:
10
<class 'int'>
Explanation:
• a is assigned the whole number 10. Using type(a) shows that Python treats it as
an integer.
2. Floating-Point (float)
• Used for numbers with a decimal point.
Example Program: Floating Point Declaration
b = 2.14
print(b)
print(type(b))
Output:
2.14
<class 'float'>
Explanation:
• b stores the decimal value 2.14, which is recognized as a float.
3. Complex Numbers (complex)
• Numbers with a real and an imaginary part, written as x + yj (where x and y are
numbers).
Example Program: Complex Number Declaration
x = 2 + 3j
print(x)
print(type(x))
Output:
(2+3j)
<class 'complex'>
Explanation:
• x is a complex number: real part is 2, imaginary part is 3.
Fundamentals of Python Programming for Beginners 43
Unit-1: Introduction to Python
Demonstration Program Using All Numeric Types
The Python program illustrating the declaration, usage, and some simple operations:
Example Program: Demonstration with int, float, and complex
x = 10 # Integer
y = 7.5 # Float
z = 2 + 3j # Complex
print("x =", x, ", type:", type(x))
print("y =", y, ", type:", type(y))
print("z =", z, ", type:", type(z))
# Arithmetic operations
sum_xy = x + y
prod_yz = y * z
print("Sum of x and y:", sum_xy)
print("Product of y and z:", prod_yz)
Output:
x = 10, type: <class 'int'>
y = 7.5, type: <class 'float'>
z = (2+3j), type: <class 'complex'>
Sum of x and y: 17.5
Product of y and z: (15+22.5j)
Explanation:
• Python automatically detects the type (int, float, complex) based on the value
assigned.
• The result of adding an int and a float is a float.
• Arithmetic with complex numbers yields a complex result.
Key Points
• Declaration: No need for type declarations in Python. The type is assigned based
on the assigned value.
• Type Checking: Use the type( ) function to check the variable type.
• Arithmetic: In Python, different types of numbers can be added together easily. If
you add a whole number and a decimal, Python automatically turns the result into
a decimal.
• Complex Numbers: Used less commonly, mainly for scientific applications.
Type Conversion:
• Python supports type conversion using constructor functions:
Example Program: Converting int to float, string, and list
x=6 # Assign the integer value 6 to variable x
y = float(x) # Convert integer x to a float and store in y (y becomes 6.0)
name = str(x) # Convert integer x to a string and store in name (name becomes "6")
r = range(4) # Create a range object representing the sequence 0, 1, 2, 3
nums = list(r) # Convert the range object into a list: [0, 1, 2, 3]
Fundamentals of Python Programming for Beginners 44
Unit-1: Introduction to Python
print(y) # Output the float value stored in y (prints: 6.0)
print(name) # Output the string stored in name (prints: 6)
print(nums) # Output the list stored in nums (prints: [0, 1, 2, 3])
Output:
6.0
6
[0, 1, 2, 3]
Programs Illustrating Data Types: List Operations
Example Program: List Operations
fruits = ["apple", "banana", "orange"]
print(fruits)
[Link]("grape")
print(fruits)
[Link]("orange")
print(fruits)
Output:
['apple', 'banana', 'orange']
['apple', 'banana', 'orange', 'grape']
['apple', 'banana', 'grape']
Explanation:
• Starts with three fruits.
• .append("grape") adds "grape".
• .remove("orange") removes "orange".
Programs Illustrating Data Types: Tuple Access
Example Program: Tuple Access
coordinates = (3, 5)
print(coordinates)
print("X-coordinate:", coordinates[0])
print("Y-coordinate:", coordinates[1])
Output:
(3, 5)
X-coordinate: 3
Y-coordinate: 5
Explanation: Coordinates is a tuple. Accessing by index gives the X and Y coordinates.
Example Program: Dictionary Access and Update
person = {"name": "Rahul", "age": 35}
print(person["name"]) # Access value by key
person["age"] += 1 # Update value
print(person) # Print updated dictionary
Output:
Rahul
{'name': 'Rahul', 'age': 36}
Fundamentals of Python Programming for Beginners 45
Unit-1: Introduction to Python
Explanation:
• person["name"] → reads the value of key "name", which is "Rahul".
• person["age"] += 1 → increases the age 35 → 36.
• Printing the dictionary shows: {'name': 'Rahul', 'age': 36}.
Programs Illustrating Data Types: Set and Frozen Set
Example Program: Set and Frozen Set
# Set
numbers = {1, 2, 2, 3}
[Link](4)
print(numbers) # Output: {1, 2, 3, 4}
# Frozen Set
frozen = frozenset([5, 6, 7])
print(frozen) # Output: frozenset({5, 6, 7})
Output:
{1, 2, 3, 4}
frozenset({5, 6, 7})
Explanation:
• Duplicates are removed in sets.
• .add(4) adds a new number.
• frozenset is like a set but can't be changed.
1.11 PYTHON PROGRAM DEVELOPMENT LIFE CYCLE
The Python Program Development Life Cycle is a structured way of writing programs
where we define, plan, code, test, run, and maintain to solve real-world problems
effectively.
Figure 1.11: Program Development Life Cycle
The Program Development Life Cycle is the process of creating a program step by step,
from idea to execution.
Problem Definition : Clearly state and understand the problem that needs to be
solved.
Problem Analysis : Study the problem in detail, identify inputs, processes, and
outputs.
Algorithm : Prepare step-by-step instructions or a flowchart to solve
Development the problem logically.
Coding : Translate the algorithm into a program using a
programming language.
Testing & Debugging : Run the program, check for errors, and correct them to
ensure accuracy.
Deployment : Implement and deliver the final working program for actual
use.
Fundamentals of Python Programming for Beginners 46
Unit-1: Introduction to Python
EXAMPLE PROGRAMS:
Q1. Arithmetic Expressions
x=4
y=2
z = x**y + x // y - y
print(z)
Output:
8
Explanation:
• x**y = 4**2 = 16
• x // y = 4 // 2 = 2 (floor division)
• So, 16 + 2 - 2 = 16.
Oh correction → Let’s carefully recompute:
16 + 2 - 2 = 16. (Final Answer should be 16 not 8).
Q2. String Operations
text = "Python Programming"
print(text[0:6])
print(text[-1])
print(len(text))
Output:
Python
g
18
Explanation:
• text[0:6] → characters from index 0 to 5 → "Python".
• text[-1] → last character → "g".
• len(text) → length of string → 18 characters.
Q3. List Manipulation
nums = [2, 4, 6]
[Link](1, 10)
[Link]()
print(nums)
Output:
[2, 10, 4]
Explanation:
• Start: [2, 4, 6]
• insert(1, 10) → put 10 at index 1 → [2, 10, 4, 6]
• pop() removes last element → [2, 10, 4].
Q4. Tuple Unpacking
a, b, c = (5, 10, 15)
print(a + b + c)
Fundamentals of Python Programming for Beginners 47
Unit-1: Introduction to Python
Output:
30
Explanation:
• Values of tuple (5,10,15) are assigned to a, b, c.
• Adding them: 5+10+15=30.
Q5. Dictionary Keys
student = {"name": "Anita", "age": 20, "branch": "ECE"}
print(list([Link]()))
Output:
['name', 'age', 'branch']
Explanation:
• .keys() gives all keys of dictionary.
• list() converts them into a list.
Q6. Set Operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print([Link](set2))
print([Link](set2))
Output:
{1, 2, 3, 4, 5}
{3}
Explanation:
• union → combines both sets (no duplicates).
• intersection → keeps only common values.
Q7. Boolean Logic
a = True
b = False
print(a and b)
print(a or b)
print(not b)
Output:
False
True
True
Explanation:
• True and False → False.
• True or False → True.
• not False → True.
Fundamentals of Python Programming for Beginners 48
Unit-1: Introduction to Python
Q8. Nested If Block
x=7
if x > 5:
if x % 2 == 0:
print("Even and greater than 5")
else:
print("Odd and greater than 5")
Output:
Odd and greater than 5
Explanation:
• x=7 → condition x>5 is True.
• Next check: 7 % 2 == 0 → False → goes to else.
• So it prints "Odd and greater than 5".
Q9. Range with Step
for i in range(2, 10, 3):
print(i, end=" ")
Output:
258
Explanation:
• range(2,10,3) starts at 2, then adds 3 each time → 2, 5, 8.
• Printed in one line because of end=" ".
Q10. Type Conversion
a = "100"
b = int(a) + 50
print(b)
Output:
150
Explanation:
• a is string "100".
• int(a) converts it to number 100.
• Then 100 + 50 = 150.
Fundamentals of Python Programming for Beginners 49