Final Python Questions
Final Python Questions
Introduction to Programming
2026
2. To make debugging easy: If your code has an error, you can ”comment out”
lines to test specific parts without deleting your work.
3 Multi-line Comments
Sometimes, a single line isn’t enough to explain complex logic. In Python, there are two
common ways to write comments that span multiple lines:
• Using multiple hashes: Placing a # at the start of every line.
• Triple Quotes: Using ’’’ or """. Technically, these are ”docstrings,” but if they
are not assigned to a variable, Python ignores them, making them perfect for long
explanations.
’’’
Method 2: Using triple quotes .
This is often used for very long
paragraphs of explanation .
1
’’’
print ( " Comments make code better ! " )
4 Practice Problems
Complete these tasks in your Python editor to practice using comments effectively.
Task 1: Create a variable named age and assign it your age. Add a single-line comment
above it explaining what the variable does.
Task 2: Write a program that prints ”Python is fun!”. Add an inline comment on the
same line that says ”Displaying a message”.
Task 3: Write a math operation (e.g., 5 * 5). Comment out this line so that it does not
run.
Task 4: Write a script that calculates the price of 3 apples (each costs $2). Use **triple
quotes** (’’’) to write a 3-line explanation of your calculation logic.
Task 5: Copy the code below and comment out the second line.
print ( " Starting the program ... " )
print ( " Second Line of the program " )
print ( " Program finished successfully . " )
2
5 Answer Key
Important Disclaimer
These answers are only for reference. Your solution might be different because
there are many ways to write code. Please only use this key if you are stuck or
want to verify your work after finishing.
Solution 1
# Storing the age of the user
age = 20
Solution 2
print ( " Python is fun ! " ) # Displaying a message
Solution 3
# 5 * 5
Solution 4
’’’
Each apple costs 2 dollars .
We are purchasing 3 apples in total .
Multiplying cost by quantity .
’’’
total = 2 * 3
print ( total )
Solution 5
print ( " Starting the program ... " )
# print (" Second Line of the program ")
print ( " Program finished successfully . " )
3
Python Programming: Understanding Variables
Introduction to Programming
January 2026
g
2 Why Do We Use Variables?
in
1. To reuse information: Instead of typing the same value many times, you store
rn
it once in a variable and use the name elsewhere.
lea
2. To make updates easy: If you change a value in the variable definition, it updates
everywhere that name is used.
ys
3. To give meaning to data: A variable name like price explains what the number
99 actually represents.
da
4 Examples of Variables
name = " Alice " # A string ( text )
age = 25 # An integer ( whole number )
score = 88.5 # A float ( decimal number )
print ( name )
print ( age + 5) # Performs addition using the variable
1
5 Practice Problems
Task 1: Create a variable called city and store your favorite city name. Print the vari-
able.
Task 2: Create two variables: num1 = 10 and num2 = 20. Create a third variable called
result that adds them together. Print result.
Task 3: Naming Challenge: Identify which of these is a valid Python name: 1st place,
total-score, or user age. Explain why the others are wrong in a comment.
Task 4: Create a variable called price and set it to 100. On the next line, change price
to 150. Print the variable to see the updated value.
Task 5: Personal Profile: Create three variables: my name, my hobby, and fav color.
Assign your own details to them. Finally, print all three variables to introduce
yourself in the output.
g
in
rn
lea
ys
da
21
2
6 Answer Key
Important Disclaimer
These answers are only for reference. Your solution might be different as there are
many ways to code. Only check these after you have tried solving the problems
yourself!
Solution 1
city = " Hyderabad "
print ( city )
Solution 2
num1 = 10
num2 = 20
g
result = num1 + num2
print ( result )
in
rn
Solution 3
lea
# Correct : user_age
# Wrong : 1 st_place ( Starts with a number )
ys
Solution 4
21
price = 100
price = 150 # The old value 100 is replaced
print ( price )
Solution 5
my_name = " Nani "
my_hobby = " Cricket "
fav_color = " Blue "
print ( my_name )
print ( my_hobby )
print ( fav_color )
3
Python Programming: Every Value has a Type!
Introduction to Programming
January 2026
g
The 7 Core Types You Must Know
in
rn
1. Integer (int)
lea
Definition: This data type represents whole numbers. We use integers to count things
that cannot be split into parts, such as the number of students in a class or a car’s speed.
Python handles extremely large integers easily.
ys
2. Float (float)
Definition: Floats are used for numbers that have a decimal point. They are essential
for any task requiring precision, such as calculating prices, measuring weight, or storing
GPS coordinates. If you write 5.0, Python sees it as a float, not an integer.
Values: Any number with a dot (e.g., 19.99, -0.5, 4.0).
Syntax: variable name = decimal number
Example: price = 99.50
3. String (str)
Definition: A String is used to store text. It can be a single letter, a word, or a whole
paragraph. To tell Python that something is text and not a command, you must wrap it
in quotes. Once created, a string’s content cannot be changed directly.
Values: Any text inside ’single’ or ”double” quotes (e.g., ”Hello”, ”123”).
Syntax: variable name = "text here"
Example: city = "New York"
1
4. Boolean (bool)
Definition: Booleans represent logic. They act like a light switch that is either ON or
OFF. We use them to answer ”Yes/No” questions in code, like ”Is the user logged in?”
or ”Is the game over?”.
Values: Only two: True or False (Must be capitalized).
Syntax: variable name = True
Example: is passed = True
5. List (list)
Definition: A List is a collection used to store multiple items in a specific order. Lists
are ”mutable,” meaning you can add, remove, or change items later. The items in a
list can be of different data types. It is like a flexible shopping list where you can
keep adding items as you walk through a store.
Values: Items separated by commas inside square brackets [ ].
Syntax: list name = [item1, item2, item3]
Example: my list = ["Apple", 10, 5.5, True]
g
6. Tuple (tuple)
in
rn
Definition: A Tuple is similar to a list as it stores multiple items in order. However,
Tuples are ”immutable,” meaning once they are created, they cannot be changed.
They are used for data that should never be edited, like the coordinates of a location.
lea
7. Dictionary (dict)
Definition: A Dictionary stores data in ”Key-Value” pairs. It works like a real-life
21
dictionary or a phone contact list: you use a ”Key” (a name) to look up a ”Value” (a
phone number). This is perfect for storing organized information about a single object.
Values: Pairs written as key: value inside curly braces { }.
Syntax: dict name = {"key": "value"}
Example: laptop = {"brand": "Dell", "ram": "16GB"}
2
Practice Problems
Task 1: Create an Integer variable for score and a Float for temperature.
Task 2: Declare a String variable called book title for your favorite book.
Task 4: Create a List named mixed data containing a city name (string) and a temper-
ature (float).
Task 5: Create a Dictionary for a person with keys ”name” and ”hobby”.
Answer Key
Disclaimer
g
These answers are only for reference. Your solution might be different as there are
many ways to code. Only check these after you have tried solving the problems
in
yourself! rn
Solution 1
ea
score = 100
temperature = 36.6
l
print ( score )
print ( temperature )
ys
da
Solution 2
book_title = " Timeline "
21
print ( book_title )
Solution 3
is_daylight = False
print ( is_daylight )
Solution 4
mixed_data = [ " Hyderabad " , 32.5]
print ( mixed_data )
3
Solution 5
person = {
" name " : " Arjun " ,
" hobby " : " Reading "
}
print ( person )
g
in
rn
lea
ys
da
21
4
Python Programming: Typecasting
Introduction to Programming
January 2026
What is Typecasting?
Typecasting (or Type Conversion) is the process of changing a value from one data type
to another.
Imagine you have a variable named age with the value "21". Because it is in quotes,
Python treats it as a String (text). If you try to add 2 to this age, Python will give you an
error because you cannot add a number to text. To fix this, you must use Typecasting
g
to convert the string "21" into an Integer 21. This makes the data compatible so you
in
can perform your math. Python supports two types of casting: implicit and explicit.
rn
1. Implicit Type Conversion
lea
In this method, Python does the work for you. The interpreter automatically converts
one type to another to prevent data loss.
ys
For example, if you add an Integer (10) to a Float (5.5), Python automatically turns
the integer into a float (10.0) so the decimal result is not lost.
da
num_int = 10 # integer
num_float = 5.5 # float
21
1
• str(): Changes a value into text.
# String to Integer
s = " 100 "
i = int ( s ) # Converts text "100" to number 100
# Integer to Float
f = float ( i ) # Converts 100 to 100.0
# Number to String
text = str ( f ) # Converts 100.0 back to "100.0"
Practice Problems
Task 1: Create a variable a = "50" and b = "20". Add them together so the result is
g
70 (not ”5020”).
Task 2:
in
Take a float variable pi = 3.14. Convert it into an integer and print the result.
What happened to the decimal?
rn
Task 3: Create an integer age = 25. Print a message saying: ”I am [age] years old” using
lea
Task 4: Convert the number 0 into a boolean. Then convert the number 1 into a boolean.
ys
Print both.
da
Task 5: Ask the user for a number using input(), multiply it by 2 before and after
typecasting the input to int, and print the result.
21
Task 7: Create a list: my data = [1, 2, 3]. Convert this list into a Tuple.
Task 8: Ask the user for two numbers. Add them and print: ”The total sum is: [result]”.
Task 9: Convert an empty string "" and a string with a space " " to Booleans.
Task 10: Convert the float 9.99 to an int and add it to the string "5" after converting
to an int.
2
Answer Key
Important Disclaimer
These answers are only for reference. Only check these after you have tried solving
the problems yourself!
Solutions 1 - 5
# Task 1
a , b = " 50 " , " 20 "
print ( int ( a ) + int ( b ) )
# Task 2
pi = 3.14
print ( int ( pi ) ) # Output : 3
# Task 3
g
age = 25
in
print ( " I ␣ am ␣ " + str ( age ) + " ␣ years ␣ old " )
rn
# Task 4
print ( bool (0) , bool (1) ) # False , True
lea
# Task 5
num = input ( " Enter ␣ a ␣ number : ␣ " )
ys
print ( num * 2)
print ( int ( num ) * 2)
da
Solutions 6 - 10
21
# Task 6
s = " 15.7 "
print ( int ( float ( s ) ) )
# Task 7
my_tuple = tuple ([1 , 2 , 3])
print ( my_tuple , type ( my_tuple ) )
# Task 8
n1 = float ( input ( " Number ␣ 1: ␣ " ) )
n2 = float ( input ( " Number ␣ 2: ␣ " ) )
print ( " The ␣ total ␣ sum ␣ is : ␣ " + str ( n1 + n2 ) )
# Task 9
print ( bool ( " " ) , bool ( " ␣ " ) ) # False , True
# Task 10
print ( int (9.99) + int ( " 5 " ) ) # 9 + 5 = 14
3
Python Programming: Operators
Introduction to Programming
January 2026
1. Arithmetic Operators
g
Used for basic mathematical calculations.
in
• Addition (+): Adds two values together. Ex: 5 + 2 is 7.
rn
• Subtraction (-): Subtracts one value from another. Ex: 5 - 2 is 3.
lea
• Floor Division (//): Divides and rounds down to the nearest whole number.
Ex: 5 // 2 is 2.
2. Assignment Operators
Used to store or update values in variables.
• Assignment (=): Assigns the right value to the left variable. Ex: x = 10.
• Compound (+=, -=, *=, etc.): Performs an operation and assigns the result
back to the same variable. Ex: x += 5 is same as x = x + 5.
1
3. Comparison (Relational) Operators
Used to compare two values; they always return True or False.
• Greater than (>), Less than (<): Checks if a value is larger or smaller. Ex:
5 > 2 is True.
• Greater/Less than or Equal (>=, <=): Checks size or equality. Ex: 5 >=
5 is True.
4. Logical Operators
Used to combine conditional statements.
g
• or: True if at least one statement is True.
in
• not: Reverses the result (True becomes False).
rn
Example:
lea
x = 10
y = 5
ys
# AND operator
da
print ( x > 5 and y < 10) # True ( both conditions are True )
# OR operator
21
# NOT operator
print ( not ( x > 5) ) # False ( reversed result )
5. Identity Operators
Identity operators check whether two variables refer to the same object in memory,
not just equal values.
Example:
2
a = [1 , 2 , 3]
b = a
c = [1 , 2 , 3]
6. Membership Operators
Membership operators check whether a value exists inside a sequence such as a list, tuple,
string, or set.
g
Examples:
numbers = [1 , 2 , 3 , 4] in
rn
print (3 in numbers ) # True
print (5 not in numbers ) # True
lea
7. Bitwise Operators
21
Bitwise operators work on numbers at the binary (bit) level. They are mainly used in
low-level programming, performance optimization, and hardware-related tasks.
Binary Basics
Computers store numbers in binary (base 2).
Bitwise Operators
• AND (&): Bit is 1 only if both bits are 1.
3
• NOT (˜): Inverts all bits.
Examples
a = 5 # Binary : 101
b = 3 # Binary : 011
g
in
rn
lea
ys
da
21
4
Practice Problems
Task 1: Calculate the remainder when 37 is divided by 5 using an operator.
Task 2: Create a variable y = 20. Use a compound operator to subtract 5 from it.
Task 3: Check if the number 50 is greater than 40 AND less than 60.
Task 4: Check if the word ”Python” is in the list ["Java", "Python", "C++"].
g
Task 9: Combine not and in to check if ”z” is absent in ”sky”.
Task 10: in
Predict the result of bitwise 2 & 3.
rn
Answer Key
lea
Important Disclaimer
ys
Solutions 1 - 5
21
# Task 1
print (37 % 5) # Output : 2
# Task 2
y = 20
y -= 5
print ( y ) # Output : 15
# Task 3
num = 50
print ( num > 40 and num < 60) # Output : True
# Task 4
tech = [ " Java " , " Python " , " C ++ " ]
print ( " Python " in tech ) # Output : True
# Task 5
print (17 // 3) # Output : 5
5
Solutions 6 - 10
# Task 6
print (3 ** 4) # Output : 81
# Task 7
a = 5
b = 10
# Swapping
c = a
a = b
b = c
# Single line Swapping
a, b = b, a
# Task 8
a = 10
b = 10.0
print ( a is not b ) # Output : True ( Types / Objects are different )
g
# Task 9
in
print ( " z " not in " sky " ) # Output : True
rn
# Task 10
lea
6
Python Programming: Conditional Statements
Introduction to Programming
January 2026
g
1. if Statement
in
The if statement is used when we want to execute a block of code only if a condition
rn
is True. If the condition is False, Python skips the block completely.
Execution Flow:
lea
Syntax:
21
if condition :
# code runs only if condition is True
Example:
age = 20
2. if-else Statement
The if-else statement is used when we want Python to choose between two paths.
Execution Flow:
• Python checks the if condition
1
• If False → else block executes
Syntax:
if condition :
# code if condition is True
else :
# code if condition is False
Example:
number = 7
if number % 2 == 0:
print ( " Even ␣ number " )
else :
print ( " Odd ␣ number " )
Important: Exactly one block will execute, either if or else.
3. if-elif-else Statement
g
in
The if-elif-else statement is used when there are multiple conditions.
Execution Flow:
rn
• Python checks the if condition first
lea
• Once a condition is True, its block executes and the rest are skipped
da
Syntax:
if condition1 :
# code
elif condition2 :
# code
elif condition3 :
# code
else :
# code ( optional )
Example:
marks = 75
2
Important Notes:
Practice Problems
Task 1: If a number is positive, print "Positive", otherwise print "Not Positive".
Task 3: If age is 18 or more, print "Eligible to vote", else print "Not eligible".
Task 4: If a number is greater than 100, print "Greater than 100", else print "100 or
less".
g
Task 5: If a character is a vowel, print "Vowel", else print "Not a vowel".
divisible".
Task 8: Print grades: "A" for marks >= 90, "B" for marks >= 60, else print "C".
da
Task 9: If a year is a leap year, print "Leap year", else print "Not a leap year".
21
Task 10: Print ticket price: 50 if age <12, 100 if age <60, else 70.
3
Answer Key
Important Disclaimer
Check these only after solving the tasks yourself!
Solutions 1 – 5
# Task 1
num = 5
if num > 0:
print ( " Positive " )
else :
print ( " Not ␣ Positive " )
# Task 2
g
num = 7
in
if num % 2 == 0:
print ( " Even " )
else :
rn
print ( " Odd " )
# Task 3
ea
age = 16
if age >= 18:
l
# Task 4
num = 85
if num > 100:
21
# Task 5
ch = ’b ’
if ch in " aeiou " :
print ( " Vowel " )
else :
print ( " Not ␣ a ␣ vowel " )
Solutions 6 – 10
# Task 6
num = 15
if num % 3 == 0 and num % 5 == 0:
print ( " Divisible " )
4
else :
print ( " Not ␣ divisible " )
# Task 7
a = 10
b = 20
if a > b :
print ( a )
else :
print ( b )
# Task 8
marks = 72
if marks >= 90:
print ( " A " )
elif marks >= 60:
print ( " B " )
else :
print ( " C " )
g
# Task 9
year = 2023 in
rn
if year % 4 == 0:
print ( " Leap ␣ year " )
lea
else :
print ( " Not ␣ a ␣ leap ␣ year " )
ys
# Task 10
age = 65
da
print (100)
else :
print (70)
5
Python Programming: Loops
Introduction to Programming
January 2026
Loops
Loops are used to repeat a block of code multiple times. Instead of writing the
same code again and again, loops help us run it automatically based on a condition or
sequence.
Python mainly provides two types of loops:
g
• while loop
• for loop in
rn
1. while Loop
lea
The while loop executes a block of code as long as a condition is True. Before each
ys
Syntax:
while condition :
# code to repeat
Important Point: The condition must eventually become False, otherwise the loop
will run forever (infinite loop).
Example: Print numbers from 1 to 5
i = 1
while i <= 5:
print ( i )
i += 1
1
Explanation:
• i starts with value 1
• Loop runs while i <= 5
• After each print, i is increased by 1
• When i becomes 6, condition becomes False and loop stops
2. for Loop
The for loop is used to iterate over a sequence such as:
• list
• string
• tuple
g
• range of numbers
Execution Flow:
in
rn
• Python takes the first value from the sequence
• Executes the loop body using that value
lea
Syntax:
for variable in sequence :
21
# code to repeat
Example: Loop through a list
fruits = [ " apple " , " banana " , " cherry " ]
3. range() Function
The range() function is used with for loops to generate a sequence of numbers.
2
range(end)
• Starts from 0
• 1, 2, 3, 4, 5
g
• step: Difference between each number. If step is not passed as an argument, by
default Python will take it as +1. in
rn
Execution Flow:
lea
print ( i )
Output:
• 1, 3, 5, 7, 9
3
Practice Problems
Task 1: Use a while loop to print numbers from 1 to 10.
Task 3: Use a for loop to print each character in the string "Python".
Task 5: Use a for loop to calculate and print the sum of numbers from 1 to 5.
Task 7: Print all odd numbers between 1 and 20 using a for loop.
Task 8: Count how many characters are there in the string "programming".
g
Task 9: Use a loop to print numbers from 10 to 1 in reverse order.
in
Task 10: Print the square of numbers from 1 to 5 using a for loop.
rn
lea
ys
da
21
4
Answer Key
Important Disclaimer
Check these only after solving the tasks yourself!
Solutions 1 – 5
# Task 1
i = 1
while i <= 10:
print ( i )
i += 1
# Task 2
i = 2
g
while i <= 10:
in
print ( i )
i += 2 rn
# Task 3
for ch in " Python " :
print ( ch )
ea
# Task 4
l
for i in range (1 , 6) :
print ( i )
ys
# Task 5
da
total = 0
for i in range (1 , 6) :
total += i
21
print ( total )
Solutions 6 – 10
# Task 6
i = 1
while i <= 10:
print ( " 5 ␣ x " , i , " = " , 5 * i )
i += 1
# Task 7
for i in range (1 , 21 , 2) :
print ( i )
# Task 8
count = 0
for ch in " programming " :
5
count += 1
print ( count )
# Task 9
for i in range (10 , 0 , -1) :
print ( i )
# Task 10
for i in range (1 , 6) :
print ( i * i )
g
in
rn
lea
ys
da
21
6
Python Programming: break, continue and pass
Introduction to Programming
January 2026
g
• for loops
1. break Statement
in
rn
The break statement is used to immediately stop a loop, even if the loop condition
lea
is still True.
Execution Flow:
ys
Syntax:
for variable in sequence :
if condition :
break
Example: Stop loop when number becomes 5
for i in range (1 , 10) :
if i == 5:
break
print ( i )
Output:
• 1, 2, 3, 4
Explanation:
• Loop starts from 1
• When i == 5, break executes
• Loop stops completely
1
2. continue Statement
The continue statement is used to skip the current iteration and move to the next
iteration of the loop.
Execution Flow:
Syntax:
for variable in sequence :
if condition :
continue
# code skipped when continue runs
Example: Skip number 5
g
for i in range (1 , 8) :
if i == 5:
continue in
rn
print ( i )
Output:
lea
• 1, 2, 3, 4, 6, 7
ys
Explanation:
3. pass Statement
The pass statement is used as a placeholder. It does nothing but avoids syntax errors
when a statement is required.
Execution Flow:
• Nothing happens
Syntax:
if condition :
pass
Example:
2
for i in range (1 , 6) :
if i == 3:
pass
print ( i )
Output:
• 1, 2, 3, 4, 5
Important Point:
Practice Problems
Task 1: Print numbers from 1 to 10 but stop when number reaches 6.
g
in
Task 3: Print numbers from 1 to 10, but skip multiples of 3.
rn
Task 4: Skip all even numbers and print only odd numbers between 1 and 10.
Task 6: Given a list of numbers [2, 4, 6, 8, 10, 7, 12], use a loop and break to
da
Task 7: Given a string "python programming", use continue to skip printing the char-
acter ’o’.
Task 8: Print numbers from 1 to 10, but stop the loop when the number is divisible by
8.
Task 9: Given a list ["apple", "", "banana", "", "cherry"], use continue to skip
empty strings and print only the words.
3
Answer Key
Important Disclaimer
Check these only after solving the tasks yourself!
Solutions 1 – 5
# Task 1
for i in range (1 , 10) :
if i == 6:
break
print ( i )
# Task 2
for i in range (1 , 11) :
g
if i == 4:
in
continue
print ( i ) rn
# Task 3
for i in range (1 , 11) :
if i % 3 == 0:
ea
continue
print ( i )
l
# Task 4
ys
continue
print ( i )
21
# Task 5
num = 5
if num > 0:
pass
Solutions 6 – 10
# Task 6
numbers = [2 , 4 , 6 , 8 , 10 , 7 , 12]
for num in numbers :
if num == 7:
break
print ( num )
# Task 7
text = " python ␣ programming "
for ch in text :
4
if ch == ’o ’:
continue
print ( ch )
# Task 8
for i in range (1 , 11) :
if i % 8 == 0:
break
print ( i )
# Task 9
words = [ " apple " , " " , " banana " , " " , " cherry " ]
# Task 10
g
student = { " name " : " Arjun " , " age " : 20 , " marks " : 85}
for key in student :
if key == " age " : in
rn
pass
else :
lea
5
Python Programming: Strings, Slicing and String
Methods
Introduction to Programming
January 2026
g
• Single quotes: ’Python’
in
• Double quotes: "Python"
rn
• Triple quotes: """Python"""
ea
Strings are immutable, meaning their values cannot be changed after creation.
language = " Python "
l
print ( language )
ys
String Indexing
da
• P
• h
• n
String Slicing
Slicing allows you to extract a portion of a string.
Syntax:
string [ start : end : step ]
1
Examples:
text = " Programming "
g
• gnimmargorP
in
rn
Most Used String Methods (Top 15)
lea
String methods are built-in functions that help us manipulate and analyze text easily.
Since strings are immutable, these methods always return a new string instead of changing
the original one.
ys
da
1. lower()
This method converts all uppercase characters in a string into lowercase. It is commonly
21
2. upper()
This method converts all lowercase characters into uppercase. It is often used for format-
ting output or highlighting text.
text = " python ␣ programming "
result = text . upper ()
print ( result )
Output:
• PYTHON PROGRAMMING
2
3. strip()
This method removes extra spaces from the beginning and end of a string. Very useful
when handling user input.
text = " ␣ ␣ ␣ Python ␣ ␣ ␣ "
result = text . strip ()
print ( result )
Output:
• Python
4. replace()
This method replaces a specific word or character with another one. It does not change
the original string.
g
text = " I ␣ like ␣ Java "
in
result = text . replace ( " Java " , " Python " )
print ( result )
Output:
rn
• I like Python
ea
5. split()
l
ys
print ( result )
Output:
21
6. join()
This method joins elements of a list into a single string using a separator.
words = [ " Python " , " is " , " easy " ]
result = " ␣ " . join ( words )
print ( result )
Output:
• Python is easy
3
7. find()
This method returns the index position of the first occurrence of a substring. If the
substring is not found, it returns -1.
text = " python ␣ programming "
result = text . find ( " programming " )
print ( result )
Output:
• 7
8. count()
This method counts how many times a character or word appears in a string.
text = " banana "
g
result = text . count ( " a " )
in
print ( result )
Output:
rn
• 3
ea
9. startswith()
l
This method checks whether a string starts with a specific value. It returns either True
ys
or False.
text = " Python "
result = text . startswith ( " Py " )
da
print ( result )
Output:
21
• True
10. endswith()
This method checks whether a string ends with a specific value.
text = " lesson . pdf "
result = text . endswith ( " . pdf " )
print ( result )
Output:
• True
4
11. capitalize()
This method converts the first character of a string to uppercase.
text = " python "
result = text . capitalize ()
print ( result )
Output:
• Python
12. title()
This method capitalizes the first letter of each word in a string.
text = " python ␣ programming ␣ language "
result = text . title ()
print ( result )
Output:
g
• Python Programming Language
in
rn
13. isdigit()
lea
Output:
• True
21
14. isalpha()
This method checks whether a string contains only alphabets.
text = " Python "
result = text . isalpha ()
print ( result )
Output:
• True
15. isalnum()
This method checks whether a string contains both alphabets and numbers.
text = " Python123 "
result = text . isalnum ()
print ( result )
5
Output:
• True
Practice Problems
Task 1: Reverse the string "Python" using slicing.
g
Task 8: Replace "old" with "new" in a string.
in
Task 9: Check if "[Link]" ends with ".txt".
rn
Task 10: Convert "hello world" to title case.
lea
ys
da
21
6
Answer Key
Important Disclaimer
Try solving the problems yourself before checking the answers!
# Task 1
result = " Python " [:: -1]
print ( result )
# Task 2
result = " programming " [3:7]
print ( result )
# Task 3
result = " WELCOME " . lower ()
print ( result )
g
# Task 4
result = " banana " . count ( " a " )
print ( result ) in
rn
# Task 5
result = " 10|20|30 " . split ( " | " )
lea
print ( result )
# Task 6
ys
result = " ␣ " . join ([ " Python " ," is " ," fun " ])
print ( result )
da
# Task 7
21
# Task 8
result = " old ␣ data " . replace ( " old " ," new " )
print ( result )
# Task 9
result = " file . txt " . endswith ( " . txt " )
print ( result )
# Task 10
result = " hello ␣ world " . title ()
print ( result )
7
Python Programming: Lists and List Methods
Introduction to Programming
January 2026
What is a List?
A list is a collection of multiple values stored in a single variable.
g
• Lists are ordered
in
• Lists are mutable (values can be changed)
rn
• Lists can store different data types
ea
numbers = [1 , 2 , 3 , 4 , 5]
print ( numbers )
l
ys
• 10
• 50
1
1. append()
Adds one element at the end of the list.
nums = [1 , 2 , 3]
nums . append (4)
print ( nums )
Output:
• [1, 2, 3, 4]
2. extend()
Adds multiple elements to the list.
nums = [1 , 2]
nums . extend ([3 , 4])
print ( nums )
g
Output:
• [1, 2, 3, 4]
in
rn
3. insert()
lea
nums = [1 , 2 , 4]
nums . insert (2 , 3)
print ( nums )
da
Output:
21
• [1, 2, 3, 4]
4. remove()
Removes a specific element from the list.
nums = [1 , 2 , 3 , 2]
nums . remove (2)
print ( nums )
Output:
• [1, 3, 2]
5. pop()
Removes and returns an element by index (default last).
2
nums = [10 , 20 , 30]
value = nums . pop ()
print ( value )
print ( nums )
Output:
• 30
• [10, 20]
6. clear()
Removes all elements from the list.
nums = [1 , 2 , 3]
nums . clear ()
print ( nums )
Output:
g
• []
in
rn
7. index()
lea
Output:
• 1
21
8. count()
Counts how many times a value appears.
nums = [1 , 2 , 2 , 3]
result = nums . count (2)
print ( result )
Output:
• 2
9. sort()
Sorts the list in ascending order.
nums = [4 , 1 , 3 , 2]
nums . sort ()
print ( nums )
3
Output:
• [1, 2, 3, 4]
10. reverse()
Reverses the order of the list.
nums = [1 , 2 , 3]
nums . reverse ()
print ( nums )
Output:
• [3, 2, 1]
11. copy()
g
in
Creates a copy of the list.
a = [1 , 2 , 3]
rn
b = a . copy ()
print ( b )
Output:
ea
• [1, 2, 3]
l
ys
12. len()
Returns the number of elements in a list.
da
print ( result )
Output:
• 3
13. max()
Returns the largest element.
nums = [5 , 9 , 2]
result = max ( nums )
print ( result )
Output:
• 9
4
14. min()
Returns the smallest element.
nums = [5 , 9 , 2]
result = min ( nums )
print ( result )
Output:
• 2
15. sum()
Returns the sum of elements.
nums = [1 , 2 , 3]
result = sum ( nums )
print ( result )
Output:
g
• 6
in
rn
Practice Problems
lea
Task 12: Using a for loop, calculate the sum of all elements in the list [5, 10, 15].
Task 13: Using a for loop, count how many even numbers are present in [1, 2, 3, 4,
5, 6].
5
Task 14: Using a for loop, create a new list that contains only numbers greater than 10
from [5, 12, 8, 20, 3].
Task 15: Using a for loop, find the largest number in the list [4, 9, 2, 7].
g
in
rn
lea
ys
da
21
6
Answer Key
Important Disclaimer
Try solving the problems yourself before checking the answers!
# Task 1
lst = [10 , 20 , 30]
lst . append (50)
print ( lst )
# Task 2
lst = [10 , 20 , 30]
lst . insert (1 , 25)
print ( lst )
# Task 3
g
lst = [10 , 20 , 30]
in
lst . remove (20)
print ( lst )
rn
# Task 4
lst = [5 , 5 , 2 , 5]
ea
result = lst . count (5)
print ( result )
l
# Task 5
ys
lst = [3 , 1 , 4 , 2]
lst . sort ()
print ( lst )
da
# Task 6
lst = [1 , 2 , 3]
21
lst . reverse ()
print ( lst )
# Task 7
lst = [10 , 20 , 30 , 40]
result = lst . index (40)
print ( result )
# Task 8
lst = [7 , 4 , 9]
result = max ( lst )
print ( result )
# Task 9
lst = [10 , 20 , 30]
result = sum ( lst )
print ( result )
7
# Task 10
lst = [1 , 2 , 3]
copy_list = lst . copy ()
print ( copy_list )
# Task 12
lst = [5 , 10 , 15]
total = 0
for num in lst :
total += num
g
print ( total )
# Task 13 in
rn
lst = [1 , 2 , 3 , 4 , 5 , 6]
count_even = 0
for num in lst :
lea
if num % 2 == 0:
count_even += 1
ys
print ( count_even )
# Task 14
da
lst = [5 , 12 , 8 , 20 , 3]
result = []
21
# Task 15
lst = [4 , 9 , 2 , 7]
largest = lst [0]
for num in lst :
if num > largest :
largest = num
print ( largest )
8
Python Programming: Tuples and Sets
Introduction to Programming
January 2026
What is a Tuple?
A tuple is a collection of values stored in a single variable, similar to a list.
g
• Tuples are ordered
in
• Tuples are immutable (cannot be changed)
rn
• Tuples allow duplicate values
ea
t = (5 , 10 , 15 , 20)
21
print ( t [0])
print ( t [ -1])
print ( t [1:3])
Output:
• 5
• 20
• (10, 15)
1
1. count()
Returns how many times a value appears in the tuple.
t = (1 , 2 , 2 , 3)
result = t . count (2)
print ( result )
Output:
• 2
2. index()
Returns the index of the first occurrence of a value.
t = (10 , 20 , 30)
result = t . index (20)
print ( result )
g
Output:
• 1
in
rn
Built-in Functions with Tuples
lea
t = (5 , 1 , 9)
ys
print ( len ( t ) )
print ( max ( t ) )
da
print ( min ( t ) )
print ( sum ( t ) )
21
Output:
• 3
• 9
• 1
• 15
What is a Set?
A set is a collection of unique values.
2
• Sets are mutable
nums = {1 , 2 , 3 , 3}
print ( nums )
Output:
• {1, 2, 3}
g
Output:
• {1, 2, 3} in
rn
2. update()
lea
s = {1 , 2}
s . update ([3 , 4])
da
print ( s )
Output:
21
• {1, 2, 3, 4}
3. remove()
Removes a specific element (error if not found).
s = {1 , 2 , 3}
s . remove (2)
print ( s )
Output:
• {1, 3}
3
4. discard()
Removes an element without error if not found.
s = {1 , 2 , 3}
s . discard (5)
print ( s )
Output:
• {1, 2, 3}
5. pop()
Removes and returns a random element.
s = {10 , 20 , 30}
value = s . pop ()
print ( value )
print ( s )
g
Output:
• 10 in
rn
• {20, 30}
lea
6. clear()
ys
s . clear ()
print ( s )
21
Output:
• set()
Set Operations
a = {1 , 2 , 3}
b = {3 , 4 , 5}
print ( a . union ( b ) )
print ( a . intersection ( b ) )
print ( a . difference ( b ) )
Output:
• {1, 2, 3, 4, 5}
• {3}
• {1, 2}
4
Practice Problems
Task 1: Create a tuple and print its length.
g
in
rn
lea
ys
da
21
5
Answer Key
Important Disclaimer
Try solving the problems yourself before checking the answers!
# Task 1
t = (1 , 2 , 3)
result = len ( t )
print ( result )
# Task 2
t = (1 , 3 , 5 , 7)
result = t . index (5)
print ( result )
# Task 3
t = (2 , 2 , 3 , 4)
g
result = t . count (2)
print ( result )
# Task 4
in
rn
s = {1 , 2}
s . add (10)
lea
print ( s )
# Task 5
ys
s = {1 , 2 , 3}
s . remove (3)
da
print ( s )
21
# Task 6
a = {1 , 2}
b = {2 , 3}
result = a . union ( b )
print ( result )
# Task 7
result = a . intersection ( b )
print ( result )
6
Python Programming: Dictionaries
Introduction to Programming
January 2026
What is a Dictionary?
A dictionary is a collection of data stored in key : value pairs.
• Dictionaries are written using curly braces {}
• Each value is accessed using a unique key
• Dictionaries are unordered
g
• Dictionaries are mutable
in
rn
student = { " name " : " Arjun " , " age " : 20 , " marks " : 85}
print ( student )
lea
Output:
• {’name’: ’Arjun’, ’age’: 20, ’marks’: 85}
ys
student = { " name " : " Arjun " , " age " : 20 , " marks " : 85}
21
print ( student )
Output:
• {’name’: ’Arjun’, ’age’: 21, ’marks’: 90}
1
Removing Dictionary Items
student = { " name " : " Arjun " , " age " : 20 , " marks " : 85}
print ( student )
Output:
• {’name’: ’Arjun’}
g
student = { " name " : " Arjun " , " age " : 20}
result1 = student . get ( " marks " )
result2 = student . get ( " age " ) in
rn
print ( result1 )
print ( result2 )
lea
Output:
• None
ys
• 20
da
2. keys()
21
3. values()
Returns all values in the dictionary.
student = { " name " : " Arjun " , " age " : 20}
result = student . values ()
print ( result )
Output:
• dict values([’Arjun’, 20])
2
4. items()
Returns key-value pairs as tuples.
student = { " name " : " Arjun " , " age " : 20}
result = student . items ()
print ( result )
Output:
5. update()
Updates dictionary with another dictionary.
student = { " name " : " Arjun " }
student . update ({ " age " : 20 , " marks " : 85})
print ( student )
g
Output:
student = { " name " : " Arjun " , " age " : 20}
result = student . pop ( " age " )
print ( result )
da
print ( student )
Output:
21
• 20
• {’name’: ’Arjun’}
7. popitem()
Removes and returns the last inserted key-value pair.
student = { " name " : " Arjun " , " age " : 20}
result = student . popitem ()
print ( result )
print ( student )
Output:
• (’age’, 20)
• {’name’: ’Arjun’}
3
8. clear()
Removes all items from the dictionary.
student = { " name " : " Arjun " }
student . clear ()
print ( student )
Output:
• {}
9. copy()
Creates a copy of the dictionary.
student = { " name " : " Arjun " }
new_student = student . copy ()
g
print ( new_student )
in
Output:
• {’name’: ’Arjun’}
rn
10. setdefault()
ea
Returns value of a key. If key does not exist, inserts it with a default value.
l
Output:
21
• 20
11. len()
Returns number of key-value pairs.
student = { " name " : " Arjun " , " age " : 20}
result = len ( student )
print ( result )
Output:
• 2
4
12. Looping Through Dictionary
student = { " name " : " Arjun " , " age " : 20}
• name Arjun
• age 20
Practice Problems
Task 1: Create a dictionary with keys "name" and "age".
Task 2: Access and print the value of "name" from the dictionary.
g
Task 3: Add a new key "marks" with value 85.
Task 12: Using the same dictionary, find and print the subject with the highest marks.
Task 13: Given a dictionary {"a": 1, "b": 2, "c": 3}, create a new dictionary
where the values are squared.
Task 14: Given a dictionary {"apple": 3, "banana": 0, "orange": 5}, remove all
keys whose value is 0.
Task 15: Given a list ["pen", "book", "pen", "pencil", "book"], create a dictionary
that counts the frequency of each word.
5
Answer Key
Important Disclaimer
Try solving the problems yourself before checking the answers!
# Task 1
student = { " name " : " Arjun " , " age " : 20}
print ( student )
# Task 2
result = student [ " name " ]
print ( result )
# Task 3
student [ " marks " ] = 85
print ( student )
g
in
# Task 4
student [ " age " ] = 21
print ( student )
rn
# Task 5
ea
student . pop ( " marks " )
print ( student )
l
# Task 6
ys
# Task 7
values = student . values ()
print ( values )
21
# Task 8
for key , value in student . items () :
print ( key , " : " , value )
# Task 9
result = " age " in student
print ( result )
# Task 10
student_copy = student . copy ()
print ( student_copy )
6
marks = { " math " : 80 , " science " : 75 , " english " : 90}
total = 0
for value in marks . values () :
total += value
print ( total )
# Task 12
marks = { " math " : 80 , " science " : 75 , " english " : 90}
highest_subject = " "
highest_marks = 0
for subject , value in marks . items () :
if value > highest_marks :
highest_marks = value
highest_subject = subject
print ( highest_subject , highest_marks )
# Task 13
data = { " a " : 1 , " b " : 2 , " c " : 3}
squared_dict = {}
g
for key , value in data . items () :
squared_dict [ key ] = value * value
print ( squared_dict ) in
rn
# Task 14
lea
fruits = { " apple " : 3 , " banana " : 0 , " orange " : 5}
result = {}
for key , value in fruits . items () :
ys
if value != 0:
result [ key ] = value
da
print ( result )
# Task 15
21
items = [ " pen " , " book " , " pen " , " pencil " , " book " ]
frequency = {}
for item in items :
if item in frequency :
frequency [ item ] += 1
else :
frequency [ item ] = 1
print ( frequency )
7
Python Programming: Functions
Introduction to Programming
January 2026
What is a Function?
A function is a block of reusable code that performs a specific task.
g
• Functions execute only when they are called
in
rn
def greet () :
print ( " Hello , ␣ Welcome ␣ to ␣ Python " )
lea
greet ()
Output:
ys
Function Syntax
def function_name ( arguments ) :
# function body
return value
1
Function Without Arguments
def say_hello () :
print ( " Hello " )
say_hello ()
Output:
• Hello
g
greet ( " Arjun " )
in
Output:
• Hello Arjun
rn
Function With Multiple Arguments
ea
def add (a , b ) :
l
result = a + b
ys
print ( result )
Output:
• 30
21
Return Statement
The return statement sends a value back to the caller.
def multiply (a , b ) :
result = a * b
return result
output = multiply (5 , 4)
print ( output )
Output:
• 20
2
Function With Default Arguments
def greet ( name = " Student " ) :
print ( " Hello " , name )
greet ()
greet ( " Python " )
Output:
• Hello Student
• Hello Python
Keyword Arguments
g
def student_info ( name , age ) :
print ( name , age )
in
student_info ( age =20 , name = " Arjun " )
rn
Output:
• Arjun 20
ea
def calculate (a , b ) :
return a +b , a - b
da
print ( result2 )
Output:
• 15
• 5
Built-in Functions
Python provides many built-in functions.
• len()
• sum()
• max()
• min()
3
• type()
nums = [1 , 2 , 3]
print ( len ( nums ) )
print ( sum ( nums ) )
Practice Problems
Task 1: Write a function that prints ”Hello World”.
Task 2: Write a function that takes one number and prints its square.
Task 3: Write a function that takes two numbers and returns their sum.
Task 5: Write a function that returns both sum and difference of two numbers.
g
Extra Practice Problems
in
rn
Task 6: Write a function that takes a number and returns whether it is even or odd.
Task 7: Write a function that takes a list of numbers and returns the largest number.
lea
Task 8: Write a function that takes a string and returns the count of vowels in it.
ys
Task 9: Write a function that takes a number and returns it factorial (factorial of first
number + factorial of second number).
da
Task 10: Write a function that takes a list and returns a new list containing only unique
elements.
21
4
Answer Key
Important Disclaimer
Try solving the problems yourself before checking the answers!
# Task 1
def hello () :
print ( " Hello ␣ World " )
hello ()
# Task 2
def square ( num ) :
result = num * num
print ( result )
g
square (5)
in
# Task 3
def add (a , b ) :
rn
return a + b
ea
result = add (10 , 20)
print ( result )
l
# Task 4
ys
greet ()
# Task 5
21
def calculate (a , b ) :
sum_result = a + b
diff_result = a - b
return sum_result , diff_result
x , y = calculate (10 , 5)
print (x , y )
5
result = even_or_odd (7)
print ( result )
# Task 7
def find_largest ( numbers ) :
largest = numbers [0]
for num in numbers :
if num > largest :
largest = num
return largest
# Task 8
def count_vowels ( text ) :
vowels = " aeiouAEIOU "
count = 0
g
for ch in text :
if ch in vowels :
count += 1 in
rn
return count
lea
# Task 9
def factorial ( n ) :
da
fact = 1
for i in range (1 , n + 1) :
fact *= i
21
return fact
# Task 10
def unique_elements ( lst ) :
result = []
for item in lst :
if item not in result :
result . append ( item )
return result
6
Python Programming: Try and Except
Introduction to Programming
January 2026
g
• It handles unexpected errors
• Division by zero
da
• Invalid input
1
Example With Try and Except
try :
a = 10
b = 0
print ( a / b )
except :
print ( " Error : ␣ Division ␣ by ␣ zero " )
Output:
• Error: Division by zero
g
Output:
• Invalid conversion in
rn
Multiple Except Blocks
lea
try :
ys
print ( a / b )
except Ze roDivi sionEr ror :
print ( " Cannot ␣ divide ␣ by ␣ zero " )
21
except ValueError :
print ( " Invalid ␣ input " )
Else Block
The else block runs if no exception occurs.
try :
a = 10
b = 2
print ( a / b )
except Ze roDivi sionEr ror :
print ( " Division ␣ by ␣ zero " )
else :
print ( " Division ␣ successful " )
Output:
• 5.0
• Division successful
2
Finally Block
The finally block always executes whether an exception occurs or not.
try :
print (10 / 0)
except Ze roDivi sionEr ror :
print ( " Error ␣ occurred " )
finally :
print ( " Program ␣ completed " )
Output:
• Error occurred
• Program completed
g
• Handles unexpected user inputs
in
rn
• Makes code more robust
lea
Practice Problems
ys
Task 1: Write a program to handle division by zero using try and except.
Task 7: Write a program to open a file and handle file not found error.
Task 8: Write a program to convert user input into integer using exception handling.
Task 9: Write a program that repeatedly asks input until valid number is entered.
Task 10: Write a program to handle multiple exceptions in a single except block.
3
Answer Key
Important Disclaimer
Try solving the problems yourself before checking the answers!
# Task 1
try :
print (10 / 0)
except Ze roDivi sionEr ror :
print ( " Cannot ␣ divide ␣ by ␣ zero " )
# Task 2
try :
num = int ( " abc " )
except ValueError :
print ( " Invalid ␣ input " )
g
in
# Task 3
try :
print (10 / 2)
rn
except Ze roDivi sionEr ror :
print ( " Error " )
ea
else :
print ( " No ␣ error ␣ occurred " )
l
# Task 4
ys
try :
print (10 / 0)
except Ze roDivi sionEr ror :
da
# Task 5
try :
a = int ( " abc " )
b = 10 / 0
except ( ValueError , Ze roDivi sionEr ror ) :
print ( " Handled ␣ multiple ␣ errors " )
4
# Task 7
try :
file = open ( " data . txt " )
except Fi leNotF oundEr ror :
print ( " File ␣ not ␣ found " )
# Task 8
try :
num = int ( input ( " Enter ␣ a ␣ number : ␣ " ) )
print ( num )
except ValueError :
print ( " Please ␣ enter ␣ a ␣ valid ␣ number " )
# Task 9
while True :
try :
num = int ( input ( " Enter ␣ a ␣ number : ␣ " ) )
break
g
except ValueError :
in
print ( " Invalid ␣ input , ␣ try ␣ again " )
rn
print ( " You ␣ entered : " , num )
lea
# Task 10
try :
x = int ( " abc " )
ys
y = 10 / 0
except ( ValueError , Ze roDivi sionEr ror ) :
da
5
Python Programming: File Handling
Introduction to Programming
January 2026
g
• Files help in data management
in
rn
Types of Files
lea
File Modes
Different modes are used while opening a file.
21
Opening a File
file = open ( " data . txt " , " r " )
1
What Happens If a File Does Not Exist?
When we try to open a file that does not exist, Python behaves differently based on the
file mode.
• FileNotFoundError occurs
Reading a File
g
file = open ( " data . txt " , " r " )
content = file . read ()
print ( content )
in
rn
file . close ()
lea
2
Using with Statement
The with statement automatically closes the file.
with open ( " data . txt " , " r " ) as file :
content = file . read ()
print ( content )
g
• To avoid data loss
in
rn
• To prevent file corruption
lea
Practice Problems
ys
Task 1: Write a program to create a file and write some text into it.
3
Answer Key
Important Disclaimer
Try solving the problems yourself before checking the answers!
# Task 1
file = open ( " sample . txt " , " w " )
file . write ( " Hello ␣ File ␣ Handling " )
file . close ()
# Task 2
file = open ( " sample . txt " , " r " )
print ( file . read () )
file . close ()
# Task 3
g
file = open ( " sample . txt " , " a " )
in
file . write ( " \ nPython ␣ Programming " )
file . close ()
rn
# Task 4
with open ( " sample . txt " , " r " ) as file :
ea
print ( file . read () )
# Task 5
l
# Task 6
with open ( " sample . txt " , " r " ) as file :
words = file . read () . split ()
print ( len ( words ) )
# Task 7
with open ( " sample . txt " , " r " ) as file :
content = file . read ()
if " Python " in content :
print ( " Word ␣ found " )
else :
print ( " Word ␣ not ␣ found " )
# Task 8
with open ( " sample . txt " , " r " ) as src :
with open ( " copy . txt " , " w " ) as dest :
dest . write ( src . read () )
4
# Task 9
with open ( " sample . txt " , " r " ) as file :
for i in range (5) :
print ( file . readline () )
# Task 10
lines = [ " Line ␣ 1\ n " , " Line ␣ 2\ n " , " Line ␣ 3\ n " ]
with open ( " multiple . txt " , " w " ) as file :
file . writelines ( lines )
g
in
rn
lea
ys
da
21
5
Python Programming: Simplified Classes and Objects
A Beginner’s Guide for Students
1
4 Practice Questions
DISCLAIMER
Please try to solve these questions yourself first! Do not look at the answers on the
next page until you have tried writing the code.
2. Description Method: Add a method to the Book class that prints: ”This book
is [Title] by [Author]”.
3. Rectangle Area: Create a class Rectangle with length and width. Add a
method to calculate the area.
4. Dog Age: Create a Dog class. Add a method that takes the dog’s age and returns
it in ”Human Years” (Age × 7).
5. Car Speed: Create a Car class with a speed of 0. Add a method accelerate()
that increases speed by 10.
2
5 Answers (For Reference Only)
# 1 & 2: Book Class
class Book :
def __init__ ( self , title , author ) :
self . title = title
self . author = author
# 3: Rectangle
class Rectangle :
def __init__ ( self , length , width ) :
self . length = length
self . width = width
def get_area ( self ) :
return self . length * self . width
# 4: Dog Age
class Dog :
def __init__ ( self , age ) :
self . age = age
def human_years ( self ) :
return self . age * 7
# 5: Car Acceleration
class Car :
def __init__ ( self ) :
self . speed = 0
def accelerate ( self ) :
self . speed += 10
print ( f " Current speed : { self . speed } " )
3
Top 40+ Beginner-Friendly Python Interview
Questions
With Clear Explanations and Solutions
Introduction
This document contains the top 40+ Python coding interview questions designed for beginners.
Each problem includes a clear explanation and simple Python code without advanced techniques.
—
1 Reverse a String
Problem: Reverse a given string.
Explanation: We start with an empty string. We take each character from the original
string and place it in front of the new string. This reverses the order step by step.
text = " python "
reversed_text = " "
print ( reversed_text )
if word == reversed_word :
print ( " Palindrome " )
else :
print ( " Not ␣ Palindrome " )
1
—
print ( largest )
print ( unique )
print ( count )
2
—
6 Check Anagram
Explanation: Two strings are anagrams if each character appears the same number of times
in both strings.
a = " listen "
b = " silent "
is_anagram = True
for char in a :
if a . count ( char ) != b . count ( char ) :
is_anagram = False
print ( is_anagram )
7 Fibonacci Series
Explanation: Each number is the sum of the previous two numbers.
n = 5
a = 0
b = 1
for i in range ( n ) :
print ( a )
c = a + b
a = b
b = c
for i in range (1 , n + 1) :
total += i
3
print ( total )
if num < 2:
is_prime = False
print ( is_prime )
10 Factorial of a Number
Explanation: Multiply numbers from 1 up to the given number.
num = 5
fact = 1
print ( fact )
11 Reverse a List
Explanation: Insert each element at the beginning of a new list.
numbers = [1 , 2 , 3]
reversed_list = []
print ( reversed_list )
4
12 Second Largest Number
Explanation: Track the largest and second largest values while looping.
numbers = [10 , 40 , 30 , 20]
largest = second = numbers [0]
print ( second )
print ( sorted_list )
for num in a :
if num in b :
common . append ( num )
print ( common )
5
15 Swap Two Numbers
Explanation: Use a temporary variable to swap values.
a = 5
b = 10
temp = a
a = b
b = temp
print (a , b )
while b != 0:
temp = b
b = a % b
a = temp
print ( a )
18 Flatten a List
Explanation: If the item is a list, add its elements individually.
nested = [1 , [2 , 3] , 4]
flat = []
6
if type ( item ) == list :
for i in item :
flat . append ( i )
else :
flat . append ( item )
print ( flat )
20 Armstrong Number
Explanation: Each digit is raised to the power of total digits and summed.
num = 153
total = 0
digits = str ( num )
for d in digits :
total += int ( d ) ** len ( digits )
if total == num :
print ( " Armstrong " )
else :
print ( " Not ␣ Armstrong " )
7
file . close ()
print ( total )
8
even += 1
else :
odd += 1
if num % 2 == 0:
print ( " Even " )
else :
print ( " Odd " )
print ( count )
9
if num == target :
found = True
print ( found )
print ( smallest )
print ( count )
10
—
31 Reverse a Number
Problem: Reverse the digits of a number.
Explanation: We repeatedly take the last digit and build the reversed number.
num = 1234
reverse = 0
print ( reverse )
for i in range (1 , n + 1) :
print ( i )
11
34 Sum of Digits of a Number
Problem: Find the sum of digits of a number.
Explanation: We extract the last digit using remainder. Add it to the total and remove
the last digit.
num = 123
total = 0
print ( total )
12
print ( is_digit )
print ( fahrenheit )
print ( index )
13
print ( result )
if total == num :
print ( " Perfect ␣ Number " )
else :
print ( " Not ␣ Perfect " )
print ( result )
14
base = 2
exponent = 3
result = 1
print ( result )
Final Note
These questions are basic Python coding problems designed to help beginners get familiar
with Python fundamentals such as loops, conditions, lists, strings, and simple logic.
They are not meant to be advanced or highly optimized. Once you are comfortable with
these basics, you are encouraged to:
• ”If you notice any errors due to my oversight, please let me know so I can correct them.”
For more questions and optimized code solutions, you can search on Google and practice
from different platforms.
– Your Babai
—
15