5. Python Control Structures and Data Handling: Questions and Answers

Select a question to reveal its answer.

Part AMultiple Choice Questions

1How many else blocks can be used in an if-elif-else structure?
  • a) Any number
  • b) Only one
  • c) Two
  • d) None
Answer

b) Only one

Only one else is allowed and it must come last. Multiple elif branches are allowed.

2In Python, code blocks such as conditional and looping statements are defined by:
  • a) Braces { }
  • b) Indentation
  • c) Semicolons
  • d) Parentheses
Answer

b) Indentation

Indentation (spaces or tabs at the start of a line) is mandatory and affects how the code executes.

3The match-case statement was introduced in Python version:
  • a) 3.0
  • b) 3.6
  • c) 3.10
  • d) 2.7
Answer

c) 3.10

It is part of structural pattern matching and is an alternative to the switch statement of other languages.

4Which symbol represents the default case in match-case?
  • a) *
  • b) #
  • c) _ (underscore)
  • d) %
Answer

c) _ (underscore)

5The default start value of range() is:
  • a) 1
  • b) 0
  • c) -1
  • d) None
Answer

b) 0

range(start, stop, step): start defaults to 0 and step defaults to 1.

6range(1, 6) generates the numbers:
  • a) 1 to 6
  • b) 0 to 5
  • c) 1 to 5
  • d) 2 to 6
Answer

c) 1 to 5

The stop value is not inclusive.

7Which statement stops a loop immediately?
  • a) continue
  • b) break
  • c) stop
  • d) exit
Answer

b) break

8Which statement skips the current iteration and moves to the next one?
  • a) break
  • b) pass
  • c) continue
  • d) skip
Answer

c) continue

9The else clause of a for loop runs:
  • a) when the loop is stopped by break
  • b) after the loop finishes normally
  • c) before the loop starts
  • d) only if the sequence is empty
Answer

b) after the loop finishes normally

10A loop that never ends because its condition never becomes False is called a(n):
  • a) nested loop
  • b) infinite loop
  • c) dead loop
  • d) else loop
Answer

b) infinite loop

It happens when the loop control variable is not updated.

11What is the index of the first element in a list?
  • a) 1
  • b) 0
  • c) -1
  • d) Depends on the list
Answer

b) 0

12Which method removes all elements from a list?
  • a) remove()
  • b) pop()
  • c) clear()
  • d) delete()
Answer

c) clear()

13Which list method adds an item at the end of the list?
  • a) insert()
  • b) append()
  • c) extend()
  • d) add()
Answer

b) append()

14Which of the following is immutable?
  • a) List
  • b) Set
  • c) Dictionary
  • d) Tuple
Answer

d) Tuple

15A tuple with a single element must be written as:
  • a) ("apple")
  • b) ("apple",)
  • c) ["apple"]
  • d) {"apple"}
Answer

b) ("apple",)

The trailing comma is required.

16Which data structure does not allow duplicates?
  • a) List
  • b) Tuple
  • c) Set
  • d) Dictionary values
Answer

c) Set

17What does a & b represent for two sets a and b?
  • a) Union
  • b) Intersection
  • c) Difference
  • d) Symmetric difference
Answer

b) Intersection

a | b is union, a - b is difference, a ^ b is symmetric difference.

18Which method removes an item from a set without raising an error if it is not found?
  • a) remove()
  • b) discard()
  • c) pop()
  • d) clear()
Answer

b) discard()

19Which method safely retrieves a value from a dictionary, returning None if the key does not exist?
  • a) get()
  • b) value()
  • c) find()
  • d) fetch()
Answer

a) get()

Square brackets raise a KeyError for a missing key.

20{} in Python creates an empty:
  • a) set
  • b) list
  • c) dictionary
  • d) tuple
Answer

c) dictionary

Use set() to create an empty set.

Part BFill in the Blanks

1The ______ statement checks the first condition in a conditional structure.
Answer

if.

2The ______ (underscore) acts as the default case in match-case.
Answer

_ (underscore): case _.

3In Python, ______ is the only way to define code blocks.
Answer

Indentation.

4A ______ loop is used to iterate over a sequence such as a list or string.
Answer

for.

5In range(start, stop, step), the ______ value is not included in the sequence.
Answer

stop.

6Placing one loop inside another is called ______.
Answer

Nesting (nested loops).

7The ______ statement exits a loop immediately and ______ skips the current iteration.
Answer

break; continue.

8A ______ loop executes a block of code as long as its condition is True.
Answer

while.

9Lists are created using ______ brackets, tuples using ______ and sets using ______.
Answer

Square [ ]; parentheses ( ); curly braces { }.

10______ lets you extract a range of elements from a list using list[start:stop:step].
Answer

Slicing.

11The list method ______ returns the number of times a value occurs and ______ returns the index of its first occurrence.
Answer

count(); index().

12The ______ function returns the number of items in a list, tuple or set.
Answer

len().

13A shorter way to create a list from a loop is called list ______.
Answer

Comprehension. Example: [x*x for x in range(1, 6)].

14Tuples are ______, so their contents cannot be changed once created.
Answer

Immutable.

15The set method ______ adds one element and ______ adds multiple elements.
Answer

add(); update().

16In a dictionary, each item is a ______ pair, and the keys must be ______.
Answer

Key-value; unique (and of an immutable type).

17The dictionary method ______ removes all items.
Answer

clear().

18From Python ______ onwards, dictionaries preserve insertion order.
Answer

3.7.

Part CMatch the Following

1Match the loop statements with their uses.
Column AColumn B
1. fora) Exits the loop immediately
2. whileb) Skips the current iteration
3. breakc) Repeats while a condition is True
4. continued) Iterates over a sequence
Answer
StatementUse
1. ford) Iterates over a sequence
2. whilec) Repeats while a condition is True
3. breaka) Exits the loop immediately
4. continueb) Skips the current iteration
2Match the list methods with their descriptions.
Column AColumn B
1. append()a) Removes the first occurrence of a value
2. insert()b) Adds an item at the end
3. remove()c) Adds an item at a given index
4. pop()d) Removes the item at a given index
Answer
MethodDescription
1. append()b) Adds an item at the end
2. insert()c) Adds an item at a given index
3. remove()a) Removes the first occurrence of a value
4. pop()d) Removes the item at a given index
3Match the set operators with their results for a={1,2,3}, b={3,4,5}.
Column AColumn B
1. a | ba) {1, 2}
2. a & bb) {1, 2, 4, 5}
3. a - bc) {1, 2, 3, 4, 5}
4. a ^ bd) {3}
Answer
ExpressionResult
1. a | bc) {1, 2, 3, 4, 5}
2. a & bd) {3}
3. a - ba) {1, 2}
4. a ^ bb) {1, 2, 4, 5}
4Match the data structures with their syntax.
Column AColumn B
1. Lista) {key: value}
2. Tupleb) [ ]
3. Setc) ( )
4. Dictionaryd) { } with single elements
Answer
Data structureSyntax
1. Listb) [ ]
2. Tuplec) ( )
3. Setd) { } with single elements
4. Dictionarya) {key: value}
5Match the dictionary methods with their descriptions.
Column AColumn B
1. keys()a) All key-value pairs
2. values()b) All keys
3. items()c) All values
4. update()d) Updates with another dictionary
Answer
MethodDescription
1. keys()b) All keys
2. values()c) All values
3. items()a) All key-value pairs
4. update()d) Updates with another dictionary

Part DShort Answer Questions

1What are control structures?
Answer

Control structures are methods that dictate the flow of execution in a program. They answer the question 'What should happen next in a program?'. They allow decision-making, looping and branching based on conditions. The two main kinds are conditional statements and looping statements.

2Explain the role of indentation in Python.
Answer

A code block is a group of statements executed together. In Python, indentation (spaces or tabs at the beginning of a line) is the only way to define code blocks such as conditional and looping statements. It is mandatory and directly affects how the code executes.

3What are the applications of control structures?
Answer
  • Decision making
  • Flow control
  • Iterations
  • Improved efficiency and flexibility
  • Real-world applications
4Write the syntax of the if-elif-else statement. Explain how it works.
Answer
if condition:
    code block/ statement
elif condition:
    code block/ statement
else:
    code block/ statement
  • The if statement checks the first condition.
  • If it is false, the elif (else if) checks another condition.
  • If neither is true, the else block is executed.
  • Multiple elif branches are allowed; only one else is allowed and it must come last.
  • elif and else are not compulsory.
  • Only one block is executed, even if multiple conditions are true.
5Write a program to display the grade for the marks entered, using if-elif-else.
Answer
marks = int(input("Enter marks: "))
if marks >= 90:
    print("Grade A+")
elif marks >= 80:
    print("Grade A")
elif marks >= 70:
    print("Grade B+")
elif marks >= 60:
    print("Grade B")
elif marks >= 50:
    print("Grade C+")
elif marks >= 40:
    print("Grade C")
elif marks >= 30:
    print("Grade D+")
else:
    print("Grade D")

Output

Enter marks: 91
Grade A+
6What is the match-case statement? What are its benefits?
Answer

match-case was introduced in Python 3.10 as part of structural pattern matching. It is an alternative to the switch statement of languages like C++, Java and JavaScript. It compares a value against several patterns and executes the code of the first matching case; _ is the default case.

  • Cleaner and more readable than long if-elif-else chains.
  • Supports advanced pattern matching (tuples, lists, conditions within patterns).
  • Enhances code maintainability.
7Write the syntax of match-case and give an example.
Answer
match variable:
    case pattern1:
        # code block
    case pattern2:
        # code block
    case _:
        # default block
day = "Monday"
match day:
    case "Monday":
        print("Start of the week")
    case "Friday":
        print("Weekend is near")
    case _:
        print("Regular day")

Output

Start of the week
8What is looping? Why is it used?
Answer

Looping allows a set of instructions to be executed repeatedly until a certain condition is met. It reduces the need to write the same code many times and makes programs shorter, faster and easier to maintain. It is used for processing collections of data, repeating calculations and controlling program flow, and is widely used in data processing, simulations and algorithm development.

9Explain the for loop with its syntax.
Answer

A for loop iterates over a sequence (like a list or string) and performs actions on each item.

for loop_variable in sequence:
    # do required operation with loop_variable
  • loop_variable takes the value of each element, one at a time.
  • sequence is the collection being iterated over.
  • The code block runs once for each item.
10Explain how a for loop works, step by step.
Answer
  1. Python looks at the first item in the sequence.
  2. It assigns that item to the loop variable.
  3. It runs the code inside the loop.
  4. It moves to the next item and repeats.
  5. When all items are processed, the loop ends.
11Write a program to print each character of a string using a for loop.
Answer
word = "hello"
for letter in word:
    print(letter)

Output

h
e
l
l
o
12What is the range() function? Write its syntax.
Answer

range() is a built-in function that generates a sequence of numbers, often used with for loops to repeat something a specific number of times.

range(start, stop, step)
  • start: where the sequence begins (default 0)
  • stop: where the sequence ends (not inclusive)
  • step: how much to increase each time (default 1)
for i in range(1, 6):
    print(i)

Output

1
2
3
4
5
13What is a nested loop? Give an example.
Answer

Placing one loop inside another is called nesting. Like a clock, the outer loop (hour hand) moves slowly while the inner loop (minute hand) completes a full cycle for each step of the outer loop.

for i in range(1, 4):
    for j in range(1, 4):
        print(i, "*", j, "=", i * j)

Output

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
14Distinguish between break and continue.
Answer
breakcontinue
Stops the loop immediately when a condition is metSkips the current iteration and moves to the next one
Prevents unnecessary iterationsAllows selective execution without ending the loop
Example: stops at 5, prints 1 2 3 4Example: skips 3, prints 1 2 4 5
15Write a program to demonstrate the break statement.
Answer
for num in range(1, 10):
    if num == 5:
        break
    print(num)

Output

1
2
3
4

The loop stops when num becomes 5, so 5 is not printed.

16Write a program to demonstrate the continue statement.
Answer
for num in range(1, 6):
    if num == 3:
        continue
    print(num)

Output

1
2
4
5

When num is 3, continue skips print(num).

17Write a program to count the vowels in a string.
Answer
sentence = "Python is fun"
vowels = "aeiou"
count = 0
for char in sentence:
    if char.lower() in vowels:
        count += 1
print("Number of vowels:", count)

Output

Number of vowels: 3
18Explain the for loop with else using an example.
Answer

An else clause can be used with a for loop. It runs after the loop finishes normally (that is, when the sequence is exhausted).

for i in range(3):
    print("Loop:", i)
else:
    print("Loop finished")

Output

Loop: 0
Loop: 1
Loop: 2
Loop finished
19Explain the while loop with its syntax.
Answer

A while loop repeatedly executes a block of code based on a condition. The condition is evaluated before each iteration; if it is True the body runs, and once it becomes False the loop terminates.

while condition:
    block of code
count = 1
while count <= 5:
    print("Count is :", count)
    count += 1

Output

Count is : 1
Count is : 2
Count is : 3
Count is : 4
Count is : 5
20Differentiate between for loop and while loop.
Answer
for loopwhile loop
Iterates over a sequence (list, string, range())Repeats as long as a condition is True
Number of repetitions is known from the sequenceUsed when the number of repetitions is not known in advance
Loop variable is updated automaticallyLoop control variable must be updated inside the loop
for i in range(1, 6):while i <= 5:
21What is an infinite loop? How can it happen?
Answer

An infinite loop occurs when the loop condition never becomes False. This can happen if the loop control variable is not updated.

i = 1
while i < 5:
    print("i =", i)   # missing increment: i never changes, so i < 5 is always True
22Explain the use of break in a while loop with an example.
Answer

break exits the while loop prematurely, even if the condition is still True.

i = 1
while i <= 10:
    print(i)
    if i == 5:
        break
    i += 1

Output

1
2
3
4
5
23Explain the use of continue in a while loop with an example.
Answer

continue skips the current iteration and moves to the next one.

i = 0
while i < 6:
    i += 1
    if i == 3:
        continue
    print(i)

Output

1
2
4
5
6
24Explain the while loop with else clause.
Answer

The else block of a while loop executes when the loop condition becomes False.

i = 0
while i < 4:
    print("i =", i)
    i += 1
else:
    print("Loop finished")

Output

i = 0
i = 1
i = 2
i = 3
Loop finished
25What is a nested while loop? Give an example.
Answer

A while loop placed inside another while loop.

i = 1
while i <= 3:
    j = 1
    while j <= 2:
        print(f"i = {i}, j = {j}")
        j += 1
    i += 1

Output

i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
26List some practical applications of the while loop.
Answer
  • User input validation: repeatedly ask for input until valid data is entered.
  • Menu-driven programs: keep displaying options until the user chooses to exit.
  • Game loops: keep running the game logic until the player quits.
27Give some tips for writing effective while loops.
Answer
  • Always ensure the loop condition will eventually become False.
  • Use break and continue carefully to control the flow.
  • Avoid infinite loops unless intentionally required (e.g. servers, games).
  • Use comments to clarify the loop logic.
28What is a list? Mention any two characteristics.
Answer

A list is a data structure that stores multiple items in a single variable. It is created with square brackets [ ] and can hold different data types (integers, strings, floats, even other lists). Characteristics: ordered (items keep a defined order), mutable (can add, remove or modify elements), allows duplicates, and indexed from 0.

29How are list elements accessed? Explain indexing.
Answer

List elements are accessed by index, starting from 0. A negative index counts from the end.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[2])
print(fruits[-1])

Output

apple
cherry
cherry
30What is list slicing? Give an example.
Answer

Slicing accesses a range of elements. Syntax: list[start:stop:step]. The stop index is not included.

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])

Output

[20, 30, 40]
31How can list elements be modified? Give an example.
Answer

Lists are mutable, so an element can be changed by assigning a new value to its index.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)

Output

['apple', 'blueberry', 'cherry']
32Explain the methods for adding elements to a list.
Answer
  • append(): adds an item to the end. fruits.append("orange")
  • insert(): adds an item at a specific index. fruits.insert(1, "grape")
  • extend(): adds the elements of another list. fruits.extend(["kiwi", "melon"])
33Explain the methods for removing elements from a list.
Answer
  • remove(): removes the first occurrence of a value. fruits.remove("banana")
  • pop(): removes the item at a given index. fruits.pop(2)
  • clear(): removes all items. fruits.clear()
34Write a program to demonstrate list operations (append, remove, pop).
Answer
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
fruits.remove("banana")
print(fruits)
fruits.pop(1)
print(fruits)
print(len(fruits))

Output

['apple', 'banana', 'cherry', 'orange']
['apple', 'cherry', 'orange']
['apple', 'orange']
2
35How do you find the length of a list and loop through it?
Answer

len() gives the number of items. A list can be traversed with a for loop or a while loop.

fruits = ["apple", "banana", "cherry"]
print(len(fruits))
for fruit in fruits:
    print(fruit)
i = 0
while i < len(fruits):
    print(fruits[i])
    i += 1

Output

3
apple
banana
cherry
apple
banana
cherry
36How can you check whether an item exists in a list?
Answer

Use the membership operators in and not in.

fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
    print("Apple is in the list")

Output

Apple is in the list
37List the important list methods.
Answer
MethodDescription
append()Adds an item to the end
insert()Inserts an item at a specified index
extend()Adds multiple items
remove()Removes the first occurrence of an item
pop()Removes the item at an index
clear()Removes all items
index()Returns the index of the first occurrence
count()Returns the number of occurrences
sort()Sorts the list in ascending order
reverse()Reverses the list
copy()Returns a shallow copy of the list
38What is list comprehension? Give an example.
Answer

List comprehension is a concise way to create lists.

squares = [x * x for x in range(1, 6)]
print(squares)

Output

[1, 4, 9, 16, 25]
39What is a nested list? How is an element accessed?
Answer

A list can contain other lists. An element is accessed using two indices: first the inner list, then the element in it.

matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[1][0])

Output

3
40What is a tuple? Why is it called immutable?
Answer

A tuple is a built-in data type that stores multiple items in a single variable, like a list, but its contents cannot be changed once created; this is why it is called immutable. Tuples suit fixed data such as coordinates, configuration settings or constants.

41How are tuples created? Write the different ways.
Answer
fruits = ("apple", "banana", "cherry")   # with parentheses
colors = "red", "green", "blue"           # without parentheses
empty = ()                                # empty tuple
single = ("apple",)                       # single element needs a trailing comma
42Differentiate between list and tuple.
Answer
ListTuple
Created with [ ]Created with ( )
MutableImmutable
Elements can be added, removed or changedContents cannot be changed after creation
More flexibleIdeal for fixed collections of data; uses less memory
Has many methods (append, insert, pop...)Only count() and index()
43What operations can be performed on tuples?
Answer

Although tuples are immutable, these operations are possible: concatenation, repetition, membership testing, slicing, indexing, len() and looping.

a = (1, 2)
b = (3, 4)
c = a + b
print(c)
repeat = ("Hi",) * 3
print(repeat)
numbers = (10, 20, 30, 40, 50)
print(numbers[1:4])
print(numbers[::2])
print(30 in numbers)
print(len(numbers))

Output

(1, 2, 3, 4)
('Hi', 'Hi', 'Hi')
(20, 30, 40)
(10, 30, 50)
True
5
44What are the tuple methods?
Answer

Tuples have only two methods because they are immutable: count() returns how many times a value appears, and index() returns the index of the first occurrence.

numbers = (1, 2, 3, 2, 2)
print(numbers.count(2))
print(numbers.index(3))

Output

3
2
45What is a set? Mention its key features.
Answer

A set is a built-in data type that stores multiple items in a single variable. Sets are unordered, unindexed and do not allow duplicate values. They are useful for removing duplicates, checking membership and performing union, intersection and difference.

46Explain the characteristics of sets.
Answer
  • Unordered: no guaranteed order of items.
  • Unindexed: elements cannot be accessed by index.
  • No duplicates: duplicate values are removed automatically.
  • Immutable elements: elements must be immutable (numbers, strings, tuples); lists and dictionaries cannot be elements.
  • Mutable container: the set itself can be changed by adding or removing items.
47How are sets created?
Answer
fruits = {"apple", "banana", "cherry"}
colors = set(["red", "green", "blue"])   # set() constructor
empty = set()                            # NOT {} which creates a dictionary
48Explain the methods for adding and removing elements in a set.
Answer
  • add(): adds a single element.
  • update(): adds multiple elements.
  • remove(): removes a specific item; raises an error if not found.
  • discard(): removes an item without error if not found.
  • pop(): removes a random item.
  • clear(): removes all items.
49What are set operations? Name any two.
Answer

Sets support mathematical operations: union, intersection, difference and symmetric difference.

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)    # union
print(a & b)    # intersection
print(a - b)    # difference
print(a ^ b)    # symmetric difference

Output

{1, 2, 3, 4, 5}
{3}
{1, 2}
{1, 2, 4, 5}
50Explain union and intersection of sets with examples.
Answer

Union combines the elements of both sets (no duplicates). Intersection gives the elements common to both sets.

a = {"apple", "banana", "cherry"}
b = {"banana", "kiwi", "melon"}
print("Union:", sorted(a.union(b)))
print("Intersection:", a.intersection(b))
print("Difference:", sorted(a.difference(b)))

Output

Union: ['apple', 'banana', 'cherry', 'kiwi', 'melon']
Intersection: {'banana'}
Difference: ['apple', 'cherry']

(The order of elements in a set may vary each time; the output above is sorted for display.)

51How can you check whether one set is a subset of another?
Answer

Use issubset().

x = {1, 2}
y = {1, 2, 3, 4}
print(x.issubset(y))

Output

True
52Write a program to remove duplicates from a list using a set.
Answer
names = ["Alice", "Bob", "Alice", "Charlie"]
unique_names = set(names)
print(sorted(unique_names))

Output

['Alice', 'Bob', 'Charlie']
53List the important set methods.
Answer
MethodDescription
add()Adds a single element
update()Adds multiple elements
remove()Removes an element (error if not found)
discard()Removes an element (no error)
pop()Removes a random element
clear()Removes all elements
union()Returns the union of sets
intersection()Returns common elements
difference()Returns elements in one set but not the other
symmetric_difference()Returns elements in either set but not both
issubset()Checks if a set is a subset of another
issuperset()Checks if a set is a superset of another
isdisjoint()Checks if sets have no common elements
54Define a dictionary with an example.
Answer

A dictionary stores data as key-value pairs. Instead of numeric indices, unique keys are used to access the values. It suits structured data like student records.

student = {
    "name": "Aryananda",
    "age": 17,
    "class": "12A"
}
print(student)

Output

{'name': 'Aryananda', 'age': 17, 'class': '12A'}
55Explain the characteristics of dictionaries.
Answer
  • Key-value pairs: each item has a key and a value.
  • Ordered: unordered before Python 3.7; from 3.7 onwards insertion order is preserved.
  • Mutable: items can be added, updated or removed.
  • Unique keys: a repeated key overwrites the previous value.
  • Immutable keys: keys must be strings, numbers or tuples (not lists or dictionaries).
  • Values can be any type: strings, numbers, lists, other dictionaries.
56How are dictionaries created?
Answer

Using curly braces or the dict() constructor. With dict(), keys must be valid identifiers (no spaces or special characters).

student1 = {"name": "Aryananda", "age": 17}
student2 = dict(name="Sreerag", age=17, class_="CSE")
print(student1)
print(student2)

Output

{'name': 'Aryananda', 'age': 17}
{'name': 'Sreerag', 'age': 17, 'class_': 'CSE'}
57How are dictionary elements accessed?
Answer

Values are accessed with their keys, using square brackets or the get() method. get() is safer because it returns None if the key does not exist, whereas square brackets raise a KeyError.

student = dict(name="Sreenanda", age=17, class_="E1")
print(student["name"])
print(student.get("age"))
print(student.get("mark"))

Output

Sreenanda
17
None
58How can dictionary elements be modified?
Answer

Assign a new value to an existing key to update it, or assign to a new key to add a pair.

student = dict(name="Sreelakshmi", age=17, class_="XI")
student["age"] = 18          # update
student["school"] = "SNHSS"  # add
print(student)

Output

{'name': 'Sreelakshmi', 'age': 18, 'class_': 'XI', 'school': 'SNHSS'}
59Explain the ways of removing elements from a dictionary.
Answer
  • pop(key): removes the item with the given key.
  • popitem(): removes the last inserted item (Python 3.7+).
  • del: deletes a key-value pair, e.g. del student["age"].
  • clear(): removes all items.
student = dict(name="Devarag", age=17, class_="XI")
student.pop("class_")
del student["age"]
print(student)
student.clear()
print(student)

Output

{'name': 'Devarag'}
{}
60Differentiate between keys and values in a dictionary.
Answer
KeysValues
Must be uniqueCan repeat
Must be immutable (string, number, tuple)Can be of any data type
Used to access the valuesData stored against a key
Example: "name"Example: "Aryananda"
61Explain the different methods used in dictionaries.
Answer
MethodDescription
get(key)Returns the value for the key
keys()Returns a view of all keys
values()Returns a view of all values
items()Returns a view of all key-value pairs
update(dict2)Updates the dictionary with another dictionary
pop(key)Removes the item with the specified key
popitem()Removes the last inserted item
clear()Removes all items
copy()Returns a shallow copy
setdefault()Returns the value of a key; sets a default if not found

Part EPrograms and Output

1Write a program to print numbers from 1 to 10 using a while loop.
Answer
i = 1
while i <= 10:
    print(i)
    i += 1

Output

1
2
3
4
5
6
7
8
9
10
2Write a program to print numbers from 10 to 1 using a while loop.
Answer
i = 10
while i >= 1:
    print(i)
    i -= 1

Output

10
9
8
7
6
5
4
3
2
1
3Write a program that asks the user to enter a password until the correct one is entered.
Answer
password = ""
while password != "python123":
    password = input("Enter password: ")
print("Access granted")

Output

Enter password: abc
Enter password: hello
Enter password: python123
Access granted
4Simulate a simple ATM withdrawal system using a while loop.
Answer
balance = 5000
choice = "yes"
while choice == "yes":
    amount = int(input("Enter amount to withdraw: "))
    if amount <= balance:
        balance = balance - amount
        print("Collect cash. Balance:", balance)
    else:
        print("Insufficient balance")
    choice = input("Another withdrawal? (yes/no): ")
print("Thank you")

Output

Enter amount to withdraw: 2000
Collect cash. Balance: 3000
Another withdrawal? (yes/no): yes
Enter amount to withdraw: 4000
Insufficient balance
Another withdrawal? (yes/no): yes
Enter amount to withdraw: 1000
Collect cash. Balance: 2000
Another withdrawal? (yes/no): no
Thank you
5Write a program to print the multiplication table of a number using a for loop.
Answer
n = int(input("Enter a number: "))
for i in range(1, 11):
    print(n, "x", i, "=", n * i)

Output

Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
6Write a program to print a multiplication table using nested for loops.
Answer
for i in range(1, 4):
    for j in range(1, 4):
        print(i, "*", j, "=", i * j)

Output

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
7Write a program to count the vowels in a string.
Answer
text = input("Enter a string: ")
count = 0
for ch in text:
    if ch.lower() in "aeiou":
        count += 1
print("Number of vowels:", count)

Output

Enter a string: Computer Applications
Number of vowels: 8
8Write a program to find the sum of the numbers from 1 to 10 using a for loop.
Answer
total = 0
for i in range(1, 11):
    total += i
print("Sum =", total)

Output

Sum = 55
9Create a list of 5 fruits and print them using a loop.
Answer
fruits = ["apple", "banana", "cherry", "orange", "grape"]
for fruit in fruits:
    print(fruit)

Output

apple
banana
cherry
orange
grape
10Write a program to find the largest number in a list.
Answer
numbers = [12, 45, 7, 89, 23]
largest = numbers[0]
for n in numbers:
    if n > largest:
        largest = n
print("Largest:", largest)

Output

Largest: 89

(The built-in max(numbers) gives the same result.)

11Create a list of numbers and remove all even numbers.
Answer
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
odd_numbers = []
for n in numbers:
    if n % 2 != 0:
        odd_numbers.append(n)
print(odd_numbers)

Output

[1, 3, 5, 7]
12Use list comprehension to generate a list of cubes from 1 to 10.
Answer
cubes = [x ** 3 for x in range(1, 11)]
print(cubes)

Output

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
13Create a nested list and access specific elements.
Answer
students = [["Anu", 85], ["Biju", 90], ["Diya", 78]]
print(students[1])
print(students[2][0])
print(students[0][1])

Output

['Biju', 90]
Diya
85
14Write a program to find the average of the marks in a list.
Answer
marks = [85, 90, 78, 92]
average = sum(marks) / len(marks)
print("Average marks:", average)

Output

Average marks: 86.25
15Create a shopping list using append().
Answer
shopping = []
shopping.append("milk")
shopping.append("bread")
shopping.append("eggs")
print(shopping)

Output

['milk', 'bread', 'eggs']
16Write a program to remove duplicates from a list without using a set.
Answer
items = ["apple", "banana", "apple", "orange"]
unique_items = []
for item in items:
    if item not in unique_items:
        unique_items.append(item)
print(unique_items)

Output

['apple', 'banana', 'orange']
17Create a set of 5 fruits and then add a new fruit.
Answer
fruits = {"apple", "banana", "cherry", "orange", "grape"}
fruits.add("kiwi")
print(sorted(fruits))
print(len(fruits))

Output

['apple', 'banana', 'cherry', 'grape', 'kiwi', 'orange']
6
18Write a program to remove duplicates from a list using a set.
Answer
names = ["Alice", "Bob", "Alice", "Charlie"]
unique_names = list(set(names))
print(sorted(unique_names))

Output

['Alice', 'Bob', 'Charlie']
19Perform union and intersection on two sets of numbers.
Answer
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Union:", a | b)
print("Intersection:", a & b)

Output

Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
20Check if one set is a subset of another.
Answer
x = {1, 2}
y = {1, 2, 3, 4}
print(x.issubset(y))
print(y.issubset(x))

Output

True
False
21Create a set and then remove an element using discard().
Answer
numbers = {1, 2, 3, 4}
numbers.discard(3)
numbers.discard(10)   # no error even though 10 is not in the set
print(numbers)

Output

{1, 2, 4}
22Write a program to create and update a dictionary.
Answer
student = {"name": "Anu", "age": 17}
student["age"] = 18
student["class"] = "XI"
print(student)
del student["age"]
print(student)

Output

{'name': 'Anu', 'age': 18, 'class': 'XI'}
{'name': 'Anu', 'class': 'XI'}
23Write a program to read a name and a mark from the user and store them in a dictionary.
Answer
name = input("Enter name: ")
mark = int(input("Enter mark: "))
result = {name: mark}
print(result)

Output

Enter name: Diya
Enter mark: 70
{'Diya': 70}
24Write a program to print all keys and values of a dictionary.
Answer
student = {"name": "Anu", "age": 17, "class": "XI"}
for key in student:
    print(key, ":", student[key])

Output

name : Anu
age : 17
class : XI

Part FLong Answer Questions

1Explain the conditional statements in Python with examples.
Answer

Conditional statements let a program make decisions based on conditions. The main ones in Python are if-elif-else and match-case.

  • if-elif-else: if checks the first condition, elif checks further conditions, and else runs when none is true. Only one block runs.
  • match-case: compares a value with several patterns and runs the first matching case; case _ is the default.
marks = 72
if marks >= 90:
    print("Grade A+")
elif marks >= 70:
    print("Grade B+")
else:
    print("Grade C")

day = "Friday"
match day:
    case "Monday":
        print("Start of the week")
    case "Friday":
        print("Weekend is near")
    case _:
        print("Regular day")

Output

Grade B+
Weekend is near
2Explain the for loop in Python with the range() function, nested loops, break, continue and else.
Answer

A for loop iterates over a sequence. range(start, stop, step) produces numbers (stop is not included). Loops can be nested. break stops the loop, continue skips an iteration, and an else clause runs when the loop ends normally.

for i in range(1, 4):
    for j in range(1, 3):
        print(i, j)

for n in range(1, 6):
    if n == 3:
        continue
    if n == 5:
        break
    print(n)
else:
    print("not printed because of break")

Output

1 1
1 2
2 1
2 2
3 1
3 2
1
2
4
3Explain the while loop in Python with examples of break, continue and else.
Answer

A while loop repeats while its condition is True. Make sure the loop variable is updated, otherwise the loop becomes infinite. break exits early, continue skips the current iteration, and else runs when the condition becomes False.

i = 0
while i < 6:
    i += 1
    if i == 3:
        continue
    if i == 5:
        break
    print(i)
else:
    print("else part")

Output

1
2
4
4Explain lists in Python: characteristics, creation, indexing, slicing, adding and removing elements.
Answer

A list is an ordered, mutable, indexed collection that allows duplicates, created with [ ].

fruits = ["apple", "banana", "cherry"]
print(fruits[0], fruits[-1])
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
fruits.append("orange")
fruits.insert(1, "grape")
fruits.extend(["kiwi", "melon"])
print(fruits)
fruits.remove("banana")
fruits.pop(2)
print(fruits)
print(len(fruits))

Output

apple cherry
[20, 30, 40]
['apple', 'grape', 'banana', 'cherry', 'orange', 'kiwi', 'melon']
['apple', 'grape', 'orange', 'kiwi', 'melon']
5
5Explain tuples in Python and compare them with lists.
Answer

A tuple is an ordered, immutable collection created with ( ). Its contents cannot be changed after creation, which makes it ideal for fixed data. Tuples support indexing, slicing, concatenation, repetition, membership testing, len() and looping, and have only count() and index() as methods.

ListTuple
[ ]( )
MutableImmutable
Many methodscount(), index()
More memoryLess memory, slightly faster
6Explain sets in Python: characteristics, methods and set operations.
Answer

A set is an unordered, unindexed collection of unique elements; elements must be immutable but the set itself is mutable. Methods: add, update, remove, discard, pop, clear. Operations: union (|), intersection (&), difference (-), symmetric difference (^), issubset, issuperset, isdisjoint.

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)
print(a & b)
print(a - b)
print(a ^ b)

Output

{1, 2, 3, 4, 5}
{3}
{1, 2}
{1, 2, 4, 5}
7Explain dictionaries in Python: characteristics, creation, accessing, modifying and removing elements.
Answer

A dictionary stores key-value pairs; keys are unique and immutable, values can be of any type, and the dictionary is mutable (and keeps insertion order from Python 3.7).

student = dict(name="Sreelakshmi", age=17, class_="XI")
print(student["name"])
print(student.get("age"))
student["age"] = 18
student["school"] = "SNHSS"
print(student)
student.pop("class_")
print(student)
print(list(student.keys()))
print(list(student.values()))

Output

Sreelakshmi
17
{'name': 'Sreelakshmi', 'age': 18, 'class_': 'XI', 'school': 'SNHSS'}
{'name': 'Sreelakshmi', 'age': 18, 'school': 'SNHSS'}
['name', 'age', 'school']
['Sreelakshmi', 18, 'SNHSS']
8Compare list, tuple, set and dictionary.
Answer
PropertyListTupleSetDictionary
DefinitionOrdered collection of itemsOrdered, immutable collectionUnordered collection of unique itemsCollection of key-value pairs
Syntax[ ]( ){ }{key: value}
MutableYesNoYesYes
Ordered (Python 3.7+)YesYesNoYes
IndexedYesYesNoNo (access via keys)
DuplicatesAllowedAllowedNot allowedKeys: no; values: yes
Element accessBy indexBy indexNot allowedBy key
Use caseGeneral-purpose collectionFixed collectionsUnique items, set operationsStructured data, key-value mapping
Common methodsappend(), insert(), pop()count(), index()add(), union()get(), keys(), values(), items()
Example["a", "b", "c"]("a", "b", "c"){"a", "b", "c"}{"name": "Anu", "age": 17}
9Distinguish between for loop and while loop with examples.
Answer
for loopwhile loop
Iterates over a sequenceRepeats while a condition is True
Used when the number of repetitions is knownUsed when it is not known in advance
Loop variable updated automaticallyLoop variable must be updated by the programmer
Less chance of infinite loopCan become infinite if the variable is not updated
for i in range(1, 4):
    print("for:", i)
i = 1
while i <= 3:
    print("while:", i)
    i += 1

Output

for: 1
for: 2
for: 3
while: 1
while: 2
while: 3