Introduction to Python Programming Notes
Introduction to Python Programming 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
Every expression has a value and often contributes to a larger instruction in the
program.
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
Now expression:
5 * 3 ** 2
Exponent (PEMDAS): 3 ** 2 = 9
Expression becomes: 5 * 9
Multiplication: 5 * 9 = 45
Final Result = 45
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:
Enter first number: 10
Enter second number: 20
Sum = 30
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
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
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
Eg:
print(10 % 3) # Output: 1 (10 = 3×3 + 1)
print(25 % 7) # Output: 4 (25 = 7×3 + 4)
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
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
Output:
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
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
The loop runs 5 times (from 0 to 4)
Output:
1
2
3
4
5
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 — —
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 —
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:
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
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
while i < n:
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)
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
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.
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
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
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
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)
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
]
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:
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
print("Intersted in music",cnt)
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
print("Intersted in music",cnt)
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
Flowchart:
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)
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))
Example:
def greet():
print("Hello! Welcome to Python")
greet()
Output:
Hello! Welcome to Python
Example:
def display(name):
print("Hello", name)
display("Asha")
Output:
Hello Asha
Example:
def get_pi():
return 3.14159
x = get_pi()
print(x)
Output:
3.14159
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
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:
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?)
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
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
3. capitalize() - Makes only the first letter uppercase and the rest lowercase.
Example:
"pYtHoN".capitalize()
Python
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:
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
Explanation:
• Start index i = 0
• Continue until end of string (i < len(s))
• Print each character using s[i]
• Increase index after each step
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
Output:
of
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
Comparison Operators
You can compare strings using:
== != < > <= >=
Example Code
s1 = "Apple"
s2 = "Banana"
if s1 < s2:
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"
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
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:
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.
def findall(s,ch):
pos=[Link](ch)
while pos!=-1:
print(pos)
pos=[Link](ch,pos+1)
s="mississippi"
findall(s,'i')
Output:
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
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).
Output:
['apple', 'banana', 'grapes']
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)
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
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)
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
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.
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)
• 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.
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.
a, b = b, a
Output:
a = 20
b = 10
Why it works?
radius = 5
result = circle_properties(radius)
Output:
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: