KnowledgeBoat Logo
|
OPEN IN APP

Chapter 8

Control Structures in Python

Class 9 - KIPS Robotics & AI



Activity 8.1

Question 1

Check that the following code snippet will execute properly or not. Justify your answer.

a=10 
b=25 
if a<b: 
print("a is less than b") 
else: 
print("b is less than a")

Answer

Output: No output

Justification: The given code snippet will not execute properly because of incorrect indentation. In Python, it is mandatory to indent the statements inside the if and else blocks. If the statements under the if condition are not indented, Python will display an IndentationError and the program will not run. Since the print() statements are not indented under if and else, the code is syntactically incorrect.

Activity 8.2

Question 1

What would be the output of following code snippet:

a = [1, 2, 3, 4, 5] 
b = [2, 2, 2, 2, 2] 
for i in a: 
    for j in b: 
        k=i+j 
    print(k)

Answer

Output:

3
4
5
6
7
Explanation
  • The outer for loop iterates through each element of list a.
  • For each value of i, the inner for loop iterates through all elements of list b.
  • Inside the inner loop, the value of k is updated as k = i + j. Since all elements of list b are 2, and k is overwritten in every inner iteration, after the inner loop finishes, k holds the value i + 2.
  • The print(k) statement is outside the inner loop but inside the outer loop, so it prints the final value of k for each i.

Iterations:

Outer Loop (i)Inner Loop (j) valuesCalculation (k = i + j)Value Printed
12, 2, 2, 2, 23, 3, 3, 3, 33
22, 2, 2, 2, 24, 4, 4, 4, 44
32, 2, 2, 2, 25, 5, 5, 5, 55
42, 2, 2, 2, 26, 6, 6, 6, 66
52, 2, 2, 2, 27, 7, 7, 7, 77

State True or False

Question 1

In Python, an 'if-elif-else' can be used to implement the 'switch-case' paradigm.

Answer

True

Reason — In Python, the if-elif-else statement allows checking multiple conditions one after another, which performs the same role as a switch-case statement by executing different blocks of code based on different conditions.

Question 2

In Python, 'elif' and 'else' can be used interchangeably.

Answer

False

Reasonelif is used to check an additional condition, whereas else does not check any condition and is executed only when all the preceding if and elif conditions evaluate to false. Therefore, elif and else cannot be used interchangeably.

Question 3

The 'while' loop is suitable to iterate sequence data type.

Answer

False

Reason — The while loop is used when the number of iterations is not known beforehand and it works based on a condition, whereas sequence data types are iterated using the for loop.

Question 4

In Python, 'continue' and 'pass' keywords are interchangeable.

Answer

False

Reason — The continue statement is used to skip the current iteration of a loop and transfer the control to the beginning of the loop for the next iteration, whereas the pass statement is a null statement that does nothing and is used only as a placeholder to make the code syntactically correct. Therefore, the continue and pass keywords are not interchangeable.

Question 5

The 'for' loop uses membership operator 'in'.

Answer

True

Reason — The for loop in Python uses the membership operator in to check the presence of a value in a sequence and to iterate over each element of that sequence one by one.

Question 6

The function of the 'continue' and 'break' statements is the same.

Answer

False

Reason — The break statement terminates the loop immediately and transfers the control outside the loop, whereas the continue statement skips the current iteration and transfers the control to the next iteration of the loop. Therefore, their functions are not the same.

Question 7

In Python, you cannot create an empty 'for' loop.

Answer

False

Reason — In Python, an empty for loop can be created by using the pass statement. The pass statement acts as a null statement and allows the loop body to remain empty while keeping the syntax correct. Therefore, it is possible to create an empty for loop in Python.

Question 8

The 'while' loop can be used to create an infinite loop.

Answer

True

Reason — The while loop executes as long as the given condition evaluates to True. If the condition never becomes False, the loop will continue to execute indefinitely, thereby creating an infinite loop.

Question 9

A loop inside a loop is called nested loop.

Answer

True

Reason — A loop that is written inside the body of another loop is called a nested loop, where one loop (inner loop) executes completely for each iteration of the outer loop.

Question 10

In Python, 'elif' can be used without 'if'.

Answer

False

Reason — The elif statement cannot be used independently. It must always be used after an if statement to check an additional condition.

Select the correct option

Question 1

Which of the following keywords is not used in conditional statements?

  1. if
  2. else
  3. elif
  4. go

Answer

go

Reason — The keywords used in Python conditional statements are if, else, and elif. The keyword go is not a conditional keyword in Python.

Question 2

What will be the output of the following statement for any two values of a & b entered by the user?

print(a) if a>b else print(b)

  1. It will give an error
  2. It will print the largest number
  3. It will print the smallest number
  4. None of these

Answer

It will print the largest number

Reason — This is a shorthand if-else statement. If the condition a > b is true, the value of a is printed, otherwise, the value of b is printed. Therefore, the larger of the two numbers is printed.

Question 3

Which of the following is the correct sequence to create multiple conditional statements?

  1. if else else
  2. if elif else
  3. if else elif
  4. if else if

Answer

if elif else

Reason — In Python, when we need to check more than one condition, we use the if-elif-else statement. The if statement checks the first condition, the elif statement checks the next condition, and the else statement is executed when none of the conditions are true. Therefore, the correct sequence to create multiple conditional statements is if elif else.

Question 4

Which logical operator(s) is/are used to combine multiple conditions in 'if' statement?

  1. and
  2. or
  3. not
  4. both a and b

Answer

both a and b

Reason — In Python, the logical operators and and or are used to combine multiple conditions in an if statement. The and operator checks if all conditions are true, while the or operator checks if any one of the conditions is true.

Question 5

The function of 'else' in 'if-else' statement is:

  1. to execute the block of statements when the condition is True
  2. to execute the block of statements when the condition is False
  3. to specify an alternative condition
  4. None of these

Answer

to execute the block of statements when the condition is False

Reason — In an if-else statement, when the condition written in the if statement evaluates to False, the else block is executed. Thus, the function of else is to execute the block of statements when the condition is False.

Question 6

How many conditions can be checked using the if-elif-elif-else statement?

  1. One
  2. Two
  3. Three
  4. Four

Answer

Three

Reason — The if-elif-elif-else statement consists of one if condition and two elif conditions, allowing three conditions to be checked. The else part does not check any condition, it executes when all the conditions are false. Therefore, the correct answer is Three.

Question 7

In Python, what would be the condition to check if a value is not equal to 5?

  1. x =! 5
  2. x != 5
  3. x not= 5
  4. x == 5

Answer

x != 5

Reason — In Python, the != operator is the not equal to comparison operator. It is used to check whether two values are not equal. Therefore, the correct condition to check if a value is not equal to 5 is x != 5.

Question 8

In Python, which keyword is used to terminate a loop immediately?

  1. exit
  2. return
  3. break
  4. continue

Answer

break

Reason — The break keyword is used to terminate a loop immediately and transfer the control outside the loop.

Question 9

From the following, which is not a comparison operator in Python?

  1. ==
  2. !=
  3. >=
  4. <>

Answer

<>

Reason — In Python, the valid comparison operators include ==, !=, and >=. The symbol <> is not a comparison operator in Python.

Question 10

What would be the result of the following expression?

15 > 12 and 2 < 1

  1. True
  2. False
  3. Error
  4. None of these

Answer

False

Reason — The expression contains the logical operator and, which returns True only if both conditions are true.

= 15 > 12 and 2 < 1
= True and False
= False

Fill blanks

Question 1

Fill in the blanks:

  1. ................ is used to repeat a block of code until a certain condition is met.
  2. ................ statement in a loop is used to break the execution of the loop.
  3. ................ keyword is used to create an empty loop.
  4. ................ statement is used to skip the current iteration of the loop and move to the next.
  5. ................ loop is used to iterate over a sequence of items.

Answer

  1. while loop is used to repeat a block of code until a certain condition is met.
  2. break statement in a loop is used to break the execution of the loop.
  3. pass keyword is used to create an empty loop.
  4. continue statement is used to skip the current iteration of the loop and move to the next.
  5. for loop is used to iterate over a sequence of items.

Short answer type questions

Question 1

Explain the use of break statement in Python with the help of an example.

Answer

The break statement in Python is used to terminate a loop immediately and transfer the control outside the loop, even if the loop condition is still true.

Example:

numbers = [1, 2, 3, 4, 5]

for n in numbers:
    if n == 4:
        break
    print(n)
print("The end")

Output:

1
2
3
The end

In this example, the loop iterates through the list numbers. When the value 4 is encountered, the break statement is executed, which stops the loop immediately and the control comes out of the loop. After the loop ends, the statement print("The end") is executed.

Question 2

Write a program to find the smallest number among three numbers by using the nested 'if-else' statements.

Solution
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a < b:
    if a < c:
        print("Smallest number is:", a)
    else:
        print("Smallest number is:", c)
else:
    if b < c:
        print("Smallest number is:", b)
    else:
        print("Smallest number is:", c)
Output
Enter first number: 5
Enter second number: 8
Enter third number: 3
Smallest number is: 3

Question 3

Write a Python program to check that if a given number is even or odd.

Solution
num = int(input("Enter a number: "))

if num % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")
Output
Enter a number: 82
The number is even.

Enter a number: 51
The number is odd.

Question 4

Write a Python program to add all the elements of a tuple.

Solution
t = (10, 20, 30, 40)
s = 0
for i in t:
    s = s + i
print("Sum of elements of the tuple is:", s)
Output
Sum of elements of the tuple is: 100

Long answer type questions

Question 1

Write a program to delete/remove all the numbers less than 10 from the list.

Solution
numbers = [5, 12, 3, 20, 8, 15, 2, 30]
new_list = []

for i in numbers:
    if i >= 10:
        new_list.append(i)

print("List after removing numbers less than 10:", new_list)
Output
List after removing numbers less than 10: [12, 20, 15, 30]

Question 2

Write a Python program to find the largest element in a tuple.

Solution
t = (12, 45, 7, 89, 34)
largest = t[0]

for i in t:
    if i > largest:
        largest = i

print("The largest element in the tuple is:", largest)
Output
The largest element in the tuple is: 89

Question 3

Write a Python program to find the square of all elements between 1 to 20.

Solution
for i in range(1, 21):
    print(i * i)
Output
1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
400

Question 4

Write a Python program to demonstrate the use of the if-elif-else statements.

Solution
num = 4

if num == 1:
    print("Red")
elif num == 2:
    print("Blue")
elif num == 3:
    print("Green")
elif num == 4:
    print("Yellow")
elif num == 5:
    print("Orange")
else:
    print("Invalid input")
Output
Yellow

Higher Order Thinking Skills (HOTS)

Question 1

Write a python program to print a pyramid using 'for' loop.

Solution
rows = 5

for i in range(1, rows + 1):
    for j in range(rows - i):
        print(" ", end="")
    for k in range(1, 2 * i):
        print("*", end="")
    print()
Output
    *
   ***
  *****
 *******
*********

Question 2

Write a program to store marks of your class students and show their percentage.

Solution
n = int(input("Enter number of students: "))
max_marks = int(input("Enter maximum marks: "))

names = []
percentages = []

for i in range(n):
    name = input("Enter student name: ")
    marks = int(input("Enter total marks: "))
    percentage = (marks / max_marks) * 100

    names.append(name)
    percentages.append(percentage)

print("\nStudent Name and Percentage")
for i in range(n):
    print(names[i], "-", percentages[i], "%")
Output
Enter number of students: 3
Enter maximum marks: 300
Enter student name: Asha
Enter total marks: 250
Enter student name: Ravi
Enter total marks: 208
Enter student name: Neha
Enter total marks: 290

Student Name and Percentage
Asha - 83.33333333333334 %
Ravi - 69.33333333333334 %
Neha - 96.66666666666667 %

Question 3

Write a program to implement a simple shopping cart system. In it user can add items, remove items, view the cart, and calculate the total cost.

Solution
cart = []
price = []
choice = 0

while choice != 5:
    print("1. Add item")
    print("2. Remove item")
    print("3. View cart")
    print("4. Calculate total cost")
    print("5. Exit")

    choice = int(input("Enter your choice: "))

    if choice == 1:
        item = input("Enter item name: ")
        cost = int(input("Enter item price: "))
        cart.append(item)
        price.append(cost)
        print("Item added to cart")

    elif choice == 2:
        item = input("Enter item name to remove: ")
        if item in cart:
            index = cart.index(item)
            cart.pop(index)
            price.pop(index)
            print("Item removed from cart")
        else:
            print("Item not found")

    elif choice == 3:
        print("Items in cart:")
        for i in range(len(cart)):
            print(cart[i], "-", price[i])

    elif choice == 4:
        total = 0
        for p in price:
            total = total + p
        print("Total cost:", total)

    elif choice == 5:
        print("Thank you for shopping")

    else:
        print("Invalid choice")
Output
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 1
Enter item name: Pen
Enter item price: 50
Item added to cart
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 1
Enter item name: Book
Enter item price: 100
Item added to cart
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 1
Enter item name: Pencil
Enter item price: 15
Item added to cart
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 2
Enter item name to remove: Pen
Item removed from cart
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 3
Items in cart:
Book - 100
Pencil - 15
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 4
Total cost: 115
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 5
Thank you for shopping

Question 4

Write a program that inputs two tuples and creates a third one that contains all the elements of the first tuple followed by all the elements of the second tuple.

Solution
tuple1 = eval(input("Enter first tuple: "))
tuple2 = eval(input("Enter second tuple: "))
tuple3 = tuple1 + tuple2
print("First tuple:", tuple1)
print("Second tuple:", tuple2)
print("Combined tuple:", tuple3)
Output
Enter first tuple: (1, 2, 3)
Enter second tuple: (4, 5, 6)
First tuple: (1, 2, 3)
Second tuple: (4, 5, 6)
Combined tuple: (1, 2, 3, 4, 5, 6)

Question 5

Write a program to print the longest word in the given list of words.

Solution
words = ["apple", "banana", "grapes", "watermelon", "kiwi"]

longest = words[0]

for w in words:
    if len(w) > len(longest):
        longest = w

print("The longest word is:", longest)
Output
The longest word is: watermelon
PrevNext