Paper Solution
Paper Solution
(b) Explain the following loops with a flow diagram, syntax, and
suitable examples
Ans:- 1. For Loop : The for loop is used to iterate over a sequence (such
as a list, tuple, string, etc.)
and execute a block of code for each element in the sequence. Here is
the syntax of a for
loop in Python:
for var in sequence:
statement(s)
Example
py_list = ['Apple','Mango','Guava','Pineapple']
i=1
#Iterating over the list
for item in py_list:
print ('Item ',i,' is ',item)
i = i+1
Output:
Item 1 is Apple
Item 2 is Mango
Item 3 is Guava
Item 4 is Pineapple
(c) Explain the continue, break, and pass statements with a suitable
example.
Ans:- In Python, continue, break, and pass are three statements used to
alter the flow of control in loops
and conditional statements.
1. continue: The continue statement is used to skip the current iteration
of a loop and move
on to the next iteration.
Example:
for i in range(1, 11):
if i % 2 == 0:
continue # skip even numbers
print(i)
Output :
1
3
5
7
9
2. break: The break statement is used to exit a loop prematurely, even if
the loop's condition
has not been met.
Example
for i in range(1, 11):
if i == 5:
break # exit loop when i equals 5
print(i)
Output
1
2
3
4
3. pass: The pass statement is used as a placeholder when no action is
required in a block of
code. It is typically used as a placeholder for code that has not yet been
implemented.
Example:
for i in range(1, 11):
if i % 2 == 0:
pass # do nothing for even numbers
else:
print(i)
Output
Copy code
1
3
5
7
9
SECTION C
1. Attempt any one part of the following:
(a) Illustrate Unpacking Sequences, Mutable Sequences, and List
comprehension with examples.
Ans:- Unpacking Sequences:
1. Unpacking sequences is the process of assigning the values of a
sequence (e.g., a tuple, list)
to multiple variables in a single statement. Here's an example:
t = (1, 2, 3)
a, b, c = t
print(a, b, c)
Output :
123
2. Mutable Sequences:
Mutable sequences are sequences (e.g., lists) that can be changed after
they are created.
Here's an example of how to use a list, which is a mutable sequence, to
add or remove
elements:
my_list = [1, 2, 3, 4]
my_list.append(5) # add an element to the end of the list
print(my_list)
my_list.remove(2) # remove an element from the list
print(my_list)
Output
[1, 2, 3, 4, 5]
[1, 3, 4, 5]
3. List Comprehension:
List comprehension is a concise way to create a new list by applying a
transformation to
each element of an existing list. Here's an example:
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]