0% found this document useful (0 votes)
3 views97 pages

Final Python Questions

The document provides an overview of Python programming concepts, focusing on comments, variables, data types, and typecasting. It explains the purpose and methods of using comments, the rules for naming variables, and introduces various data types such as integers, floats, strings, and lists. Additionally, it covers typecasting with examples of implicit and explicit conversions, along with practice problems and solutions for hands-on learning.

Uploaded by

srujajolle
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)
3 views97 pages

Final Python Questions

The document provides an overview of Python programming concepts, focusing on comments, variables, data types, and typecasting. It explains the purpose and methods of using comments, the rules for naming variables, and introduces various data types such as integers, floats, strings, and lists. Additionally, it covers typecasting with examples of implicit and explicit conversions, along with practice problems and solutions for hands-on learning.

Uploaded by

srujajolle
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

Python Programming: Mastering Comments

Introduction to Programming
2026

1 What are Comments?


In Python, a comment is a piece of text that the computer completely ignores when
running your program. They are written for humans to read. To write a basic comment,
we use the hash symbol (#). Everything after the # on that specific line is treated as a
comment.

2 Why Do We Use Comments?


1. To understand code written previously: When you revisit code after weeks
or months, comments serve as a ”note to self” to remember your logic.

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. While working with teams: In professional software development, comments


help your teammates understand your thought process so they can collaborate ef-
fectively.

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 1: Using multiple hash symbols


# This is a comment that
# spans across several lines .

’’’
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

1 What are Variables?


In Python, a variable is like a container or a box where you store data. Once you put
something in the box, you can give it a name so you can find and use it later. You create
a variable by giving it a name and assigning a value using the = sign.

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

3 Rules for Naming Variables


21

• Names must start with a letter or an underscore ( ).

• They cannot start with a number.

• Names are case-sensitive (age is not the same as Age).

• Spaces are not allowed; use snake case (e.g., my variable).

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

# Wrong : total - score ( Hyphens are not allowed )


da

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

What is a Data Type?


Just like we store different things in different boxes (milk in a bottle, toys in a crate),
Python uses different ”types” to store data. This tells Python what we can do with that
data. For example, you can perform math on numbers, but you cannot do math on a
person’s name!

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

Values: Positive/negative whole numbers and zero (e.g., 5, -100, 0).


Syntax: variable name = whole number
da

Example: student count = 35


21

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

Values: Items separated by commas inside parentheses ( ).


Syntax: tuple name = (item1, item2)
ys

Example: coordinates = (10.5, 20.3)


da

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 3: Create a Boolean variable called is daylight and set it to False.

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

num_sum = num_int + num_float

print ( num_sum ) # Output : 15.5


print ( type ( num_sum ) ) # Output : < class ’ float ’>

2. Explicit Type Conversion


This is where you (the programmer) do the work. You manually change the type
using built-in functions like int(), float(), or str(). This is useful when you need to
force a specific data type for your logic.

Common Casting Functions


• int(): Changes a value to a whole number.

• float(): Changes a value to a decimal number.

1
• str(): Changes a value into text.

• bool(): Changes a value to True or False.

# 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

str() to combine them.

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

Extra Practice Problems


Task 6: Take a string "15.7". Convert it to a float first, then to an int.

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

What are Operators?


Operators are special symbols or keywords that perform operations on variables and
values. They are the ”tools” we use to manipulate and compare data in our programs.

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

• Multiplication (*): Multiplies two values. Ex: 5 * 2 is 10.


ys

• Division (/): Divides one value by another, resulting in a float. Ex: 5 / 2 is


2.5.
da

• Modulus (%): Returns the remainder of a division. Ex: 5 % 2 is 1.


21

• Exponentiation (**): Raises one number to the power of another. Ex: 5 ** 2


is 25.

• 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.

• Equal to (==): True if values are the same. Ex: 5 == 5 is True.

• Not equal (!=): True if values are different. Ex: 5 != 3 is True.

• 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.

• and: True if both statements are True.

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

print ( x > 15 or y < 10) # True ( one condition is True )

# 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.

• is: Returns True if both variables point to the same object.

• is not: Returns True if they point to different objects.

Example:

2
a = [1 , 2 , 3]
b = a
c = [1 , 2 , 3]

print ( a is b ) # True ( same memory object )


print ( a is c ) # False ( different objects )
print ( a is not c ) # True
Note: Use identity operators when you care about memory reference, not value.

6. Membership Operators
Membership operators check whether a value exists inside a sequence such as a list, tuple,
string, or set.

• in: Returns True if the value exists.

• not in: Returns True if the value does not exist.

g
Examples:
numbers = [1 , 2 , 3 , 4] in
rn
print (3 in numbers ) # True
print (5 not in numbers ) # True
lea

word = " Python "


ys

print ( " P " in word ) # True


print ( " z " in word ) # False
da

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).

• Decimal 5 = Binary 101

• Decimal 3 = Binary 011

Bitwise Operators
• AND (&): Bit is 1 only if both bits are 1.

• OR (|): Bit is 1 if at least one bit is 1.

• XOR (ˆ): Bit is 1 if bits are different.

3
• NOT (˜): Inverts all bits.

• Left Shift (<<): Shifts bits left (multiplies by 2).

• Right Shift (>>): Shifts bits right (divides by 2).

Examples
a = 5 # Binary : 101
b = 3 # Binary : 011

print ( a & b ) # AND -> 1 (001)


print ( a | b ) # OR -> 7 (111)
print ( a ^ b ) # XOR -> 6 (110)
print (~ a ) # NOT -> -6
print ( a << 1) # Left shift -> 10 (1010)
print ( a >> 1) # Right shift -> 2 (010)

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++"].

Task 5: Divide 17 by 3 using Floor Division (//). What is the result?

Extra Practice Problems


Task 6: Use the exponent operator to find 34 .

Task 7: Swap a = 5 and b = 10.

Task 8: Use ’is not’ to compare an integer 10 and a float 10.0.

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

Check these only after solving the tasks yourself!


da

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

print (2 & 3) # Output : 2


ys
da
21

6
Python Programming: Conditional Statements
Introduction to Programming
January 2026

What are Conditional Statements?


Conditional statements allow a program to make decisions. Python checks conditions
one by one and executes code blocks based on whether the condition evaluates to True
or False.

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

• Python evaluates the condition inside the if

• If the condition is True, the indented block runs


ys

• If the condition is False, nothing happens


da

Syntax:
21

if condition :
# code runs only if condition is True
Example:
age = 20

if age >= 18:


print ( " You ␣ are ␣ eligible ␣ to ␣ vote " )
Note: There is no output if the condition is False because no alternative block is
provided.

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

• If True → if block executes

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

• If False, it checks the next elif

• This continues until a condition is True


ys

• Once a condition is True, its block executes and the rest are skipped
da

• If no condition is True, the else block executes (if present)


21

Syntax:
if condition1 :
# code
elif condition2 :
# code
elif condition3 :
# code
else :
# code ( optional )
Example:
marks = 75

if marks >= 90:


print ( " Grade ␣ A " )
elif marks >= 60:
print ( " Grade ␣ B " )
else :
print ( " Grade ␣ C " )

2
Important Notes:

• Conditions are checked from top to bottom

• Only the first True condition executes

• The else block is optional

Practice Problems
Task 1: If a number is positive, print "Positive", otherwise print "Not Positive".

Task 2: If a number is even, print "Even", else print "Odd".

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".

Extra Practice Problems in


rn
Task 6: If a number is divisible by both 3 and 5, print "Divisible", else print "Not
lea

divisible".

Task 7: Compare two numbers and print the greater one.


ys

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

print ( " Eligible ␣ to ␣ vote " )


else :
ys

print ( " Not ␣ eligible " )


da

# Task 4
num = 85
if num > 100:
21

print ( " Greater ␣ than ␣ 100 " )


else :
print ( " 100 ␣ or ␣ less " )

# 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

if age < 12:


print (50)
elif age < 60:
21

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

iteration, Python checks the condition.


Execution Flow:
da

• Python checks the condition

• If the condition is True, the loop body executes


21

• After execution, the condition is checked again

• This continues until the condition becomes False

• When the condition is False, the loop stops

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

• Moves to the next value in the sequence


ys

• Repeats until the sequence ends


da

Syntax:
for variable in sequence :
21

# code to repeat
Example: Loop through a list
fruits = [ " apple " , " banana " , " cherry " ]

for fruit in fruits :


print ( fruit )
Explanation:
• First iteration: fruit = "apple"
• Second iteration: fruit = "banana"
• Third iteration: fruit = "cherry"
• Loop stops after last item

3. range() Function
The range() function is used with for loops to generate a sequence of numbers.

2
range(end)
• Starts from 0

• Ends before the given number

for i in range (5) :


print ( i )
Output:

• 1, 2, 3, 4, 5

range(start, end, step)


Explanation:

• start: Number from where the sequence begins

• end: Number where the sequence stops (not included)

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

• Starts from start

• Adds step each time


ys

• Stops before reaching end


da

Example: Print numbers from 1 to 10 with step 2


for i in range (1 , 11 , 2) :
21

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 2: Use a while loop to print even numbers from 2 to 10.

Task 3: Use a for loop to print each character in the string "Python".

Task 4: Use a for loop and range() to print numbers from 1 to 5.

Task 5: Use a for loop to calculate and print the sum of numbers from 1 to 5.

Extra Practice Problems


Task 6: Print the multiplication table of 5 using a while loop.

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

What are break, continue and pass?


break, continue, and pass are loop control statements. They change the normal
flow of loops based on certain conditions.
These statements are mainly used inside:
• while loops

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

• Python enters the loop


• When break is encountered, the loop stops immediately
da

• Control moves outside the loop


21

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:

• Python checks the condition

• If continue is executed, remaining code in that iteration is skipped

• Loop continues with the next iteration

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:

• When i == 5, print statement is skipped


da

• Loop continues with next value


21

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:

• Python encounters pass

• Nothing happens

• Execution continues normally

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:

• pass does not skip or stop the loop

• It is useful when writing empty blocks temporarily

Practice Problems
Task 1: Print numbers from 1 to 10 but stop when number reaches 6.

Task 2: Print 1 to 10 using a loop. Use continue to skip printing number 4.

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 5: Use pass inside an if condition.


lea

Extra Practice Problems


ys

Task 6: Given a list of numbers [2, 4, 6, 8, 10, 7, 12], use a loop and break to
da

stop printing when number 7 is found.


21

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.

Task 10: Given a dictionary


student = {"name": "Arjun", "age": 20, "marks": 85},
use a loop and pass when the key is "age".

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

for i in range (1 , 11) :


if i % 2 == 0:
da

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 " ]

for word in words :


if word == " " :
continue
print ( word )

# Task 10

g
student = { " name " : " Arjun " , " age " : 20 , " marks " : 85}
for key in student :
if key == " age " : in
rn
pass
else :
lea

print ( key , " : " , student [ key ])


ys
da
21

5
Python Programming: Strings, Slicing and String
Methods
Introduction to Programming
January 2026

What are Strings?


A string is a sequence of characters enclosed in quotes.

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

Each character in a string has an index number.


21

text = " Python "


print ( text [0])
print ( text [3])
print ( text [ -1])
Output:

• P

• h

• n

String Slicing
Slicing allows you to extract a portion of a string.
Syntax:
string [ start : end : step ]

1
Examples:
text = " Programming "

print ( text [0:6]) # Characters from index 0 to 5


print ( text [3:8]) # From index 3 to 7
print ( text [:5]) # From start
print ( text [5:]) # Till end
print ( text [::2]) # Skip characters
print ( text [:: -1]) # Reverse string
Output:
• Progra
• gramm
• Progr
• amming
• Pormig

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

used while comparing user input or normalizing text data.


text = " HELLO ␣ WORLD "
result = text . lower ()
print ( result )
Output:
• hello world

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

This method splits a string into a list based on a delimiter.


text = " apple , banana , orange "
result = text . split ( " ," )
da

print ( result )
Output:
21

• [’apple’, ’banana’, ’orange’]

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

This method checks whether a string contains only numeric digits.


text = " 12345 "
ys

result = text . isdigit ()


print ( result )
da

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.

Task 2: Extract "gram" from "programming".

Task 3: Convert "WELCOME" to lowercase.

Task 4: Count number of "a" in "banana".

Task 5: Split "10|20|30" using |.

Task 6: Join ["Python","is","fun"] with spaces.

Task 7: Check if "123abc" is alphanumeric.

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

result = " 123 abc " . isalnum ()


print ( result )

# 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.

• Lists are written using square brackets []

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

List Indexing and Slicing


da

data = [10 , 20 , 30 , 40 , 50]


21

print ( data [0])


print ( data [ -1])
print ( data [1:4])
Output:

• 10

• 50

• [20, 30, 40]

Most Used List Methods (Top 15)


List methods are built-in functions that help us add, remove, update, and analyze list
elements easily.

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

Inserts an element at a specific index.


ys

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

Returns the index of the first occurrence of a value.


nums = [5 , 10 , 15]
ys

pos = nums . index (10)


print ( pos )
da

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

nums = [10 , 20 , 30]


result = len ( nums )
21

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 1: Add number 50 to the list [10, 20, 30].


ys

Task 2: Insert number 25 at index 1 in [10, 20, 30].

Task 3: Remove number 20 from the list.


da

Task 4: Count how many times 5 appears in [5,5,2,5].


21

Task 5: Sort the list [3,1,4,2].

Task 6: Reverse the list [1,2,3].

Task 7: Find the index of 40 in [10,20,30,40].

Task 8: Find the maximum value in [7,4,9].

Task 9: Find the sum of [10,20,30].

Task 10: Create a copy of a list.

Additional Practice Problems (Using for Loop)


Task 11: Using a for loop, print each element in the list [10, 20, 30, 40].

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 )

Solutions for Additional Practice Problems


# Task 11
lst = [10 , 20 , 30 , 40]
for item in lst :
print ( item )

# 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

for num in lst :


if num > 10:
result . append ( num )
print ( result )

# 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.

• Tuples are written using parentheses ()

g
• Tuples are ordered

in
• Tuples are immutable (cannot be changed)
rn
• Tuples allow duplicate values
ea

data = (10 , 20 , 30)


print ( data )
l
ys

Tuple Indexing and Slicing


da

t = (5 , 10 , 15 , 20)
21

print ( t [0])
print ( t [ -1])
print ( t [1:3])
Output:

• 5

• 20

• (10, 15)

Important Tuple Methods


Tuples have very few methods because they are immutable.

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.

• Sets are written using curly braces {}

• Sets are unordered

• Sets do not allow duplicates

2
• Sets are mutable

nums = {1 , 2 , 3 , 3}
print ( nums )
Output:

• {1, 2, 3}

Most Used Set Methods


1. add()
Adds one element to the set.
s = {1 , 2}
s . add (3)
print ( s )

g
Output:

• {1, 2, 3} in
rn
2. update()
lea

Adds multiple elements to the set.


ys

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

Removes all elements from the set.


s = {1 , 2 , 3}
da

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.

Task 2: Find the index of value 5 in (1, 3, 5, 7).

Task 3: Count how many times 2 appears in (2,2,3,4).

Task 4: Add value 10 to a set.

Task 5: Remove value 3 from a set.

Task 6: Find union of {1,2} and {2,3}.

Task 7: Find intersection of two sets.

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

Accessing Dictionary Values


da

student = { " name " : " Arjun " , " age " : 20 , " marks " : 85}
21

print ( student [ " name " ])


print ( student [ " age " ])
Output:
• Arjun
• 20

Adding and Updating Values


student = { " name " : " Arjun " , " age " : 20}

student [ " marks " ] = 90


student [ " age " ] = 21

print ( student )
Output:
• {’name’: ’Arjun’, ’age’: 21, ’marks’: 90}

1
Removing Dictionary Items
student = { " name " : " Arjun " , " age " : 20 , " marks " : 85}

student . pop ( " age " )


del student [ " marks " ]

print ( student )
Output:
• {’name’: ’Arjun’}

Most Used Dictionary Methods (Top 12)


1. get()
Returns the value of a key. If the key does not exist, it returns None instead of error.

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

Returns all keys in the dictionary.


student = { " name " : " Arjun " , " age " : 20}
result = student . keys ()
print ( result )
Output:
• dict keys([’name’, ’age’])

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:

• dict items([(’name’, ’Arjun’), (’age’, 20)])

5. update()
Updates dictionary with another dictionary.
student = { " name " : " Arjun " }
student . update ({ " age " : 20 , " marks " : 85})
print ( student )

g
Output:

• {’name’: ’Arjun’, ’age’:


in
20, ’marks’: 85}
rn
6. pop()
lea

Removes a value using key and returns it.


ys

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

student = { " name " : " Arjun " }


ys

result = student . setdefault ( " age " , 20)


print ( result )
print ( student )
da

Output:
21

• 20

• {’name’: ’Arjun’, ’age’: 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}

for key , value in student . items () :


print ( key , value )
Output:

• 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 4: Update the value of "age". in


rn
Task 5: Remove the key "marks" from the dictionary.
lea

Task 6: Print all keys in the dictionary.

Task 7: Print all values in the dictionary.


ys

Task 8: Use a for loop to print all keys and values.


da

Task 9: Check whether the key "age" exists in the dictionary.


21

Task 10: Create a copy of the dictionary and print it.

Intermediate Practice Problems


Task 11: Given the dictionary {"math": 80, "science": 75, "english": 90}, use
a loop to calculate and print the total marks.

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

keys = student . keys ()


print ( keys )
da

# 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 )

Solutions for Intermediate Practice Problems


# Task 11

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.

• Functions help reduce code repetition

• Functions make code more readable

g
• Functions execute only when they are called
in
rn
def greet () :
print ( " Hello , ␣ Welcome ␣ to ␣ Python " )
lea

greet ()
Output:
ys

• Hello, Welcome to Python


da

Why Do We Use Functions?


21

• To avoid writing the same code again and again

• To divide a big problem into smaller parts

• To improve code maintenance

Function Syntax
def function_name ( arguments ) :
# function body
return value

1
Function Without Arguments
def say_hello () :
print ( " Hello " )

say_hello ()
Output:

• Hello

Function With Arguments


def greet ( name ) :
print ( " Hello " , name )

g
greet ( " Arjun " )

in
Output:

• Hello Arjun
rn
Function With Multiple Arguments
ea

def add (a , b ) :
l

result = a + b
ys

print ( result )

add (10 , 20)


da

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

Function Returning Multiple Values


l
ys

def calculate (a , b ) :
return a +b , a - b
da

result1 , result2 = calculate (10 , 5)


print ( result1 )
21

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 4: Write a function with default parameter value.

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

def greet ( name = " User " ) :


print ( " Hello " , name )
da

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 )

Solutions for Extra Practice Problems


# Task 6
def even_or_odd ( num ) :
if num % 2 == 0:
return " Even "
else :
return " Odd "

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

result = find_largest ([4 , 9 , 2 , 7])


print ( result )

# 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

result = count_vowels ( " Python ␣ Programming " )


print ( result )
ys

# Task 9
def factorial ( n ) :
da

fact = 1
for i in range (1 , n + 1) :
fact *= i
21

return fact

result = factorial (4)


print ( result )

# Task 10
def unique_elements ( lst ) :
result = []
for item in lst :
if item not in result :
result . append ( item )
return result

output = unique_elements ([1 , 2 , 2 , 3 , 4 , 3])


print ( output )

6
Python Programming: Try and Except
Introduction to Programming
January 2026

What is Exception Handling?


Exception handling is a mechanism used to handle runtime errors so that the normal
flow of a program is not interrupted.

• It prevents the program from crashing

g
• It handles unexpected errors

• It improves program reliability in


rn
What is an Exception?
lea

An exception is an error that occurs during the execution of a program.


ys

• Division by zero
da

• Invalid input

• File not found


21

Try and Except Block


try :
# code that may cause an error
except :
# code that runs if error occurs

Example Without Exception Handling


a = 10
b = 0
print ( a / b )
Result:

• Program crashes due to ZeroDivisionError

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

Handling Specific Exceptions


try :
num = int ( " abc " )
except ValueError :
print ( " Invalid ␣ conversion " )

g
Output:
• Invalid conversion in
rn
Multiple Except Blocks
lea

try :
ys

a = int ( input ( " Enter ␣ a ␣ number : ␣ " ) )


b = int ( input ( " Enter ␣ another ␣ number : ␣ " ) )
da

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

Why Use Exception Handling?


• Prevents program from crashing

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 2: Write a program that handles invalid integer input.


da

Task 3: Write a program using try-except-else.


21

Task 4: Write a program using try-except-finally.

Task 5: Write a program that handles both ValueError and ZeroDivisionError.

Extra Practice Problems


Task 6: Write a program to safely access a list element 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

print ( " Error ␣ occurred " )


finally :
print ( " End ␣ of ␣ program " )
21

# Task 5
try :
a = int ( " abc " )
b = 10 / 0
except ( ValueError , Ze roDivi sionEr ror ) :
print ( " Handled ␣ multiple ␣ errors " )

Solutions for Extra Practice Problems


# Task 6
try :
lst = [1 , 2 , 3]
print ( lst [5])
except IndexError :
print ( " Index ␣ out ␣ of ␣ range " )

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

print ( " Error ␣ handled " )


21

5
Python Programming: File Handling
Introduction to Programming
January 2026

What is File Handling?


File handling is used to store data permanently in a file and access it later.

• Data can be saved for future use

• Data can be read from files

g
• Files help in data management
in
rn
Types of Files
lea

• Text files (.txt)

• Binary files (.bin)


ys
da

File Modes
Different modes are used while opening a file.
21

• "r" – Read mode

• "w" – Write mode

• "a" – Append mode

• "r+" – Read and Write mode

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.

• "r" mode raises a FileNotFoundError

• "w" mode creates a new file

• "a" mode creates a new file if it does not exist

file = open ( " missing . txt " , " r " )


Result:

• FileNotFoundError occurs

Reading a File

g
file = open ( " data . txt " , " r " )
content = file . read ()
print ( content )
in
rn
file . close ()
lea

Writing into a File


ys

file = open ( " data . txt " , " w " )


da

file . write ( " Hello ␣ Python " )


file . close ()
21

Appending into a File


file = open ( " data . txt " , " a " )
file . write ( " \ nWelcome ␣ to ␣ File ␣ Handling " )
file . close ()

What Happens If We Do Not Close a File?


If a file is not closed properly:

• Data may not be saved completely

• System resources remain occupied

• File may get corrupted

That is why closing a file is very important.

2
Using with Statement
The with statement automatically closes the file.
with open ( " data . txt " , " r " ) as file :
content = file . read ()
print ( content )

Reading File Line by Line


with open ( " data . txt " , " r " ) as file :
for line in file :
print ( line )

Why Close a File?


• To free system resources

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.

Task 2: Write a program to read data from a file.


da

Task 3: Write a program to append data into an existing file.


21

Task 4: Write a program using with statement to read a file.

Task 5: Write a program to count number of lines in a file.

Extra Practice Problems


Task 6: Write a program to count number of words in a file.

Task 7: Write a program to search a word in a file.

Task 8: Write a program to copy content from one file to another.

Task 9: Write a program to read first 5 lines of a file.

Task 10: Write a program to write multiple lines into a file.

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

with open ( " sample . txt " , " r " ) as file :


ys

lines = file . readlines ()


print ( len ( lines ) )
da

Solutions for Extra Practice Problems


21

# 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 What is a Class? (The Blueprint/Naksha)


A Class is just a plan or a template. It is like an Aadhaar Card Design.
• The government has a master design that says every card must have a Name,
Address, and a 12-digit number.
• This design itself is not a person. It is just a rulebook.
What if we don’t have Classes?
Imagine 1 billion people making their own ID cards without a template. Someone would
forget their photo, someone would use a different size. It would be total confusion! Classes
bring order to your code.

2 What is an Object? (The Real Thing)


An Object is the actual Aadhaar card in your pocket.
• It follows the ”Class” rules, but it has your specific name and your photo.
• You can’t board a train using the ”Master Design”; you need your specific Object
(your own card).

3 The Concept of init and self


3.1 1. init (The Registration)
Think of this as the Setup Wizard. When you buy a new SIM card, the shopkeeper
”initializes” it by linking your name to the number.
• Without init : You would have a blank SIM card with no number.
• With init : The moment you create the object, it is ”born” with its data ready
to use.

3.2 2. self (Apna/Own)


self means ”This specific one.” Imagine a classroom where every student has a note-
book. If the teacher says, ”Write your name in [Link],” every student writes in
their own book.
• Without self, the computer wouldn’t know if you are talking about Rahul’s marks
or Anjali’s marks. It keeps data separate for every object.

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.

1. Book Class: Create a class Book with title and author.

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

def description ( self ) :


print ( f " This book is { self . title } by { self . 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 = " "

for char in text :


reversed_text = char + reversed_text

print ( reversed_text )

2 Check if a String is Palindrome


Problem: Check whether a string reads the same forwards and backwards.
Explanation: We reverse the string manually and compare it with the original string. If
both are equal, it is a palindrome.
word = " madam "
reversed_word = " "

for char in word :


reversed_word = char + reversed_word

if word == reversed_word :
print ( " Palindrome " )
else :
print ( " Not ␣ Palindrome " )

1

3 Find the Largest Number in a List


Problem: Find the largest number in a list.
Explanation: Assume the first number is the largest. Compare it with each number and
update when a larger value is found.
numbers = [10 , 25 , 90 , 45]
largest = numbers [0]

for num in numbers :


if num > largest :
largest = num

print ( largest )

4 Remove Duplicates from a List


Explanation: Create a new list and add elements only if they are not already present.
numbers = [1 , 2 , 2 , 3 , 4 , 4]
unique = []

for num in numbers :


if num not in unique :
unique . append ( num )

print ( unique )

5 Count Characters in a String


Explanation: Use a dictionary to store how many times each character appears.
text = " hello "
count = {}

for char in text :


if char in count :
count [ char ] += 1
else :
count [ char ] = 1

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

8 Find Missing Number


Explanation: Add all numbers from 1 to n, then subtract the numbers present in the list.
numbers = [1 , 2 , 3 , 5]
n = 5
total = 0

for i in range (1 , n + 1) :
total += i

for num in numbers :


total -= num

3
print ( total )

9 Check Prime Number


Explanation: A prime number is divisible only by 1 and itself.
num = 7
is_prime = True

if num < 2:
is_prime = False

for i in range (2 , num ) :


if num % i == 0:
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

for i in range (1 , num + 1) :


fact = fact * i

print ( fact )

11 Reverse a List
Explanation: Insert each element at the beginning of a new list.
numbers = [1 , 2 , 3]
reversed_list = []

for num in numbers :


reversed_list = [ num ] + 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]

for num in numbers :


if num > largest :
second = largest
largest = num
elif num > second and num != largest :
second = num

print ( second )

13 Check if List is Sorted


Explanation: Compare each element with the next one.
numbers = [1 , 2 , 3 , 4]
sorted_list = True

for i in range ( len ( numbers ) - 1) :


if numbers [ i ] > numbers [ i + 1]:
sorted_list = False

print ( sorted_list )

14 Find Common Elements


Explanation: Check if each element of one list exists in the other.
a = [1 , 2 , 3]
b = [2 , 3 , 4]
common = []

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 )

16 Count Words in a Sentence


Explanation: Split the sentence into words and count them.
sentence = " I ␣ love ␣ python "
words = sentence . split ()

print ( len ( words ) )

17 GCD of Two Numbers


Explanation: Repeatedly apply remainder until it becomes zero.
a = 12
b = 18

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 = []

for item in nested :

6
if type ( item ) == list :
for i in item :
flat . append ( i )
else :
flat . append ( item )

print ( flat )

19 First Non-Repeating Character


Explanation: Check each character and print the first one that appears only once.
text = " aabbcdd "

for char in text :


if text . count ( char ) == 1:
print ( char )
break

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 " )

21 Read File Line by Line


Explanation: Open the file and read each line using a loop.
file = open ( " test . txt " , " r " )

for line in file :


print ( line )

7
file . close ()

22 args and kwargs


Explanation: *args accepts multiple values, **kwargs accepts key-value pairs.
def show (* args , ** kwargs ) :
for value in args :
print ( value )

for key in kwargs :


print ( key , kwargs [ key ])

show (1 , 2 , 3 , name = " Python " , level = " Beginner " )

Additional Frequently Asked Python Interview Questions

23 Sum of Elements in a List


Problem: Find the sum of all numbers in a list.
Explanation: We start with a variable set to zero. We go through each number in the list
and keep adding it to the total.
numbers = [1 , 2 , 3 , 4 , 5]
total = 0

for num in numbers :


total = total + num

print ( total )

24 Count Even and Odd Numbers


Problem: Count how many even and odd numbers are in a list.
Explanation: If a number is divisible by 2, it is even. Otherwise, it is odd.
numbers = [1 , 2 , 3 , 4 , 5]
even = 0
odd = 0

for num in numbers :


if num % 2 == 0:

8
even += 1
else :
odd += 1

print ( " Even : " , even )


print ( " Odd : " , odd )

25 Check if a Number is Even or Odd


Problem: Determine whether a number is even or odd.
Explanation: If the remainder after dividing by 2 is zero, the number is even.
num = 7

if num % 2 == 0:
print ( " Even " )
else :
print ( " Odd " )

26 Find Length of a String Without len()


Problem: Find the length of a string without using len().
Explanation: We count each character one by one using a loop.
text = " python "
count = 0

for char in text :


count += 1

print ( count )

27 Check if Element Exists in a List


Problem: Check whether a given value exists in a list.
Explanation: We compare each element in the list with the target value.
numbers = [10 , 20 , 30 , 40]
target = 30
found = False

for num in numbers :

9
if num == target :
found = True

print ( found )

28 Find Smallest Number in a List


Problem: Find the smallest number in a list.
Explanation: Assume the first number is the smallest and compare it with others.
numbers = [25 , 10 , 40 , 5]
smallest = numbers [0]

for num in numbers :


if num < smallest :
smallest = num

print ( smallest )

29 Count Vowels in a String


Problem: Count how many vowels are in a string.
Explanation: We check each character and see if it is a vowel.
text = " education "
vowels = " aeiou "
count = 0

for char in text :


if char in vowels :
count += 1

print ( count )

30 Print Multiplication Table


Problem: Print the multiplication table of a number.
Explanation: Multiply the number with values from 1 to 10.
num = 5

for i in range (1 , 11) :


print ( num , " x " , i , " = " , num * i )

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

while num > 0:


digit = num % 10
reverse = reverse * 10 + digit
num = num // 10

print ( reverse )

32 Check Leap Year


Problem: Check whether a year is a leap year.
Explanation: A leap year is divisible by 4 but not by 100, unless it is also divisible by 400.
year = 2024

if ( year % 4 == 0 and year % 100 != 0) or ( year % 400 == 0) :


print ( " Leap ␣ Year " )
else :
print ( " Not ␣ a ␣ Leap ␣ Year " )

More Python Interview Questions for Students

33 Print Numbers from 1 to N


Problem: Print numbers from 1 to a given number N.
Explanation: We use a loop that starts from 1 and ends at N. Each number is printed one
by one.
n = 5

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

while num > 0:


digit = num % 10
total = total + digit
num = num // 10

print ( total )

35 Count Positive and Negative Numbers


Problem: Count positive and negative numbers in a list.
Explanation: Check each number and increase the corresponding counter.
numbers = [1 , -2 , 3 , -4 , 5]
positive = 0
negative = 0

for num in numbers :


if num > 0:
positive += 1
elif num < 0:
negative += 1

print ( " Positive : " , positive )


print ( " Negative : " , negative )

36 Check if a String Contains Only Digits


Problem: Check whether a string contains only digits.
Explanation: We check each character and verify it is between 0 and 9.
text = " 12345 "
is_digit = True

for char in text :


if char < ’0 ’ or char > ’9 ’:
is_digit = False

12
print ( is_digit )

37 Convert Celsius to Fahrenheit


Problem: Convert temperature from Celsius to Fahrenheit.
Explanation: Use the formula: (Celsius × 9/5) + 32
celsius = 25
fahrenheit = ( celsius * 9 / 5) + 32

print ( fahrenheit )

38 Find Index of an Element in a List


Problem: Find the index of an element without using index().
Explanation: We loop through the list and track the index manually.
numbers = [10 , 20 , 30 , 40]
target = 30
index = -1

for i in range ( len ( numbers ) ) :


if numbers [ i ] == target :
index = i

print ( index )

39 Replace Spaces with Hyphen in a String


Problem: Replace spaces with hyphens.
Explanation: We build a new string character by character. If space is found, replace it
with a hyphen.
text = " hello ␣ world ␣ python "
result = " "

for char in text :


if char == " ␣ " :
result += " -"
else :
result += char

13
print ( result )

40 Check if a Number is Perfect


Problem: Check whether a number is a perfect number.
Explanation: Add all divisors of the number except itself. If the sum equals the number,
it is perfect.
num = 6
total = 0

for i in range (1 , num ) :


if num % i == 0:
total += i

if total == num :
print ( " Perfect ␣ Number " )
else :
print ( " Not ␣ Perfect " )

41 Remove All Occurrences of an Element


Problem: Remove all occurrences of a value from a list.
Explanation: Create a new list and add elements that are not equal to the given value.
numbers = [1 , 2 , 3 , 2 , 4]
remove = 2
result = []

for num in numbers :


if num != remove :
result . append ( num )

print ( result )

42 Find Power of a Number Without Using pow()


Problem: Find power of a number without using built-in functions.
Explanation: Multiply the base number by itself exponent times.

14
base = 2
exponent = 3
result = 1

for i in range ( exponent ) :


result = result * base

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:

• Practice more problems regularly

• Learn optimized and advanced solutions

• Explore real interview-level questions

• ”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.

Happy Learning and Keep Practicing!

– Your Babai

15

You might also like