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
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
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
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) %
c) _ (underscore)
5The default start value of range() is:
- a) 1
- b) 0
- c) -1
- d) None
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
c) 1 to 5
The stop value is not inclusive.
7Which statement stops a loop immediately?
- a) continue
- b) break
- c) stop
- d) exit
b) break
8Which statement skips the current iteration and moves to the next one?
- a) break
- b) pass
- c) continue
- d) skip
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
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
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
b) 0
12Which method removes all elements from a list?
- a) remove()
- b) pop()
- c) clear()
- d) delete()
c) clear()
13Which list method adds an item at the end of the list?
- a) insert()
- b) append()
- c) extend()
- d) add()
b) append()
14Which of the following is immutable?
- a) List
- b) Set
- c) Dictionary
- d) Tuple
d) Tuple
15A tuple with a single element must be written as:
- a) ("apple")
- b) ("apple",)
- c) ["apple"]
- d) {"apple"}
b) ("apple",)
The trailing comma is required.
16Which data structure does not allow duplicates?
- a) List
- b) Tuple
- c) Set
- d) Dictionary values
c) Set
17What does a & b represent for two sets a and b?
- a) Union
- b) Intersection
- c) Difference
- d) Symmetric difference
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()
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()
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
c) dictionary
Use set() to create an empty set.
Part BFill in the Blanks
1The ______ statement checks the first condition in a conditional structure.
if.
2The ______ (underscore) acts as the default case in match-case.
_ (underscore): case _.
3In Python, ______ is the only way to define code blocks.
Indentation.
4A ______ loop is used to iterate over a sequence such as a list or string.
for.
5In range(start, stop, step), the ______ value is not included in the sequence.
stop.
6Placing one loop inside another is called ______.
Nesting (nested loops).
7The ______ statement exits a loop immediately and ______ skips the current iteration.
break; continue.
8A ______ loop executes a block of code as long as its condition is True.
while.
9Lists are created using ______ brackets, tuples using ______ and sets using ______.
Square [ ]; parentheses ( ); curly braces { }.
10______ lets you extract a range of elements from a list using list[start:stop:step].
Slicing.
11The list method ______ returns the number of times a value occurs and ______ returns the index of its first occurrence.
count(); index().
12The ______ function returns the number of items in a list, tuple or set.
len().
13A shorter way to create a list from a loop is called list ______.
Comprehension. Example: [x*x for x in range(1, 6)].
14Tuples are ______, so their contents cannot be changed once created.
Immutable.
15The set method ______ adds one element and ______ adds multiple elements.
add(); update().
16In a dictionary, each item is a ______ pair, and the keys must be ______.
Key-value; unique (and of an immutable type).
17The dictionary method ______ removes all items.
clear().
18From Python ______ onwards, dictionaries preserve insertion order.
3.7.
Part CMatch the Following
1Match the loop statements with their uses.
| Column A | Column B |
|---|---|
| 1. for | a) Exits the loop immediately |
| 2. while | b) Skips the current iteration |
| 3. break | c) Repeats while a condition is True |
| 4. continue | d) Iterates over a sequence |
| Statement | Use |
|---|---|
| 1. for | d) Iterates over a sequence |
| 2. while | c) Repeats while a condition is True |
| 3. break | a) Exits the loop immediately |
| 4. continue | b) Skips the current iteration |
2Match the list methods with their descriptions.
| Column A | Column 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 |
| Method | Description |
|---|---|
| 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 A | Column B |
|---|---|
| 1. a | b | a) {1, 2} |
| 2. a & b | b) {1, 2, 4, 5} |
| 3. a - b | c) {1, 2, 3, 4, 5} |
| 4. a ^ b | d) {3} |
| Expression | Result |
|---|---|
| 1. a | b | c) {1, 2, 3, 4, 5} |
| 2. a & b | d) {3} |
| 3. a - b | a) {1, 2} |
| 4. a ^ b | b) {1, 2, 4, 5} |
4Match the data structures with their syntax.
| Column A | Column B |
|---|---|
| 1. List | a) {key: value} |
| 2. Tuple | b) [ ] |
| 3. Set | c) ( ) |
| 4. Dictionary | d) { } with single elements |
| Data structure | Syntax |
|---|---|
| 1. List | b) [ ] |
| 2. Tuple | c) ( ) |
| 3. Set | d) { } with single elements |
| 4. Dictionary | a) {key: value} |
5Match the dictionary methods with their descriptions.
| Column A | Column 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 |
| Method | Description |
|---|---|
| 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?
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.
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?
- 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.
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.
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?
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.
match variable:
case pattern1:
# code block
case pattern2:
# code block
case _:
# default blockday = "Monday"
match day:
case "Monday":
print("Start of the week")
case "Friday":
print("Weekend is near")
case _:
print("Regular day")Output
Start of the week8What is looping? Why is it used?
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.
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.
- Python looks at the first item in the sequence.
- It assigns that item to the loop variable.
- It runs the code inside the loop.
- It moves to the next item and repeats.
- When all items are processed, the loop ends.
11Write a program to print each character of a string using a for loop.
word = "hello"
for letter in word:
print(letter)Output
h
e
l
l
o12What is the range() function? Write its syntax.
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
513What is a nested loop? Give an example.
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 = 914Distinguish between break and continue.
| break | continue |
|---|---|
| Stops the loop immediately when a condition is met | Skips the current iteration and moves to the next one |
| Prevents unnecessary iterations | Allows selective execution without ending the loop |
| Example: stops at 5, prints 1 2 3 4 | Example: skips 3, prints 1 2 4 5 |
15Write a program to demonstrate the break statement.
for num in range(1, 10):
if num == 5:
break
print(num)Output
1
2
3
4The loop stops when num becomes 5, so 5 is not printed.
16Write a program to demonstrate the continue statement.
for num in range(1, 6):
if num == 3:
continue
print(num)Output
1
2
4
5When num is 3, continue skips print(num).
17Write a program to count the vowels in a string.
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: 318Explain the for loop with else using an example.
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 finished19Explain the while loop with its syntax.
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 codecount = 1
while count <= 5:
print("Count is :", count)
count += 1Output
Count is : 1
Count is : 2
Count is : 3
Count is : 4
Count is : 520Differentiate between for loop and while loop.
| for loop | while loop |
|---|---|
| Iterates over a sequence (list, string, range()) | Repeats as long as a condition is True |
| Number of repetitions is known from the sequence | Used when the number of repetitions is not known in advance |
| Loop variable is updated automatically | Loop 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?
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 True22Explain the use of break in a while loop with an example.
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 += 1Output
1
2
3
4
523Explain the use of continue in a while loop with an example.
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
624Explain the while loop with else clause.
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 finished25What is a nested while loop? Give an example.
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 += 1Output
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 226List some practical applications of the while loop.
- 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.
- 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.
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.
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
cherry30What is list slicing? Give an example.
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.
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.
- 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.
- 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).
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']
235How do you find the length of a list and loop through it?
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 += 1Output
3
apple
banana
cherry
apple
banana
cherry36How can you check whether an item exists in a list?
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 list37List the important list methods.
| Method | Description |
|---|---|
| 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.
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?
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
340What is a tuple? Why is it called immutable?
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.
fruits = ("apple", "banana", "cherry") # with parentheses
colors = "red", "green", "blue" # without parentheses
empty = () # empty tuple
single = ("apple",) # single element needs a trailing comma42Differentiate between list and tuple.
| List | Tuple |
|---|---|
| Created with [ ] | Created with ( ) |
| Mutable | Immutable |
| Elements can be added, removed or changed | Contents cannot be changed after creation |
| More flexible | Ideal 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?
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
544What are the tuple methods?
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
245What is a set? Mention its key features.
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.
- 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?
fruits = {"apple", "banana", "cherry"}
colors = set(["red", "green", "blue"]) # set() constructor
empty = set() # NOT {} which creates a dictionary48Explain the methods for adding and removing elements in a set.
- 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.
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 differenceOutput
{1, 2, 3, 4, 5}
{3}
{1, 2}
{1, 2, 4, 5}50Explain union and intersection of sets with examples.
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?
Use issubset().
x = {1, 2}
y = {1, 2, 3, 4}
print(x.issubset(y))Output
True52Write a program to remove duplicates from a list using a set.
names = ["Alice", "Bob", "Alice", "Charlie"]
unique_names = set(names)
print(sorted(unique_names))Output
['Alice', 'Bob', 'Charlie']53List the important set methods.
| Method | Description |
|---|---|
| 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.
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.
- 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?
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?
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
None58How can dictionary elements be modified?
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.
- 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.
| Keys | Values |
|---|---|
| Must be unique | Can repeat |
| Must be immutable (string, number, tuple) | Can be of any data type |
| Used to access the values | Data stored against a key |
| Example: "name" | Example: "Aryananda" |
61Explain the different methods used in dictionaries.
| Method | Description |
|---|---|
| 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.
i = 1
while i <= 10:
print(i)
i += 1Output
1
2
3
4
5
6
7
8
9
102Write a program to print numbers from 10 to 1 using a while loop.
i = 10
while i >= 1:
print(i)
i -= 1Output
10
9
8
7
6
5
4
3
2
13Write a program that asks the user to enter a password until the correct one is entered.
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted")Output
Enter password: abc
Enter password: hello
Enter password: python123
Access granted4Simulate a simple ATM withdrawal system using a while loop.
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 you5Write a program to print the multiplication table of a number using a for loop.
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 = 506Write a program to print a multiplication table using nested for loops.
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 = 97Write a program to count the vowels in a string.
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: 88Write a program to find the sum of the numbers from 1 to 10 using a for loop.
total = 0
for i in range(1, 11):
total += i
print("Sum =", total)Output
Sum = 559Create a list of 5 fruits and print them using a loop.
fruits = ["apple", "banana", "cherry", "orange", "grape"]
for fruit in fruits:
print(fruit)Output
apple
banana
cherry
orange
grape10Write a program to find the largest number in a list.
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.
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.
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.
students = [["Anu", 85], ["Biju", 90], ["Diya", 78]]
print(students[1])
print(students[2][0])
print(students[0][1])Output
['Biju', 90]
Diya
8514Write a program to find the average of the marks in a list.
marks = [85, 90, 78, 92]
average = sum(marks) / len(marks)
print("Average marks:", average)Output
Average marks: 86.2515Create a shopping list using append().
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.
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.
fruits = {"apple", "banana", "cherry", "orange", "grape"}
fruits.add("kiwi")
print(sorted(fruits))
print(len(fruits))Output
['apple', 'banana', 'cherry', 'grape', 'kiwi', 'orange']
618Write a program to remove duplicates from a list using a set.
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.
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.
x = {1, 2}
y = {1, 2, 3, 4}
print(x.issubset(y))
print(y.issubset(x))Output
True
False21Create a set and then remove an element using discard().
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.
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.
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.
student = {"name": "Anu", "age": 17, "class": "XI"}
for key in student:
print(key, ":", student[key])Output
name : Anu
age : 17
class : XIPart FLong Answer Questions
1Explain the conditional statements in Python with examples.
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 near2Explain the for loop in Python with the range() function, nested loops, break, continue and else.
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
43Explain the while loop in Python with examples of break, continue and else.
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
44Explain lists in Python: characteristics, creation, indexing, slicing, adding and removing elements.
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']
55Explain tuples in Python and compare them with lists.
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.
| List | Tuple |
|---|---|
| [ ] | ( ) |
| Mutable | Immutable |
| Many methods | count(), index() |
| More memory | Less memory, slightly faster |
6Explain sets in Python: characteristics, methods and set operations.
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.
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.
| Property | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Definition | Ordered collection of items | Ordered, immutable collection | Unordered collection of unique items | Collection of key-value pairs |
| Syntax | [ ] | ( ) | { } | {key: value} |
| Mutable | Yes | No | Yes | Yes |
| Ordered (Python 3.7+) | Yes | Yes | No | Yes |
| Indexed | Yes | Yes | No | No (access via keys) |
| Duplicates | Allowed | Allowed | Not allowed | Keys: no; values: yes |
| Element access | By index | By index | Not allowed | By key |
| Use case | General-purpose collection | Fixed collections | Unique items, set operations | Structured data, key-value mapping |
| Common methods | append(), 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.
| for loop | while loop |
|---|---|
| Iterates over a sequence | Repeats while a condition is True |
| Used when the number of repetitions is known | Used when it is not known in advance |
| Loop variable updated automatically | Loop variable must be updated by the programmer |
| Less chance of infinite loop | Can 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 += 1Output
for: 1
for: 2
for: 3
while: 1
while: 2
while: 3