0% found this document useful (0 votes)
11 views49 pages

Introduction to Python Programming Notes

The document provides an introduction to Python programming, covering key concepts such as the differences between low-level and high-level languages, the definition of a program, and the debugging process. It also explains variables, naming conventions, operators, expressions, and type conversion functions, along with examples. Additionally, it highlights the importance of input statements and program composition in creating interactive and efficient code.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views49 pages

Introduction to Python Programming Notes

The document provides an introduction to Python programming, covering key concepts such as the differences between low-level and high-level languages, the definition of a program, and the debugging process. It also explains variables, naming conventions, operators, expressions, and type conversion functions, along with examples. Additionally, it highlights the importance of input statements and program composition in creating interactive and efficient code.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION TO PYTHON -NOTES

Module-I Notes
Differentiate low level and high level languages
Feature Low-Level High-Level Language
Language
Meaning Machine language Human-friendly
or assembly languages like Python,
language C++, Java, etc.
Readability Hard for humans to Easier for humans to
read/write understand
Execution Computer can Must be translated to
execute directly low-level form before
execution
Time to Takes more time and Much faster to write
Write programming effort programs
Portability Not portable — tied Portable — can run on
to a specific machine different computers with
little/no change
Error More chances of Fewer mistakes due to
chances mistakes simplicity

What is a program
A program is an ordered sequence of instructions written in a programming
language that tells a computer exactly what tasks or computations to perform.
These instructions include input operations, data processing, decision-making
(conditions), repetition (loops), and output generation. Essentially, a program
translates a problem statement into a form that the computer can execute step by
step.
When you write a program, you are specifying a procedure: first accept some
input, then apply one or more operations (such as calculations or comparisons),
possibly repeating steps or making choices based on conditions, and finally
producing output. The computer follows these instructions in the exact order
given, unless directed otherwise (e.g., by a loop or conditional). The success of a
program depends on its logic being correct and efficient.
Define debugging and explain types of errors with simple example

Debugging is the process of identifying, locating, and correcting errors (bugs) in a


program so that it runs correctly and gives the expected output.
There are three main types of errors:
Type of Meaning Simple Example
Error
Syntax Violation of programming print "Hello"
Error rules. Program won’t (missing brackets in
execute until fixed. Python)

DEPT. OF AIML, JNNCE


1
INTRODUCTION TO PYTHON -NOTES

Runtime Error occurs while the a = 10 / 0


Error program is running due to (division by zero)
invalid operations.
Logical Program runs without Area of square: area
Error crashing but gives incorrect = 2 * side instead of
output. side * side

what is Experimental debugging and why is it required


Experimental debugging is a method of fixing errors by running the program with
different test inputs, observing the output and behavior, and then modifying the code
step-by-step to find where the error occurs. Experimental debugging is a debugging
technique where the programmer:
• Treats debugging like detective work
• Forms a hypothesis about what is wrong
• Modifies the program and runs it again
• Compares the results with what was expected
• Repeats experiments until the program behaves correctly
Why is it required?
• Complex programs rarely work perfectly the first time
• Errors can only be detected by running the program
• Helps programmers eliminate impossible causes and find true reason

Differentiate Values and Types with examples


In programming, a value is a piece of data that a program processes, whereas a type
tells what kind of data that value represents and what operations can be performed on
it.
Values
• Actual data items stored or processed.
• Examples: numbers, text, decimal values.
• Each value belongs to a specific type.
Example values: 10, 3.14, "Python", True
Types
• Classification or category of values.
• Determines:
o Size in memory
o Allowed operations
o Valid representation
Common built-in types in Python:
Type Example Value Meaning
int 42 Whole numbers
float 3.14 Decimal / real numbers

DEPT. OF AIML, JNNCE


2
INTRODUCTION TO PYTHON -NOTES

str "Hello" Text (characters)


bool True / False Logical values
NoneType None Special “no value”

Strings and Their Quote types


Strings are values of type str. Python allows 3 ways to write them:
Quoting style Example Purpose
Single-quoted 'JNNCE' Small text, simplest form
Double- "Hello World" Used when text has single quotes inside
quoted
Triple-quoted """This is a Multi-line strings or documentation
paragraph""" strings

Explain Need of Variables and Their Use in Python


In programming, data needs to be stored temporarily in memory so that it can
be reused and processed during execution. A variable is a named storage
location used to hold values in a program. Instead of writing the same value
repeatedly, a variable allows us to store the value once and refer to it by its
name whenever required. Variables make programs readable, flexible, and
easier to modify. If the stored data changes, we need to update it only in one
place, and the entire program automatically uses the updated value.
In Python, variables are created dynamically — meaning we do not need to
declare their type in advance. When we assign a value using the assignment
operator =, Python automatically decides the data type based on the assigned
value. For example:
name = "Riya" # string variable
age = 20 # integer variable
marks = 87.5 # float variable
Here, name, age, and marks are variables storing different types of data. Since
variables are names given to memory locations, they help in performing
operations on stored values. For example, you can add two number-variables,
display stored text, or update values during runtime:
age = age + 1 # value updated at runtime
Thus, variables are essential in Python because they enable data storage,
modification, reuse, and meaningful representation of information within a
program. Without variables, programming would be repetitive, error-prone,
and difficult to manage

What are Variable Naming Conventions in Python


In Python, a variable name is an identifier used to refer to a stored value. Python
follows certain naming conventions to ensure that the code is clear and error-free.
A variable name must begin with a letter (A–Z / a–z) or underscore (_) and
can be followed by letters, digits (0–9), or underscores.

DEPT. OF AIML, JNNCE


3
INTRODUCTION TO PYTHON -NOTES

Spaces are not allowed inside variable names.


Python is case-sensitive, so age, Age, and AGE are considered three different
variables.
Eg:
student_name = "Rahul" - valid
marks1 = 85 - valid
_age = 20 - valid (used for internal variables)
1name = "Asha" - invalid (cannot start with number)
my name = "Ron" - space not allowed
Variable names should be meaningful, short, and follow the snake_case style in
Python for better readability. For example, total_score is preferred compared to ts
because it expresses its purpose clearly.

What is the Impact of Keywords on Variable Naming


Python has a set of reserved words called keywords, which have special meaning in
the language (e.g., if, for, while, True, return). These keywords cannot be used as
variable names because Python uses them to define the structure and logic of the
program. If a programmer attempts to use a keyword as a variable name, Python will
raise a syntax error.

if = 10 error: 'if' is a keyword


Valid alternative naming:
num_if = 10 is valid

Some example Python keywords list:

Define statements and expressions with examples


An expression is a piece of code that produces a value when evaluated.
It can consist of variables, values, and operators. Python evaluates an expression and
returns a result.
Eg:
5+3 # evaluates to 8
x * 10 # evaluates to a computed value
"Hello" + "World" # produces a string HelloWorld

DEPT. OF AIML, JNNCE


4
INTRODUCTION TO PYTHON -NOTES

Every expression has a value and often contributes to a larger instruction in the
program.

A statement is a complete instruction that the Python interpreter can execute.


Statements perform an action — such as assigning values, displaying output, or
controlling program flow.
Eg:
x = 10 # assignment statement
print(x) # print/output statement
if x > 5: # conditional statement
print("Large")
A statement may contain expressions inside it, but a statement itself does not return
a value.

Differences:
Feature Expression Statement
Purpose Produces a value Performs an action
Returns a result? Yes No direct result
Can be part of a statement? Yes Often contains expressions
Example a+b a=b+5

Define operators, operands and various python arithmetic operators


with examples. Explain the role of precedence and associativity of
operators

An operator is a symbol used to perform an operation on data (values or variables).


Eg: a + b, Here + is an operator.

Operands are the values or variables on which an operator acts.


Eg: a + b, Here a and b are operands.

Arithmetic Operators – are used for mathematical calculations.


Operator Meaning Example Output
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 4 * 3 12
/ Division 10 / 4 2.5
// Floor division 10 // 4 2
% Modulus 10 % 4 2
** Exponent 2 ** 3 8

Role of Precedence and Associativity in Python

DEPT. OF AIML, JNNCE


5
INTRODUCTION TO PYTHON -NOTES

In Python, an expression may contain several operators together. The precedence of


operators determines which operator is evaluated first. Associativity determines the
direction of evaluation when two operators have the same precedence.
If precedence rules did not exist, Python would not know how to correctly evaluate
expressions. Therefore, correct results depend on operator precedence and
associativity.

PEMDAS Rule (Operator Precedence Order)


Python follows a standard order, commonly remembered as PEMDAS:
Letter Meaning Example
P Parentheses (5 + 3) * 2 = 16
E Exponent 2 ** 3 * 2 = 16
M Multiplication
D Division
A Addition
S Subtraction

Example with PEMDAS


result = 10 - 2 * 3 ** 2 + 1
Evaluation steps:
1. Exponent: 3 ** 2 = 9
2. Multiplication: 2 * 9 = 18
3. Subtraction: 10 - 18 = -8
4. Addition: -8 + 1 = -7
Final Result = -7
Associativity
When two operators have the same precedence, Python decides the evaluation order
using associativity.
Operator Type Associativity Example
Arithmetic (+, -, *, /, //, %) Left → Right 20 / 5 * 2 = (20/5) * 2 = 8
Comparison and Logical Left → Right 5 > 3 > 1 = True
Exponentiation (** ) Right → Left 2 ** 3 ** 2 = 2 ** (9) = 512
Assignment (=, +=, -=…) Right → Left a = b = 10 → b first
Associativity Example: x = 2 ** 3 ** 2
• 3 ** 2 = 9 (right side first)
• 2 ** 9 = 512
Final result: 512

Evaluate: result = (10 - (2 + 3)) * (4 - 1) ** 2


Innermost parentheses first: (2 + 3) = 5
So expression becomes:
(10 - 5) * (4 - 1) ** 2
Next parentheses: (10 - 5) = 5
(4 - 1) = 3

DEPT. OF AIML, JNNCE


6
INTRODUCTION TO PYTHON -NOTES

Now expression:
5 * 3 ** 2
Exponent (PEMDAS): 3 ** 2 = 9
Expression becomes: 5 * 9
Multiplication: 5 * 9 = 45
Final Result = 45

Explain type conversion functions in Python:


In Python, sometimes values of one data type need to be converted into another data
type to perform arithmetic operations, comparisons, or display them properly.
Python provides built-in type converter functions to convert values explicitly.
This process is known as type casting or type conversion.

Function Meaning / Example Output Explanation


Conversion To
int() Converts value into int(3.9) 3 Decimal part is
an integer removed (flooring not
rounding)
int("25") 25 String must contain
only digits
float() Converts value into float(7) 7.0 Adds decimal point
floating-point
number
float("12.65") 12.65 String must be numeric
str() Converts any value str(5 + 3) "8" Useful in printing text
into a string + numbers
str(True) "True" Boolean becomes text
bool() Converts into bool(10) True Non-zero → True
Boolean (True/False)
bool("") False Empty string → False

What are various string operators. Explain with appropriate code


snippets
String Concatenation Operator (+)
String concatenation means joining two or more strings into a single continuous
string.
In Python, the + operator is used for concatenation.
Important Rule: Both operands must be strings, otherwise Python gives a TypeError.
Eg:
name = "JNNCE"
place = "Shivamogga"
result = name + " - " + place

DEPT. OF AIML, JNNCE


7
INTRODUCTION TO PYTHON -NOTES

print(result)
Output: JNNCE – Shivamogga
String Repetition Operator (*)
The repetition operator duplicates the string a specified number of times.
In Python, the * operator is used with a string and an integer.
Eg:
msg = "Hello! "
repeat_msg = msg * 3
print(repeat_msg)

Output: Hello! Hello! Hello!


Note:
• A string multiplied by 0 gives an empty string.
• A string cannot be multiplied by another string (error).

Explain the need of input statement of python with examples


Python provides the input() function to allow the user to enter data during program
execution. Whatever the user types from the keyboard is taken as input and stored in
a variable.
Important Notes
• input() always returns data as a string, even if numbers are entered.
• To convert it into int or float, we must use type conversion functions (int(),
float(), etc.)
Eg:
name = input("Enter your name: ")
print("Hello", name)
Output:
Enter your name: Chetan
Hello Chetan
Numerical Input with Type Conversion
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 + num2
print("Sum =", result)

Output:
Enter first number: 10
Enter second number: 20
Sum = 30

Float Input Example


price = float(input("Enter item price: "))
print("Total price =", price)

Input in Single Line (Multiple Values)

DEPT. OF AIML, JNNCE


8
INTRODUCTION TO PYTHON -NOTES

a, b = input("Enter two numbers: ").split()


a = int(a)
b = int(b)
print("Sum =", a + b)

Output:
Enter two numbers: 5 7
Sum = 12
Why is input() needed?
Feature Benefit
Accepts data dynamically Makes the program interactive
Can read strings, ints, floats (with Useful for calculations and real-world
conversion) applications
Supports prompt message Guides user clearly

Why do we need program composition


Small programming elements such as literals, variables, operators, and
function calls can be composed together to form larger meaningful statements,
which further form the complete functioning program. This concept is called
Composition.
Composition in Python is the mechanism of combining simple expressions or
function calls into a single more powerful statement. It allows nesting of
operations such that the result of one expression can be used directly inside
another. This improves code readability and reduces lines of code. Examples
include using a function inside another function call or performing arithmetic
inside print statements.

This diagram visually explains how small program elements like expressions, variables,
and functions are combined to create larger composed statements, and eventually form
the full program behavior

DEPT. OF AIML, JNNCE


9
INTRODUCTION TO PYTHON -NOTES

Eg:
name = input("Enter your name: ")
greet = "Hello " + name
print(greet)

Compositions:
Step Component Description
input() Takes user input
String concatenation "Hello " + name
print() Outputs final result

Explain the role and working of modulus operator


The modulus operator (%) returns the remainder obtained after dividing one number
by another. It helps determine what is left over after division and is commonly used
in arithmetic logic and decision-making.
Syntax:
result = a % b
Here,
• a → dividend
• b → divisor
• result → remainder

Eg:
print(10 % 3) # Output: 1 (10 = 3×3 + 1)
print(25 % 7) # Output: 4 (25 = 7×3 + 4)

Uses of Modulus Operator


Use Case Explanation Example
Check even or odd If number % 2 == 0 → Even else 7 % 2 = 1 → Odd
Odd
Cyclic operations / Used in clocks, rotations, (14 % 12) = 2 →
repeating patterns periodic behavior Clock hours
Extract last digit(s) of a Remainder gives final digit 567 % 10 = 7
number patterns
Divisibility check If number % divisor == 0 → 20 % 5 = 0 →
perfectly divisible divisible

Programming (Compositions examples)

Program to add 2 numbers


x=int(input('Enter x'))
y=int(input('Enter y'))
print(x+y)

DEPT. OF AIML, JNNCE


10
INTRODUCTION TO PYTHON -NOTES

Write a program to compute compound interest


p=int(input('Enter P'))
r=int(input('Enter r'))
n=int(input('Enter n'))
t=int(input('Enter t'))
r=r/100
A=p*(1+r/n)**(n*t)
print(A)

Let’s Trace With These Sample Inputs


Variable Meaning
P = 10000 Principal amount
r = 10 Rate of interest (10%)
n=2 Compounded twice per year
t=3 Time in years

Output:

Tracing:
Step Statement Internal Calculation Updated Value
1 Input P User enters 10000 p = 10000
2 Input r User enters 10 r = 10
3 Input n User enters 2 n=2
4 Input t User enters 3 t=3
5 r = r / 100 10 / 100 r = 0.10
6 Compute A (A = 10000 * (1 + 0.10/2)^{(2*3)}) —
7 Simplify inside (1 + 0.10/2 = 1 + 0.05 = 1.05) —
8 Power (1.05^{6} ≈ 1.3400956) —
9 Final multiplication (10000 × 1.3400956 ≈ 13400.956) A = 13400.956
10 Print A Output 13400.956

DEPT. OF AIML, JNNCE


11
INTRODUCTION TO PYTHON -NOTES

Write a program to extract digits of 4 digit number


num=int(input('Enter a number'))
first=num%10
quotient=num//10
second=quotient%10
quotient=quotient//10
third=quotient%10
quotient=quotient//10
fourth=quotient%10
quotient=quotient//10
print(first,second,third,fourth)

Output:

Tracing:
Step Statement / Operation Calculation Value Stored
1 num = 7531 — num = 7531
2 first = num % 10 7531 % 10 = 1 first = 1
3 quotient = num // 10 7531 // 10 = 753 quotient = 753
4 second = quotient % 10 753 % 10 = 3 second = 3
5 quotient = quotient // 10 753 // 10 = 75 quotient = 75
6 third = quotient % 10 75 % 10 = 5 third = 5
7 quotient = quotient // 10 75 // 10 = 7 quotient = 7
8 fourth = quotient % 10 7 % 10 = 7 fourth = 7
9 quotient = quotient // 10 7 // 10 = 0 quotient = 0

write a program to ask the user to enter some seconds, and convert them
into hours, minutes, and remaining seconds

secs = int(input("Enter seconds"))


hours = secs // 3600
rem = secs % 3600
mins = rem // 60
secs = rem % 60
print(hours, mins, secs)

Output:

DEPT. OF AIML, JNNCE


12
INTRODUCTION TO PYTHON -NOTES

Tracing:
Step Statement / Operation Calculation Stored Value
1 secs = 5000 — secs = 5000
2 hours = secs // 3600 5000 // 3600 = 1 hours = 1
3 rem = secs % 3600 5000 % 3600 = 1400 rem = 1400
4 mins = rem // 60 1400 // 60 = 23 mins = 23
5 secs = rem % 60 1400 % 60 = 20 secs = 20

Explain iteration and its types


Iteration means repeating a block of statements multiple times in a program.
Instead of writing the same code again and again, Python allows us to loop through
code efficiently. Iteration is useful when a task needs to be performed repeatedly—
like printing numbers, scanning lists, or running computations many times.

Two Major Types of Iteration


Definite Iteration (Known number of repetitions)
We know exactly how many times the loop should run. ➡ Usually implemented
using the for loop.

Example:
for i in range(5):
print(i)

Output:
0
1
2
3
4
The loop runs 5 times (from 0 to 4)

Indefinite Iteration (Unknown number of repetitions)


The number of repetitions is not fixed. The loop continues until a condition becomes
false. Implemented using the while loop.
Example:
n=1
while n <= 5:
print(n)
n=n+1

Output:

DEPT. OF AIML, JNNCE


13
INTRODUCTION TO PYTHON -NOTES

1
2
3
4
5

Why Iteration is needed?


Problem Without Iteration Solution With Iteration
Code becomes long Code becomes shorter
Difficult to update Easily maintainable
Repetition creates errors Loop automates repetition
Slow to write Faster development

Write a Python program to traverse a list of friends


friends=["mona","rona","tina","leena","seena"]
i=0
while i < len(friends):
friend=friends[i]
print("Welcome",friend)
i=i+1

Output:

Tracing:
Iteration i Condition friend = Print Output Updated
value Check friends[i] i
1 0 0 < 5 → True "mona" Welcome 1
mona
2 1 1 < 5 → True "rona" Welcome 2
rona
3 2 2 < 5 → True "tina" Welcome tina 3
4 3 3 < 5 → True "leena" Welcome 4
leena
5 4 4 < 5 → True "seena" Welcome 5
seena
6 5 5 < 5 → False Loop stops — —

DEPT. OF AIML, JNNCE


14
INTRODUCTION TO PYTHON -NOTES

Write a python program to count the number of digits in a number


number=int(input('Enter number'))
digits=0
while number!=0:
number=number//10
digits=digits+1
print(digits)

Output:

Tracing:
Iteration number (before loop Condition number = number // digits
step) 10 value
Initial 7531 7531 != 0 — 0
1 7531 7531!=0 7531 // 10 = 753 1
2 753 753!=0 753 // 10 = 75 2
3 75 75!=0 75 // 10 = 7 3
4 7 7!=0 7 // 10 = 0 4
5 0 0 != 0 Loop stops —

Explain Collatz 3n+1 sequence and write a Python program to generate


the same
The Collatz sequence is a famous mathematical process applied to any positive
integer:
If the number is even → divide it by 2
If the number is odd → multiply by 3 and add 1
Repeat the process until the number becomes 1.

Program:
n=int(input('Enter n'))
while n!=1:
print(n,end=",")
if n%2==0:
n=n//2
else:
n=3*n+1
print(n)

Output:

DEPT. OF AIML, JNNCE


15
INTRODUCTION TO PYTHON -NOTES

Tracing:
Step n (Before) Even/Odd? Operation n (After) Printed
1 6 Even 6 // 2 3 6,
2 3 Odd 3×3 + 1 10 3,
3 10 Even 10 // 2 5 10,
4 5 Odd 3×5 + 1 16 5,
5 16 Even 16 // 2 8 16,
6 8 Even 8 // 2 4 8,
7 4 Even 4 // 2 2 4,
8 2 Even 2 // 2 1 2,
9 Loop ends 1 — 1 print(n) prints 1

Write a Python program to find sum of first n numbers


n=int(input('Enter n'))
numbers=range(n)
sm=0
for number in numbers:
sm=sm+number

print(sm)

Tracing:
Loop Step number sm (previous) Operation sm (new value)
Start — 0 — 0
1 0 0 0+0 0
2 1 0 0+1 1
3 2 1 1+2 3
4 3 3 3+3 6
5 4 6 6+4 10

Same Program Using while Loop:


n = int(input("Enter n"))
i=0
sm = 0

while i < n:

DEPT. OF AIML, JNNCE


16
INTRODUCTION TO PYTHON -NOTES

sm = sm + i
i=i+1

print(sm)

Tracing:
Step i sm Operation sm i
(Before) (Before) Performed (After) (After)
Start 0 0 — 0 0
1 0 0 sm = 0+0 0 1
2 1 0 sm = 0+1 1 2
3 2 1 sm = 1+2 3 3
4 3 3 sm = 3+3 6 4
5 4 6 sm = 6+4 10 5
Loop ends (since
i=5 ≥ n)

Write a python program to find sum of a list of numbers


numbers=[11,60,5,19,4,3,7]
sm=0
for number in numbers:
sm=sm+number
print(sm)

Output:

Tracing:
Step number sm (Before) Operation sm (After)
Start — 0 — 0
1 11 0 0 + 11 11
2 60 11 11 + 60 71
3 5 71 71 + 5 76
4 19 76 76 + 19 95
5 4 95 95 + 4 99
6 3 99 99 + 3 102
7 7 102 102 + 7 109

Write a program to generate a table of squares and cubes (1D and 2D


tables)
n=int(input('Enter n'))

DEPT. OF AIML, JNNCE


17
INTRODUCTION TO PYTHON -NOTES

numbers=range(1,n+1)
for number in numbers:
sq=number**2
cube=number**3
print("(",sq,cube,")",end=",")

Output:

Tracing:
number square (number²) cube (number³) Printed Output
1 1 1 (1 1),
2 4 8 (4 8),
3 9 27 (9 27),
4 16 64 (16 64),
5 25 125 (25 125),
Explain break and continue statements with appropriate examples
Break Statement
The break statement is used to immediately exit a loop (while or for), even if the loop
condition is still true. Once break executes, the control jumps to the first statement
after the loop.

Eg:
for num in range(1, 10):
if num == 5:
break
print(num)
print("Loop stopped")

Output:
1
2
3
4
Loop stopped

Reason: When num becomes 5, break executes and the loop terminates.

Continue Statement
The continue statement skips the current iteration of the loop but does not stop the
loop.
The loop continues with the next value.

DEPT. OF AIML, JNNCE


18
INTRODUCTION TO PYTHON -NOTES

Example:
for num in range(1, 10):
if num == 5:
continue
print(num)

Output:
1
2
3
4
6
7
8
9

Reason: When num is 5, the continue statement skips the print() and moves to the next
iteration, so 5 is not printed.

Differences:
Feature break continue
Loop termination Stops loop completely Skips only current iteration
Control goes to Statement after loop Next iteration of the loop
Effect Loop ends early Some values may not be processed

Explain middle test loops with Flowchart

Step-by-step Description:
1. Start of Loop The loop begins and execution enters the loop body.
2. Execute Loop Body Statement The first process block represents statements
inside the loop.
3. Condition Check A decision diamond checks a particular condition:
o If condition is false, the loop continues normally.
o If condition is true, the break instruction is triggered.
4. Break Condition True → Exit Loop Immediately
o When the break condition becomes true, the flow jumps out of the loop

DEPT. OF AIML, JNNCE


19
INTRODUCTION TO PYTHON -NOTES

oLoop stops, and program continues with the next statement after the
loop
5. Break Condition False → Continue Loop
o If the break condition is not satisfied, control goes back to the beginning
of loop and next iteration starts

Write a program to generate Lucas series


n=int(input('Enter n'))
f1=2
f2=1
print(f1,f2,end=",")
i=2
while i<n:
f3=f1+f2
print(f3,end=",")
f1=f2
f2=f3
i=i+1

Output:

Tracing:
Step i f1 f2 f3 = f1+f2 Output printed
Init - 2 1 - 2, 1, (printed before loop)
1st Iteration 2 2 1 3 3,
update 3 1 3 - -
2nd Iteration 3 1 3 4 4,
update 4 3 4 - -
3rd Iteration 4 3 4 7 7,
update 5 4 7 - -
4th Iteration 5 4 7 11 11,
update 6 7 11 - loop stops (i = n)

Write a Python program to implement Guess the number game


import random
rng=[Link]()
num=[Link](1,12)
attempts=0
while True:
attempts+=1
unum=int(input('Enter the number'))

DEPT. OF AIML, JNNCE


20
INTRODUCTION TO PYTHON -NOTES

if unum>num:
print('Guess is high')
elif unum<num:
print('Guess is low')
else:
break
print("number of attempts",attempts)

Tracing:
Iteration User Input (unum) Condition Checked Output Shown attempts
1 10 unum > num Guess is high 1
2 3 unum < num Guess is low 2
3 6 unum < num Guess is low 3
4 7 unum == num Loop breaks 4

Output:
number of attempts 4

Key concepts used in this program:


Concept Where Used
Infinite Loop while True:
Counter Variable attempts += 1
Conditional Statements if, elif, else
Random Number Generation [Link](1,12)
Loop Termination break

Explain paired data in python with an example


Paired Data in Python
Paired data refers to two related sets of values that are connected position-wise.
Each value in one list has a direct relationship with the value at the same index in
another list.
Example in real life:
• Names of students and their marks
• Products and their prices
• Countries and their capitals
Python allows us to process such paired data using: Tuples inside a list

Example program for countries and their currencies:


concur=[
("US","Dollar"),
("India","Rupee"),
("China","Yen"),
("Europe","Euros")

DEPT. OF AIML, JNNCE


21
INTRODUCTION TO PYTHON -NOTES

]
for country,currency in concur:
print("Country ",country,
"Currency ",currency)

Output:

Tracing:
Iteration Loop Variables country currency Output Printed
Extracted Value Value
1 ("US", "Dollar") US Dollar Country: US Currency:
Dollar
2 ("India", "Rupee") India Rupee Country: India
Currency: Rupee
3 ("China", "Yen") China Yen Country: China
Currency: Yen
4 ("Europe", Europe Euros Country: Europe
"Euros") Currency: Euros

Write a python program to create pair for cricket players and their
nicknames
players=[
("Rahul Dravid","Jammy"),
("Virat Kohli","Chikoo"),
("Anil Kumble","Jumbo"),
("Shikhar Dhawan","Gabbar")
]
for name,nickname in players:
print("Player name ",name,
"Nick Name ",nickname)

Output:

DEPT. OF AIML, JNNCE


22
INTRODUCTION TO PYTHON -NOTES

Tracing
Iteration Tuple Extracted name nickname Output Printed
Value Value
1 ("Rahul Rahul Jammy Player name: Rahul
Dravid","Jammy") Dravid Dravid Nick Name:
Jammy
2 ("Virat Virat Chikoo Player name: Virat
Kohli","Chikoo") Kohli Kohli Nick Name:
Chikoo
3 ("Anil Anil Jumbo Player name: Anil
Kumble","Jumbo") Kumble Kumble Nick Name:
Jumbo
4 ("Shikhar Shikhar Gabbar Player name:
Dhawan","Gabbar") Dhawan Shikhar Dhawan
Nick Name: Gabbar

Explain the concept of Nested Loops for Nested Data


Sometimes in Python, we store records where each element is a tuple containing:
• A name (string)
• A list of values (like marks, scores, or subjects)
Eg:
data = [
("Rohan", [78, 88, 90]),
("Meena", [92, 85, 87]),
("Kiran", [81, 79, 84])
]
To access this type of nested structure, we use a nested loop:

Full Python code example:


sh=[
("David",["Music","Cooking"]),
("Sarah",["Music","Cooking","Reading"]),
("James",["Sports","Music","Cooking"]),
("Aisha",["Music","Sports","Cycling"])
]
cnt=0
for student in sh:
(name,hobby)=student
for h in hobby:
if h=="Music":
cnt+=1

print("Intersted in music",cnt)

DEPT. OF AIML, JNNCE


23
INTRODUCTION TO PYTHON -NOTES

Output:

Tracing
Iteratio student nam hobby list Inner Condition cn
n e loop (h=="Musi t
hobby c")
h
1 ("David Davi ["Music","Cooking"] Music True 1
", [...]) d
Cookin False 1
g
2 ("Sarah Sara ["Music","Cooking","Readi Music True 2
", [...]) h ng"]
Cookin False 2
g
Readin False 2
g
3 ("James Jame ["Sports","Music","Cookin Sports False 2
", [...]) s g"]
Music True 3
Cookin False 3
g
4 ("Aisha Aish ["Music","Sports","Cycling Music True 4
", [...]) a "]
Sports False 4
Cyclin False 4
g

The same program can be rewritten without using nesting as:


sh=[
("David",["Music","Cooking"]),
("Sarah",["Music","Cooking","Reading"]),
("James",["Sports","Music","Cooking"]),
("Aisha",["Music","Sports","Cycling"])
]
cnt=0
for student in sh:
(name,hobby)=student
if "Music"in hobby:
cnt+=1

print("Intersted in music",cnt)

DEPT. OF AIML, JNNCE


24
INTRODUCTION TO PYTHON -NOTES

Here Instead of checking hobby one-by-one, we directly check

Tracing
Iterati student tuple na hobby list Condit cnt
on me ion val
"Music ue
" in
hobby
1 ("David",["Music","Cooking" Dav ["Music","Cooking"] 1
]) id True
2 ("Sarah",["Music","Cooking" Sara ["Music","Cooking"," 2
,"Reading"]) h Reading"] True
3 ("James",["Sports","Music"," Jam ["Sports","Music","Co 3
Cooking"]) es oking"] True
4 ("Aisha",["Music","Sports"," Ais ["Music","Sports","Cy 4
Cycling"]) ha cling"] True

Write a Python program to implement Newton’s method for finding


square roots

Flowchart:

DEPT. OF AIML, JNNCE


25
INTRODUCTION TO PYTHON -NOTES

Program:
n=int(input('Enter n'))
x0=2
thresh=0.0000001
while True:
x1=(x0+n/x0)/2
if abs(x0-x1)<thresh:
break
x0=x1
print(x1)

| Iteration | x₀ (previous value) | n / x₀ | (x₀ + n/x₀) / 2 → x₁ | |x₀ - x₁| | Condition


( < threshold? ) |
|----------|-------------------:|----------------:|----------------------:|----------------:|----------------
------------|
| Initial | 2.0000000 | — | — | — | — |

DEPT. OF AIML, JNNCE


26
INTRODUCTION TO PYTHON -NOTES

| 1 | 2.0000000 | 4.0000000 | 3.0000000 | 1.0000000 | No |


| 2 | 3.0000000 | 2.6666667 | 2.8333333 | 0.1666667 | No |
| 3 | 2.8333333 | 2.8235294 | 2.8285714 | 0.0047619 | No |
| 4 | 2.8285714 | 2.8284440 | 2.8284271 | 0.0001443 | No |
| 5 | 2.8284271 | 2.8284270 | 2.8284271 | 0.000000025 | YES → Stop |

Define functions in python . Give the need and syntax


A function in Python is a block of reusable code that performs a specific task.
It executes only when it is called and may return a value after processing.

Need for Functions


Functions are used because they:
1. Avoid repetition – Write code once, use many times.
2. Improve readability & organization of a program.
3. Make debugging easier since logic is separated into small parts.
4. Enable modular programming – Divide a large program into smaller modules.
5. Promote code reuse in multiple places or programs.

Syntax of a Function in Python


def function_name(parameters):
statement(s)
return value # optional

Explanation:
• def → keyword used to define a function
• function_name → user-defined name
• parameters → input values (optional)
• return → sends back output (optional)
Eg code:
def add(a, b):
c=a+b
return c

print(add(3, 5))

What are the various classifications of functions based on Parameters &


Return Values
In Python, functions can be classified into four categories based on whether they take
parameters (input) and whether they return values (output).

Function without parameters and without return value


• Does not take any input
• Does not return anything to the caller
• Only performs a task inside the function

DEPT. OF AIML, JNNCE


27
INTRODUCTION TO PYTHON -NOTES

Example:
def greet():
print("Hello! Welcome to Python")

greet()

Output:
Hello! Welcome to Python

Function with parameters and without return value


• Takes input values (parameters)
• Processes and prints result directly
• No value returned

Example:
def display(name):
print("Hello", name)

display("Asha")

Output:
Hello Asha

Function without parameters and with return value


• No input given
• Produces and returns a result using internal logic

Example:
def get_pi():
return 3.14159

x = get_pi()
print(x)

Output:
3.14159

unction with parameters and with return value


(Most commonly used type)
Takes input, processes it, and returns the result
Example:
def add(a, b):
return a + b

DEPT. OF AIML, JNNCE


28
INTRODUCTION TO PYTHON -NOTES

result = add(10, 20)


print(result)
Output:
30

Differences summary:
Type Parameters Return Purpose Example Use
Value
1 No No Only perform task Greeting, menu
display
2 Yes No Use inputs but only Display user info
print
3 No Yes Generate and send Random number
result back generator
4 Yes Yes Full processing Calculations,
function conversions

Practical component of Module-1:


1. a. Develop a python program to read 2 numbers from the
keyboard and perform the basic arithmetic operations based on
the choice. (1-Add, 2-Subtract, 3-Multiply, 4-Divide).

Program:
num1=int(input('Enter number1'))
num2=int(input('Enter number2'))
choice=int(input('Enter the choice'))
if choice==1:
add=num1+num2
print(add)
elif choice==2:
sub=num1-num2
print(sub)
elif choice==3:
prod=num1*num2
print(prod)
elif choice==4:
div=num1/num2
print(div)

Output:

DEPT. OF AIML, JNNCE


29
INTRODUCTION TO PYTHON -NOTES

Tracing:
Step Statement num1 num2 choice Condition Result
Executed Check
1 num1 = 8 8 — — — —
2 num2 = 12 8 12 — — —
3 choice = 3 8 12 3 — —
4 if choice == 1 8 12 3 False skip
5 elif choice == 2 8 12 3 False skip
6 elif choice == 3 8 12 3 True Execute
7 prod = num1 * — — — — prod = 96
num2
8 print(prod) — — — — Output:
96

1b. Develop a program to read the name and year of birth of a person.
Display whether the person is a senior citizen or not

Program:
year=int(input('Enter the yearof birth'))
name=input('Enter your name')
age=2025-year
if age>=60:
print(name,' is senior citizen')
else:
print(name,' is Not senior citizen')

Output:

Tracing
Step Statement year name age Condition (age ≥ Output
Executed 60?)

DEPT. OF AIML, JNNCE


30
INTRODUCTION TO PYTHON -NOTES

1 year = 1984 1984 — — — —


2 name = "moni" 1984 moni — — —
3 age = 2025 - 1984 moni 41 — —
1984
4 if 41 ≥ 60 — — 41 False Execute else block
5 else → print — moni 41 — moni is Not senior
citizen

2a. Develop a program to generate Fibonacci sequence of length (N).


Read N from the console

Program:
n=int(input('Enter n'))
f1=0
f2=1
print(f1,f2,end=",")
i=2
while i<n:
f3=f1+f2
print(f3,end=",")
f1=f2
f2=f3
i=i+1

Output:

Tracing
Iteration i value f1 f2 f3 = f1 + f2 Printed Output
Initial print — 0 1 — 0, 1,
1 2 0 1 1 0, 1, 1,
2 3 1 1 2 0, 1, 1, 2,
3 4 1 2 3 0, 1, 1, 2, 3,
4 5 2 3 5 0, 1, 1, 2, 3, 5,
5 6 3 5 8 0, 1, 1, 2, 3, 5, 8,
6 7 5 8 13 0, 1, 1, 2, 3, 5, 8, 13,
Stop i = 8 (not < n) — — — Loop ends

DEPT. OF AIML, JNNCE


31
INTRODUCTION TO PYTHON -NOTES

Module-II: Strings, tuples and Lists


Why String is called a compound type
A String is a compound type because it is not a single, indivisible value. Instead, it
is made up of multiple smaller elements — characters, each represented as a string
of length 1. Since the whole string is composed of these smaller components, and we
can either treat it as a single unit or access its individual characters, it is classified as a
compound data type.
Eg: The string "CAT" looks like one value, but you can break it into its parts — "C",
"A", "T".

Give and explain the whole string processing functions

These functions work on the entire string at once, not character by character.
They return a new modified string.
1. upper() - Makes all letters in the string UPPERCASE.
Example:
"hello".upper()
HELLO

2. lower() - Makes all letters in the string lowercase.


Example:
"HELLO".lower()
hello

3. capitalize() - Makes only the first letter uppercase and the rest lowercase.
Example:
"pYtHoN".capitalize()
Python

4. swapcase() - Flips the case of every letter:


• UPPER → lower
• lower → UPPER
Example:
"HeLLo".swapcase()
hEllO

DEPT. OF AIML, JNNCE


32
INTRODUCTION TO PYTHON -NOTES

Give and explain the processing of string in parts

A string is a sequence of characters, and each character in the string has a fixed
position number called its index.
Python allows us to access characters using two types of indexing:

1. Forward Indexing (Left → Right)


• Starts from 0
• Counts characters from the beginning of the string
• Useful when accessing characters normally
Example:
For the string "Python"
P y t h o n
0 1 2 3 4 5
So,
string[0] → 'P'
string[3] → 'h'

2. Backward Indexing (Right → Left)


• Starts from -1
• Counts characters from the end of the string
• Useful when accessing characters from the back
Example:
P y t h o n
-6 -5 -4 -3 -2 -1
So,
string[-1] → 'n'
string[-3] → 'h'

Why indexing is useful?


• Helps access individual characters
• Allows slicing (extracting parts of a string)
• Shows that a string is a compound data type—because it has smaller parts

Explain string length using Python with example

DEPT. OF AIML, JNNCE


33
INTRODUCTION TO PYTHON -NOTES

Python provides a built-in function called len() to find the number of characters in a
string.
This count includes:
• letters
• digits
• spaces
• punctuation
• special characters

Syntax
len(string)

Example
text = "Python"
print(len(text))
Output:
6

Explanation:
The string "Python" has 6 characters:
P, y, t, h, o, n → total = 6

What is String traversal. How can it be accomplished in 2 ways

String traversal means visiting each character of a string one by one.


Python allows traversal in two ways:
1. Using a while loop
2. Using a for loop
We will use one example string for both:
s = "Python"

1. Traversing a String Using while Loop


We use an index to move from one character to the next.
s = "Python"
i=0
while i < len(s):
print(s[i])
i += 1

DEPT. OF AIML, JNNCE


34
INTRODUCTION TO PYTHON -NOTES

Explanation:
• Start index i = 0
• Continue until end of string (i < len(s))
• Print each character using s[i]
• Increase index after each step

2. Traversing a String Using for Loop


Simplest and most commonly used method.
s = "Python"
for ch in s:
print(ch)
Explanation:
• The loop automatically takes each character from the string
• No need for index or manual counting
• ch stores one character at a time

Discuss string slicing with various options

String slicing means extracting a part of a string using a special format:


string[start : stop : step]
start → index where the slice begins
stop → index where the slice ends (exclusive)
step → how many characters to skip each time (increment)
If any part is missing, Python uses a default value.

1. Basic Example
Let:
s = "Pirates of the Caribbean"
▶ Example 1: Slice first 7 characters
print(s[0:7])
Output:
Pirates
Explanation: characters from index 0 to 6

▶ Example 2: Slice from middle


print(s[8:10])

DEPT. OF AIML, JNNCE


35
INTRODUCTION TO PYTHON -NOTES

Output:
of

▶ Example 3: Using step


print(s[0:14:2])
Output:
Prts f h
Every 2nd character from index 0 to 13 is taken.

2. Default Values
▶ No start → starts from beginning
print(s[:7])
→ Pirates
▶ No stop → goes till end
print(s[8:])
→ of the Caribbean
▶ No step → takes every character
print(s[0:7])
→ same as above

3. Negative Index Slicing


▶ Example:
print(s[-9:-1])
Output:
Caribbea

Explain lexicographical comparison of string with various operators


Lexicographical comparison means comparing strings character by character, similar
to how words are arranged in a dictionary.
Python compares characters using their Unicode (ASCII) values.
Order of comparison:
1. Compare first character of both strings
2. If equal → compare next character
3. If different → the string with the smaller ASCII value is considered smaller
4. If all characters are equal → strings are equal

Comparison Operators
You can compare strings using:
== != < > <= >=

Example Code
s1 = "Apple"
s2 = "Banana"

if s1 < s2:

DEPT. OF AIML, JNNCE


36
INTRODUCTION TO PYTHON -NOTES

print("Apple comes before Banana")


else:
print("Banana comes before Apple")
Output:
Apple comes before Banana
Explanation:
• Compare first letters: 'A' vs 'B'
• ASCII of A = 65
• ASCII of B = 66
• Since 65 < 66 → "Apple" < "Banana"

Another Example
print("cat" > "car")
Output:
True
Why?
• Compare 'c' = 'c'
• Compare 'a' = 'a'
• Compare 't'(116) vs 'r'(114)
• 116 > 114 → "cat" is greater than "car"

Strings are immutable-Substantiate:


In Python, strings are immutable, which means they cannot be changed after they
are created. You cannot modify an individual character inside a string.

Trying to Modify a Character → Error


Name = "Michael Jackson"
Name[1] = "J" # Not allowed
Output:
TypeError: 'str' object does not support item assignment
Reason: Strings do not allow changing individual characters.

Changing the Whole String is Allowed


You can reassign a new string because you’re not modifying the original—you’re
creating a new one.
Name = "Michael Jackson"
Name = Name + " is the best"
print(Name)
Output:
Michael Jackson is the best
This works because Python creates a new string and assigns it to the variable Name.

What are two membership operators in Python


Python provides two membership operators:

DEPT. OF AIML, JNNCE


37
INTRODUCTION TO PYTHON -NOTES

• in → checks if a substring/character exists inside a string


• not in → checks if a substring/character does NOT exist inside a string
These operators return True or False.

1. Using in Operator
Meaning
Checks whether a given character or substring is present in the string.
Example
s = "Python Programming"

print("Python" in s)
print("Pro" in s)
print("Java" in s)

Output:
True
True
False
Explanation:
• "Python" exists in the string → True
• "Pro" exists in the string → True
• "Java" does not exist → False

2. Using not in Operator


Meaning
Checks whether a substring is NOT present in the string.
Example
s = "Hello World"

print("Hi" not in s)
print("World" not in s)

Output:
True
False
Explanation:
• "Hi" is not in the string → True
• "World" is present → so "World" not in s" is False

Explain find method in Python. Also write python program to find all
occurrences of a given character:

find() Method in Python

DEPT. OF AIML, JNNCE


38
INTRODUCTION TO PYTHON -NOTES

The find() method is used to search for a substring or character inside a string.
It returns the index of its first occurrence.
Syntax
[Link](substring)
If found → returns index (0, 1, 2, …)
If not found → returns -1

Example of find()
s = "programming"
print([Link]("g"))
Output:
3
Explanation:
The first "g" appears at index 3.

Python Program to Find All Occurrences of a Character

def findall(s,ch):
pos=[Link](ch)
while pos!=-1:
print(pos)
pos=[Link](ch,pos+1)

s="mississippi"
findall(s,'i')

Output:

Write a Python function to count the number of occurrences of specific


character
def countocc(s,ch):
cnt=0
for c in s:
if c==ch:
cnt+=1

DEPT. OF AIML, JNNCE


39
INTRODUCTION TO PYTHON -NOTES

return cnt
s='mississippi'
ans=countocc(s,'i')
print(ans)

Output:
4

Tracing table:
Step c (current char) c == 'i'? cnt (before) cnt (after)
1 m No 0 0
2 i Yes 0 1
3 s No 1 1
4 s No 1 1
5 i Yes 1 2
6 s No 2 2
7 s No 2 2
8 i Yes 2 3
9 p No 3 3
10 p No 3 3
11 i Yes 3 4

Explain the role of split() in strings


The split() method is used to break a string into a list of words or parts, based on a
separator (also called a delimiter).
By default, it splits on spaces.

Syntax
[Link](separator)
• separator (optional): the character(s) where the string should be split.
• If not given → Python splits wherever it finds whitespace (spaces, tabs,
newlines).

1. Splitting Using Space (Default)


s = "Python is fun"
print([Link]())
Output:
['Python', 'is', 'fun']
Explanation:
The string is split at each space.

2. Splitting Using a Specific Character


s = "apple,banana,grapes"
print([Link](","))

DEPT. OF AIML, JNNCE


40
INTRODUCTION TO PYTHON -NOTES

Output:
['apple', 'banana', 'grapes']

Write a Python program to clean strings by removing punctuation


symbols
p=",!?:;&<>[]()"
s="This is a story about Romeo,Juliet!It is a tragic story?"
ns=""
for c in s:
if c in p:
continue
ns=ns+c
print(ns)

Output:

Tracing table:
Step c (character) c in p Action ns (new string so far)
?
1 T No add T
2 h No add Th
3 i No add Thi
4 s No add This
… (spaces/letters) No add This is a story about Romeo
25 , Yes skip (no change)
… Juliet No add This is a story about RomeoJuliet
33 ! Yes skip (no change)
… story No add This is a story about RomeoJulietIt is a
tragic story
last ? Yes skip (final)

Explain various uses of string formatting in Python

DEPT. OF AIML, JNNCE


41
INTRODUCTION TO PYTHON -NOTES

The format() method in Python is used to insert values into a string.


It replaces { } placeholders inside a string with the values you provide.

Basic Syntax
"string with {placeholders}".format(values)

1. Positional Formatting
You can insert values in order:
msg = "My name is {} and I am {} years old.".format("John", 20)
print(msg)
Output:
My name is John and I am 20 years old.

2. Indexed Placeholders
You can control which value goes where:
msg = "First: {1}, Second: {0}".format("Apple", "Banana")
print(msg)
Output:
First: Banana, Second: Apple

3. Named Placeholders
You can use keyword arguments:
msg = "Name: {name}, Age: {age}".format(name="Rohan", age=40)
print(msg)
Output:
Name: Rohan, Age: 40

4. Formatting Numbers
Fixed decimal places
"Value = {:.2f}".format(12.34567)
Output:
Value = 12.35

Field width (alignment)


{:10} → width 10
{:<10} → left-align
{:>10} → right-align
{:^10} → center-align

Example:
s1="Tom"
s2="Jerry"
p1="{0:<15} and {1:<15}".format(s1,s2)
p2="{0:>15} and {1:>15}".format(s1,s2)
p3="{0:^15} and {1:^15}".format(s1,s2)

DEPT. OF AIML, JNNCE


42
INTRODUCTION TO PYTHON -NOTES

print(p1)
print(p2)
print(p3)
Output:

5. Formatting Integers
Binary, Octal, Hex
print("Binary: {:b}, Hex: {:x}".format(15, 15))
Output:
Binary: 1111, Hex: f

6. Padding with Zeros


print("{:05}".format(42))
Output:
00042

7. Combining Multiple Options


You can combine alignment + width + decimals:
print("{:>10.2f}".format(3.14159))
Output:
3.14

Define tuples and enlist their properties with example


A tuple is an ordered, immutable collection of items in Python.
It is similar to a list, but cannot be changed after creation.
Tuples are written using round brackets ( ).

Syntax
t = (item1, item2, item3)

Properties of Tuples
Ordered
Tuple elements have a fixed order — the order will not change.
Immutable
Once created, elements cannot be modified, added, or removed.
Allow duplicate values
Tuples can contain repeated elements.
Can contain mixed data types
A tuple can have integers, strings, floats, lists, etc.

DEPT. OF AIML, JNNCE


43
INTRODUCTION TO PYTHON -NOTES

Indexed
Elements can be accessed using their index, just like lists. t[0], t[1] ...
Supports slicing
Tuples allow slicing: t[1:4]
Faster than lists
Tuples are more memory-efficient and faster to access.
Can be nested
Tuples can contain other tuples or lists.

Examples of Tuples
Example 1: Simple tuple
t = (10, 20, 30)
Example 2: Mixed data types
t = ("Alice", 25, 5.6)
Example 3: Nested tuple
t = (1, 2, (3, 4), 5)
Example 4: Accessing elements
t = ("apple", "banana", "cherry")
print(t[1]) # banana
print(t[0:2]) # ('apple', 'banana')
Example 5: Duplicate values allowed
t = (1, 2, 2, 3, 3, 3)

Explain the two important applications of tuples

1. Tuples Used for Grouping of Data


Meaning
A tuple can store different pieces of related information together in one unit.
It acts like a container for grouping values that belong together.
Why grouping?
Because tuples are ordered and immutable, they are perfect for storing fixed sets of
information such as:
• Student record: (Name, USN, Branch)
• Coordinates: (x, y)
• Date: (day, month, year)

DEPT. OF AIML, JNNCE


44
INTRODUCTION TO PYTHON -NOTES

• RGB color: (255, 0, 0)


Example
Grouping a student’s information into one tuple:
student = ("Chetan", "1JN20AI001", "AIML")
Now the tuple acts as one whole record.

2. Tuples Used for Nesting of Data


Meaning
Nesting means placing one tuple inside another tuple.
Just like a bird keeps multiple eggs in a nest, a tuple can hold multiple smaller tuples.
Why nesting?
To represent structured or hierarchical data, such as:
• Class of students
• Matrix (2D data)
• Weekly time tables
• Geographic coordinates for multiple locations
Example
A list of 3D coordinates stored as nested tuples:
points = ((2, 3, 4), (5, 6, 7), (1, 0, 9))
Or grouping multiple student records:
students = (
("Chetan", "AIML"),
("Rahul", "CSE"),
("Asha", "ECE")
)

Explain the immutability of tuples and its use


A tuple is immutable, meaning once it is created, its elements cannot be changed.
You cannot:
• Modify an element
• Add new elements
• Remove elements
• Rearrange the order
Example:
t = (10, 20, 30)
t[1] = 50 # Error
This produces:
TypeError: 'tuple' object does not support item assignment
The tuple remains exactly the same throughout the program.

Why Tuples are Immutable (Uses & Advantages)


1. Safety of Data (Protection)
Immutability ensures that data cannot be accidentally changed.
Useful for storing:

DEPT. OF AIML, JNNCE


45
INTRODUCTION TO PYTHON -NOTES

• Dates
• Coordinates
• Configuration values
• Student records that must not change

2. Faster Access
Tuples are faster than lists because Python stores them in a compact, fixed structure.
Good for performance-sensitive operations.

3. Used in Return Statements


Functions often return multiple values in a tuple because the result is safe and stable.
def get_point():
return (3, 4)

4. Reliable for Grouping Fixed Data


If the group of values should never change, tuples are ideal.
Example:
rgb = (255, 0, 0)

Explain packing and unpacking concepts of tuples with various types


of assignment also write how swapping is easier with tuples.
1. Tuple Packing
Packing means putting multiple values together into a single tuple. Python
automatically packs values into a tuple when you separate them by commas.

Example:
t = 10, 20, 30
print(t)
Output:
(10, 20, 30)
Here, the values 10, 20, 30 get packed into a tuple.
You may also use parentheses:
t = (10, 20, 30)
Packing = grouping multiple values into one tuple.

2. Tuple Unpacking
Unpacking means extracting the values of a tuple into individual variables.

Example:
t = (10, 20, 30)
a, b, c = t
print(a, b, c)
Output:
10 20 30
Each element of the tuple is assigned to a separate variable.

DEPT. OF AIML, JNNCE


46
INTRODUCTION TO PYTHON -NOTES

Unpacking = splitting a tuple into variables.

3. Various Types of Tuple Assignment


(A) variable = tuple
Assign a tuple to one variable.
t = (1, 2, 3)

(B) tuple = variable


Assign a variable containing a tuple to another tuple variable.
x = (4, 5, 6)
t=x

(C) tuple = tuple


Reassign one tuple to another.
t1 = (1, 2)
t2 = (3, 4)
t1 = t2 # now t1 is (3,4)

(D) Multiple Assignment (Packing + Unpacking)


a, b, c = 10, 20, 30
This is packing (right side) + unpacking (left side) in one step.

4. Extended Unpacking Using * Operator


Python allows grabbing many values using *.
a, *b = (10, 20, 30, 40)
Result:
a = 10
b = [20, 30, 40]

5. Swapping Is Easier With Tuples


In other languages, swapping requires a temporary variable:
temp = a
a=b
b = temp
In Python:
Swapping uses tuple packing + unpacking in a single line.
a = 10
b = 20

a, b = b, a
Output:
a = 20
b = 10

Why it works?

DEPT. OF AIML, JNNCE


47
INTRODUCTION TO PYTHON -NOTES

• Right side packs: (b, a), Left side unpacks: a, b


• No temporary variable needed.

Tuple assignment in Python follows this rule:


Number of variables on the left must match the number of values on the right.
If they don’t match → ValueError.

1. Mismatch in number of elements (most common)


Example 1 — Too many values:
a, b = (10, 20, 30)
Error:
ValueError: too many values to unpack

Example 2 — Too few values:


a, b, c = (5, 6)
Error:
ValueError: not enough values to unpack

Write a python program to demonstrate tuples as return values


def circle_properties(r):
area = 3.14 * r * r
perimeter = 2 * [Link] * r
diameter = 2 * r
return (area, perimeter, diameter) # returning a tuple

radius = 5
result = circle_properties(radius)

print("Returned tuple:", result)

Output:

Demonstrate various python tuple functions

DEPT. OF AIML, JNNCE


48
INTRODUCTION TO PYTHON -NOTES

o=(1,4,3,2,5,-2)
print(len(o))
print(max(o))
print(min(o))
print(sorted(o))
print(sorted(o,reverse=True))
l=[4,5,6,2,3]
t=tuple(l)
print(t)

Output:

DEPT. OF AIML, JNNCE


49

You might also like