0% found this document useful (0 votes)
4 views

Chapter 6

Chapter 6 discusses the flow of control in Python programming, including concepts such as sequence, selection, and repetition. It covers control structures like if statements, loops, and the importance of indentation, along with examples demonstrating their usage. The chapter also includes multiple-choice questions to reinforce understanding of these concepts.

Uploaded by

motivekannada08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter 6

Chapter 6 discusses the flow of control in Python programming, including concepts such as sequence, selection, and repetition. It covers control structures like if statements, loops, and the importance of indentation, along with examples demonstrating their usage. The chapter also includes multiple-choice questions to reinforce understanding of these concepts.

Uploaded by

motivekannada08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

CHAPTER 6 FLOW OF CONTROL

CHAPTER BLUEPRINT PLAN FOR FINAL EXAM

R
L
VSA 1 MARK SA 2 MARKS LA 3 MARKS ESSAY 5 MARKS TOTAL

N
1 MCQ 1 NIL 1 08 MARKS

EE
CHAPTER SYNOPSIS
H
AT
Introduction
M

• Concept of Sequence: Programs execute statements in order, from beginning to end.


• Flow of Control: The order in which statements are executed in a program.
• Control Structures: Python supports selection and repetition to control the flow of the program.
ED

Example: Program 6-1


M

# Program to print the difference of two input numbers


num1 = int(input("Enter first number: "))
M

num2 = int(input("Enter second number: "))


diff = num1 - num2
A

print("The difference of", num1, "and", num2, "is", diff)


H

Explanation: This program takes two integer inputs from the user, calculates their difference, and prints the
O

result. It demonstrates a simple sequence of operations: input, calculation, and output.


M

Selection

• if Statement: Executes a block of code if the condition is true.

• Syntax:

if condition:
statement(s)

183
August 24, 2024

**Example: Voting Eligibility**

```python
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")

R
Explanation: This program checks if the user’s age is 18 or above to determine voting eligibility. If the condition

L
(age >= 18) is true, it prints “Eligible to vote”; otherwise, it prints “Not eligible to vote.”

N
• if..else Statement: Provides two paths based on whether the condition is true or false.

EE
• Syntax:

if condition:
statements-1
H
AT
else:
statements-2
M

Example: Positive Difference (Program 6-2)

# Program to print the positive difference of two numbers


ED

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
if num1 > num2:
M

diff = num1 - num2


else:
M

diff = num2 - num1


print("The difference of", num1, "and", num2, "is", diff)
A

Explanation: This program calculates the positive difference between two input numbers by comparing them
H

and subtracting the smaller number from the larger one. It demonstrates the use of an if..else statement to
O

choose between two actions.


M

• if..elif..else Statement: Checks multiple conditions.

• syntax:

if condition1:
statements-1
elif condition2:
statements-2
.

184 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

.
.
elif condition-n:
statements-n
else:
statements-else

‘ Example: Simple Calculator (Program 6-3)

R
# Program to create a four function calculator
result = 0
val1 = float(input("Enter value 1: "))

L
val2 = float(input("Enter value 2: "))

N
op = input("Enter any one of the operator (+,-,*,/): ")
if op == "+":

EE
result = val1 + val2
elif op == "-":
result = val1 - val2
elif op == "*":
H
AT
result = val1 * val2
elif op == "/":
if val2 == 0:
M

print("Error! Division by zero is not allowed. Program terminated")


else:
ED

result = val1 / val2


else:
print("Wrong input, program terminated")
M

print("The result is", result)

_Explanation: This program performs basic arithmetic operations (+, -, *, /) on two input numbers based on the
M

user’s choice of operator. It demonstrates the use of if..elif..else statements to handle multiple conditions._
A
H

Indentation
O

• Indentation: Python uses indentation to define blocks of code. Proper indentation is crucial to avoid
M

syntax errors.

Example: Larger Number (Program 6-4)

# Program to find the larger of the two numbers


num1 = 5
num2 = 6
if num1 > num2:
print("First number is larger")
print("Bye")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 185


August 24, 2024

else:
print("Second number is larger")
print("Bye Bye")

Explanation: This program compares two numbers and prints which one is larger. The example emphasizes the
importance of indentation in Python to define blocks of code within if and else statements.

Repetition

R
• Iteration: Repetition of a set of statements using looping constructs.
• For Loop: Executes a block of code a specific number of times.

L
• Syntax:

N
for variable in range or sequence:

EE
statements

Example: For Loop (Program 6-6)


H
AT
# Print the characters in word PYTHON using for loop
for letter in 'PYTHON':
print(letter)
M

Explanation: This program uses a for loop to iterate over each character in the string ‘PYTHON’ and prints
them. It demonstrates the basic usage of the for loop.
ED

Example: Sequence of Numbers (Program 6-7)

# Print the given sequence of numbers using for loop


M

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


for num in count:
M

print(num)
A

Explanation: This program iterates over a list of numbers and prints each number. It shows how the for loop
H

can be used to traverse elements in a list.


O

Example: Even Numbers (Program 6-8)


M

# Print even numbers in the given sequence


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if (num % 2) == 0:
print(num, 'is an even number')

Explanation: This program checks each number in the list to see if it’s even and prints the even numbers. It
combines a for loop with an if statement to filter elements based on a condition.

Example: Multiples of 10 (Program 6-9)

186 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

# Print multiples of 10 for numbers in a given range


for num in range(5):
if num > 0:
print(num * 10)

Explanation: This program prints the multiples of 10 for numbers from 1 to 4 using the range function in a for
loop. It demonstrates how to use the range function to generate a sequence of numbers.

range() Function

R
• range() Function: Generates a sequence of numbers. Useful for looping a specific number of times.

L
• Syntax:

N
range(start,stop,step)

EE
Example: Range Function (Program 6-10)

# Using range function in a for loop


for i in range(1, 6): H
AT
print(i)
M

Explanation: This program uses the range function to print numbers from 1 to 5. The range function generates
a sequence of numbers from 1 to 5, which the for loop iterates over.
ED

Example: Reverse Range (Program 6-11)

# Using range function to generate a reverse sequence


for i in range(5, 0, -1):
M

print(i)
M

Explanation: This program prints numbers from 5 to 1 in reverse order using the range function with a negative
A

step. It demonstrates how the range function can be customized to generate sequences with different steps.
H

while Loop
O
M

• while Loop: Executes a block of code as long as the condition is true. Useful for situations where the
number of iterations is not known in advance.
• Syntax:

while condition:
statements

Example: Counting Down (Program 6-12)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 187


August 24, 2024

i = 5
while i > 0:
print(i)
i -= 1

Explanation: This program uses a while loop to count down from 5 to 1. The loop continues to execute as long
as the condition (i > 0) is true.
Example: Sum of First N Natural Numbers (Program 6-13)
# Using while loop to find sum of first n natural numbers

R
n = int(input("Enter a number: "))
sum = 0

L
i = 1
while i <= n:

N
sum += i

EE
i += 1
print("Sum of first", n, "natural numbers is", sum)

H
Explanation: This program calculates the sum of the first n natural numbers using a while loop. The loop
iterates from 1 to n, adding each number to the sum.
AT
break and continue Statements
M

• break Statement: Terminates the loop prematurely. Useful for breaking out of a loop based on a condi-
ED

tion.

Example: break Statement (Program 6-14)


M

# Using break statement in a loop


for i in range(1, 11):
M

if i == 6:
break
A

print(i)
H

Explanation: This program uses a for loop to print numbers from 1 to 10 but breaks out of the loop when i
O

equals 6. The break statement exits the loop when the condition (i == 6) is met.
M

• continue Statement: Skips the current iteration and continues with the next. Useful for skipping specific
iterations based on a condition.

Example: continue Statement (Program 6-15)


# Using continue statement in a loop
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)

188 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

Explanation: This program uses a for loop to print odd numbers from 1 to 10 by skipping even numbers. The
continue statement skips the current iteration if the condition (i % 2 == 0) is true.

Nested Loops

A loop inside another loop. Useful for iterating over multi-dimensional structures like matrices

Example: Nested for Loop (Program 6-16)

# Using nested for loops to print a pattern

R
for i in range(1, 4):
for j in range(1, 4):

L
print(i, j)

N
Explanation: This program demonstrates nested loops by printing pairs of numbers from 1 to 3.

EE
Example: Multiplication Table (Program 6-17)

# Using nested loops to print multiplication table


for i in range(1, 6):
for j in range(1, 6): H
AT
print(i * j, end=' ')
print()
M

Explanation: This program uses nested loops to print a multiplication table from 1 to 5.
ED

Multiple Choice Questions


M

1. What is the order of execution of statements in a program called?

a) Execution flow
M

b) Control flow
A

c) Flow of control
H

d) Program sequence
O

Answer: c) Flow of control


M

2. Which control structures does Python support for flow of control?

a) Sequence and iteration

b) Selection and iteration

c) Selection and repetition

d) Sequence and selection

Answer: c) Selection and repetition

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 189


August 24, 2024

3. How does Python group statements into a single block of code?

a) Curly brackets

b) Parentheses

c) Indentation

d) Semicolon

Answer: c) Indentation

R
4. What is used to implement decision-making in Python?

L
a) for loop

b) if..else statement

N
c) while loop

EE
d) switch statement

Answer: b) if..else statement


H
AT
5. What does the break statement do in a loop?

a) Skips an iteration
M

b) Repeats the current iteration

c) Exits the loop


ED

d) Restarts the loop

Answer: c) Exits the loop


M

6. What is the purpose of the continue statement?


M

a) Exits the loop


A

b) Skips the current iteration


H

c) Restarts the loop


O

d) Ends the program


M

Answer: b) Skips the current iteration

7. What is a loop inside another loop called?

a) Recursive loop

b) Nested loop

c) Inner loop

d) Infinite loop

190 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

Answer: b) Nested loop

8. Which of the following is a correct example of a nested loop in Python?

a) ‘for i in range(3): for j in range(2): print(j)‘

b) ‘for i in range(3) { for j in range(2) { print(j) } }‘

c) ‘for (i in range(3)) (for j in range(2)) (print(j))‘

d) ‘for i in range(3): { for j in range(2): { print(j) } }‘

R
Answer: a) ‘for i in range(3): for j in range(2): print(j)‘

L
9. What happens if indentation is incorrect in a Python program?

a) Program runs with warnings

N
b) Program skips the indented block

EE
c) Syntax error

d) Indentation error
H
AT
Answer: c) Syntax error

10. How can a block of code be created in Python?


M

a) Using curly brackets ‘{}‘

b) Using indentation
ED

c) Using parentheses ‘()‘

d) Using square brackets ‘[]‘


M

Answer: b) Using indentation


M

11. What is the output of the following code snippet?


A

Python Code:
H

num1 = 5
O

num2 = 6
M

if num1 > num2:

print(“first number is larger”)

print(“Bye”)

else:

print(“second number is larger”)

print(“Bye Bye”)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 191


August 24, 2024

a) Syntax error

b) ‘first number is larger Bye‘

c) ‘second number is larger Bye Bye‘

d) ‘Bye Bye‘

Answer: a) Syntax error

12. What will be the output of the following code?

R
Python Code:

L
for i in range(1, 6):

if i == 3:

N
continue

EE
print(i)

a) 1 2 3 4 5
H
AT
b) 1 2 4 5

c) 1 2 4 5 6
M

d) 2 4 6

Answer: b) 1 2 4 5
ED

13. Which statement is used to skip the rest of the code inside a loop for the current iteration only?

a) break
M

b) pass
M

c) skip
A

d) continue
H

Answer: d) continue
O

14. What type of loop is used in the following code?


M

Python Code:

while True:

print(“Infinite loop”)

a) for loop

b) finite loop

c) infinite loop

192 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

d) nested loop

Answer: c) infinite loop

15. Which of the following is the correct syntax for an if..else statement in Python?

a) ‘if condition: statements else: statements‘

b) ‘if condition { statements } else { statements }‘

c) ‘if (condition): statements; else: statements;‘

R
d) ‘if condition: { statements } else: { statements }‘

Answer: a) ‘if condition: statements else: statements‘

L
18. Which of the following programs will print the sum of all positive numbers entered by the user until

N
a negative number is entered?

EE
a)

Python Code:

sum = 0
H
AT
while True:

num = int(input(“Enter a number:”))


M

if num < 0:
ED

break

sum += num
M

print(“Sum:”, sum)

b)
M

Python Code:
A

sum = 0
H

while True:
O

num = int(input(“Enter a number:”))


M

if num < 0:

continue

sum += num

print(“Sum:”, sum)

c)

Python Code:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 193


August 24, 2024

sum = 0

num = int(input(“Enter a number:”))

while num >= 0:

sum += num

num = int(input(“Enter a number:”))

print(“Sum:”, sum)

R
d)

Python Code:

L
sum = 0

N
while num >= 0:

EE
num = int(input(“Enter a number:”))

if num < 0:

break H
AT
sum += num
M

print(“Sum:”, sum)

Answer: a)
ED

Python Code:

sum = 0
M

while True:
M

num = int(input(“Enter a number:”))

if num < 0:
A

break
H

sum += num
O

print(“Sum:”, sum)
M

19. In a nested loop, how many times will the inner loop execute if the outer loop runs 3 times and the
inner loop runs 2 times each iteration?

a) 3

b) 6

c) 2

d) 5

194 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

Answer: b) 6

20. How is a block of code indicated in Python?

a) By using curly brackets

b) By using parentheses

c) By using indentation

d) By using semicolons

R
Answer: c) By using indentation

L
21. What type of error will you get if the indentation is not consistent in Python?

a) Logical error

N
b) Syntax error

EE
c) Runtime error

d) Semantic error
H
AT
Answer: b) Syntax error

22. What will be the output of the following code?


M

Python Code:

for i in range(5):
ED

if i == 2:

continue
M

print(i)
M

a) 0 1 2 3 4
A

b) 1 2 3 4 5
H

c) 0 1 3 4
O

d) 0 1 3 4 5
M

Answer: c) 0 1 3 4

23. How can the flow of control be altered in a program?

a) Using operators

b) Using control structures

c) Using functions

d) Using variables

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 195


August 24, 2024

Answer: b) Using control structures

24. What does the else part of an if statement represent?

a) Code that runs if the condition is false

b) Code that runs if the condition is true

c) A secondary condition

d) An error handling block

R
Answer: a) Code that runs if the condition is false

L
25. What does the following code do?

Python Code:

N
x=5

EE
y = 10

if x < y:
H
AT
print(“x is less than y”)

else:
M

print(“x is not less than y”)

a) Prints “x is not less than y”


ED

b) Prints “x is less than y”

c) Prints nothing
M

d) Syntax error
M

Answer: b) Prints “x is less than y”


A

26. What is the purpose of an infinite loop?


H

a) To iterate a fixed number of times


O

b) To loop until a condition is met


M

c) To keep running without termination

d) To generate an error

Answer: c) To keep running without termination

27. Which of the following is true about the break statement in a loop?

a) It skips to the next iteration

b) It stops the current iteration and continues with the next

196 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

c) It stops the loop entirely

d) It only works with for loops

Answer: c) It stops the loop entirely

28. What is the output of the following code?

Python Code:

for i in range(4):

R
print(i)

L
if i == 2:

break

N
a) 0 1 2 3

EE
b) 0 1 2

c) 0 1 3
H
AT
d) 0 1

Answer: b) 0 1 2
M

29. How does the continue statement affect a loop’s execution?

a) Terminates the loop


ED

b) Skips the rest of the code inside the loop for the current iteration

c) Repeats the current iteration


M

d) Exits the loop and continues with the next iteration


M

Answer: b) Skips the rest of the code inside the loop for the current iteration
A

30. What is the difference between a for loop and a while loop?
H

a) For loop is used for definite iteration, while loop is used for indefinite iteration
O

b) For loop has a fixed number of iterations, while loop runs indefinitely
M

c) For loop is used for selection, while loop is used for repetition

d) There is no difference

Answer: a) For loop is used for definite iteration, while loop is used for indefinite iteration

31. What will be the output of the following code snippet?

Python Code:

count = 0

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 197


August 24, 2024

while count < 5:

count += 1

print(count)

a) 0 1 2 3 4 5

b) 1 2 3 4 5

c) 0 1 2 3 4

R
d) 1 2 3 4

L
Answer: b) 1 2 3 4 5

32. How many times will the loop run in the following code?

N
Python Code:

EE
for i in range(3):

for j in range(2):
H
AT
print(i, j)

a) 3 times
M

b) 6 times

c) 2 times
ED

d) 5 times

Answer: b) 6 times
M

33. Which statement is used to exit a loop in Python?


M

a) exit
A

b) break
H

c) continue
O

d) stop
M

Answer: b) break

34. What will be the output of the following code?

Python Code:

i=0

while i < 4:

i += 1

198 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

print(i)

if i == 2:

continue

a) 1 2 3 4

b) 1 2 4

c) 1 2 3 4 5

R
d) 1 2 2 3 4

L
Answer: a) 1 2 3 4

35. What is the purpose of a nested loop?

N
a) To create infinite loops

EE
b) To break out of a loop

H
c) To perform repeated operations on each element of a sequence
AT
d) To skip iterations in a loop

Answer: c) To perform repeated operations on each element of a sequence


M

36. Which statement correctly describes the functionality of break and continue in Python?

a) break terminates the loop, continue skips the current iteration


ED

b) break skips the current iteration, continue terminates the loop

c) break and continue both terminate the loop


M

d) break and continue both skip the current iteration


M

Answer: a) break terminates the loop, continue skips the current iteration
A

37. What is the output of the following code?


H

Python Code:
O

for i in range(3):
M

for j in range(2):

if j == 1:

break

print(i, j)

a) 0 0 0 1 1 0 1 1 2 0 2 1

b) 0 0 1 0 2 0

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 199


August 24, 2024

c) 0 0 0 1 1 0 2 0 2 1

d) 0 0 1 0 1 1 2 0 2 1

Answer: b) 0 0 1 0 2 0

38. Which of the following is a correct syntax for a while loop in Python?

a) ‘while condition: { statements }‘

b) ‘while (condition) { statements }‘

R
c) ‘while condition: statements‘

L
d) ‘while (condition): statements‘

Answer: d) ‘while (condition): statements‘

N
39. What happens when the break statement is executed inside a nested loop?

EE
a) Exits all loops

b) Exits the inner loop only


H
AT
c) Continues with the next iteration of the inner loop

d) Restarts the inner loop


M

Answer: b) Exits the inner loop only

40. Which of the following is the correct syntax for a for loop in Python?
ED

a) ‘for (i in range(5)): print(i)‘

b) ‘for i in range(5): print(i)‘


M

c) ‘for i in range(5) { print(i) }‘


M

d) ‘for (i in range(5)) { print(i) }‘


A

Answer: b) ‘for i in range(5): print(i)‘


H

41. How can you create a block of code in Python?


O

a) Using curly brackets


M

b) Using indentation

c) Using parentheses

d) Using semicolons

Answer: b) Using indentation

42. What is the output of the following code?

Python Code:

200 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

count = 0

while count < 3:

print(count)

count += 1

a) 0 1 2 3

b) 1 2 3

R
c) 0 1 2

L
d) 0 1

Answer: c) 0 1 2

N
43. Which of the following statements will break out of a loop?

EE
a) exit

b) continue
H
AT
c) stop

d) break
M

Answer: d) break

44. What is the purpose of the continue statement in a loop?


ED

a) To terminate the loop

b) To skip the rest of the code inside the loop for the current iteration
M

c) To exit the loop and continue with the next iteration


M

d) To repeat the current iteration


A

Answer: b) To skip the rest of the code inside the loop for the current iteration
H

45. What will be the output of the following code?


O

Python Code:
M

for i in range(3):

for j in range(2):

if j == 1:

break

print(i, j)

print(“Out of nested loop”)

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 201


August 24, 2024

a) 0 0 1 0 2 0 Out of nested loop

b) 0 0 0 1 1 0 2 0 2 1 Out of nested loop

c) 0 0 1 0 2 0 Out of nested loop

d) 0 0 1 0 1 1 2 0 2 1 Out of nested loop

Answer: c) 0 0 1 0 2 0 Out of nested loop

46. What is the output of the following code?

R
Python Code:

L
for i in range(5):

if i == 3:

N
break

EE
print(i)

else:
H
AT
print(“Completed”)

a) 0 1 2 Completed
M

b) 0 1 2

c) 0 1 2 3 4 Completed
ED

d) 0 1 2 3 Completed

Answer: b) 0 1 2
M

47. What is the output of the following code snippet?


M

Python Code:
A

for i in range(2):
H

for j in range(2):
O

print(i, j)
M

a) 0 0 1 0

b) 0 0 1 1

c) 0 0 0 1 1 0 1 1

d) 0 0 1 0 1 1

Answer: c) 0 0 0 1 1 0 1 1

48. Which of the following is true about the for loop?

202 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

a) It runs indefinitely

b) It is used for definite iteration

c) It is used for selection

d) It is used for decision-making

Answer: b) It is used for definite iteration

49. What will be the output of the following code?

R
Python Code:

for i in range(3):

L
if i == 1:

N
break

EE
print(i)

else:

print(“Loop completed”) H
AT
a) 0 1 Loop completed
M

b) 0 Loop completed

c) 0 1
ED

d) 0

Answer: d) 0
M

50. How do you implement a nested loop in Python?


M

a) By placing one loop inside another loop

b) By placing one function inside another function


A

c) By using indentation
H

d) By using a break statement


O

Answer: a) By placing one loop inside another loop


M

2 Marks Questions and Answers

1. What is the flow of control in programming?

• Answer: The flow of control in programming refers to the order in which individual statements,
instructions, or function calls are executed or evaluated. In Python, this can be implemented using
control structures such as selection and repetition .

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 203


August 24, 2024

2. Explain the concept of sequence in Python.

• Answer: In Python, a sequence refers to the execution of statements one after another in a specific
order. This is the simplest form of flow control where the program runs from the beginning to the
end, following the sequence of statements written in the code .

3. Define selection structure in Python.

• Answer: A selection structure in Python is a control structure that allows the execution of certain

R
parts of the code based on the evaluation of a condition. The primary selection structures are if,
if..else, and if..elif..else statements .

L
4. How is indentation used in Python?

N
• Answer: Indentation in Python is used to define the level of nesting of statements. It is crucial

EE
because it indicates a block of code, such as the body of a function, loop, or conditional statement.
Proper indentation ensures code readability and logical grouping of statements .

5. What is the syntax of an if statement in Python?


H
AT
• Answer: The syntax of an if statement in Python is:
M

if condition:
statement(s)
ED

This structure evaluates the condition, and if it is true, the indented statements are executed .
M

6. Give an example of an if..else statement in Python.


M

• Answer: An example of an if..else statement in Python is:


A

age = 20
H

if age >= 18:


O

print("Eligible to vote")
else:
M

print("Not eligible to vote")

This code checks if the age is 18 or older and prints the appropriate message .

7. What does the elif statement do in Python?

• Answer: The elif statement in Python allows you to check multiple conditions sequentially. It
stands for “else if” and is used to test several conditions one after another, executing the block of
code associated with the first true condition:

204 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

if condition1:
statement(s)
elif condition2:
statement(s)
else:
statement(s)

8. How does Python handle nested if statements?

• Answer: Python handles nested if statements by allowing an if or else statement inside another if

R
or else statement. This enables more complex decision-making processes. For example:

L
num = 10
if num >= 0:

N
if num == 0:
print("Zero")

EE
else:
print("Positive number")
else:
print("Negative number")
H
AT
9. What is the purpose of the break statement in loops?

• Answer: The break statement in Python is used to exit a loop prematurely when a specific condition
M

is met. It is useful for terminating the loop early and transferring control to the statement immediately
following the loop .
ED

10. Explain the use of the continue statement in loops.


M

• Answer: The continue statement in Python is used to skip the current iteration of a loop and proceed
to the next iteration. It is useful for skipping certain conditions without terminating the entire loop .
M

11. How do you implement repetition structures in Python?


A

• Answer: Repetition structures in Python are implemented using loops, such as for loops and while
H

loops. These structures allow a block of code to be executed repeatedly based on a condition or a
sequence of values .
O
M

12. What are the two types of control structures supported by Python?

• Answer: The two types of control structures supported by Python are selection and repetition. Se-
lection structures include if, if..else, and if..elif..else statements, while repetition structures include
for and while loops .

13. Describe a scenario where a selection structure would be used.

• Answer: A selection structure would be used in a scenario where a decision needs to be made based
on a condition. For example, determining if a user is eligible to vote based on their age:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 205


August 24, 2024

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


if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")

14. How does Python ensure code is properly indented?

• Answer: Python enforces proper indentation by treating the level of indentation as part of its syntax.
Improper indentation will result in a syntax error, ensuring that the code blocks are clearly defined

R
and organized .

L
15. How do you read input from the user in Python?

N
• Answer: To read input from the user in Python, you use the input() function. For example:

EE
name = input("Enter your name: ")
print("Hello, " + name)

H
16. What is the importance of the if condition in an if..else structure?
AT
• Answer: The if condition in an if..else structure is crucial because it determines which block of
code will be executed. If the condition is true, the code within the if block is executed; otherwise,
M

the code within the else block is executed .

17. Explain how a simple calculator program can be implemented in Python.


ED

• Answer: A simple calculator program in Python can be implemented using if..else statements to han-
dle different operations. For example: “‘python num1 = float(input(“Enter first number:”)) num2
M

= float(input(“Enter second number:”)) operation = input(“Enter operation (add, subtract, multiply,


divide):”)
M

if operation == “add”: result = num1 + num2 elif operation == “subtract”: result = num1 - num2 elif operation
A

== “multiply”: result = num1 * num2 elif operation == “divide”: result = num1 / num2 else: result = “Invalid
operation”
H

print(“Result:”, result)
O
M

### 3 Mark Questions and Answers

1. **Write a Python program to find the positive difference between two numbers.**

* **Answer:** Here is a Python program to find the positive difference between two numbers:

```python

206 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

if num1 > num2:


difference = num1 – num2
else:
difference = num2 – num1

print("The positive difference between the two numbers is:", difference)

R
L
2. Describe the role of control structures in Python programming.

• Answer: Control structures in Python programming manage the flow of execution based on condi-

N
tions and loops. They include:

EE
– Selection structures: if, if..else, and if..elif..else statements that execute code blocks based on
boolean conditions.

H
– Repetition structures: for and while loops that repeat code blocks multiple times.
AT
– Control transfer: break, continue, statements that alter the flow within loops and conditional
statements.
M

3. How does indentation affect the execution of a Python program?


ED

• Answer: Indentation in Python:

– Defines blocks of code: Indentation is used to group statements into blocks that form loops,
M

functions, and conditionals.


M

– Ensures readability: Proper indentation makes the code more readable and maintainable.

– Syntax requirement: Python enforces indentation as part of its syntax; incorrect indentation
A

can lead to error and affect the program’s execution flow.


H

4. Explain the concept of nested if statements with an example.


O

• Answer: Nested if statements are if statements inside another if statement. This allows for checking
M

multiple conditions in a hierarchical manner. Example:

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

if num > 0:
print("The number is positive.")
if num % 2 == 0:
print("It is an even number.")
else:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 207


August 24, 2024

print("It is an odd number.")


else:
print("The number is non-positive.")

5. What are the key differences between if, if..else, and if..elif statements?

• Answer: Differences between if, if..else, and if..elif statements:

– if statement: Executes a block of code if a condition is true.

if condition:

R
# code block

L
• if..else statement: Executes a block of code if a condition is true; otherwise, executes another block of

N
code.

EE
if condition:
# code block if condition is true
else:
# code block if condition is false H
AT
• if..elif..else statement: Checks multiple conditions sequentially, executing the corresponding block for
M

the first true condition. The else block executes if no conditions are true.
ED

if condition1:

# code block if condition1 is true


M

elif condition2:
M
A

# code block if condition2 is true


H

else:
O
M

# code block if none of the conditions are true

6. Write a Python program to check if a number is positive, negative, or zero.

• Answer:

num = float(input("Enter a number: "))

if num > 0:
print("The number is positive.")

208 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

elif num < 0:


print("The number is negative.")
else:
print("The number is zero.")

7. Describe the use of logical operators in selection structures.

• Answer: Logical operators in Python (and, or, not) are used in selection structures to combine multiple
conditions:

R
– and: Returns True if all conditions are true. “‘ if condition1 and condition2:

# code block

L
N
* * **or****:** Returns True if at least one condition is true.

EE
if condition1 or condition2:

# code block
H
AT
* **not****:** Inverts the boolean value of a condition.
M

if not condition:

# code block
ED

8. **How can you handle multiple conditions in Python using elif?**


M
M

* **Answer:** Multiple conditions can be handled using elif to create a chain of conditions:
A

```python
H

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


O

if num > 0:
M

print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

9. What is the significance of the else block in an if..else statement?

• Answer: The else block:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 209


August 24, 2024

– Handles all other cases: It executes code when none of the preceding if or elif conditions are
true.

– Provides default actions: Ensures that there is a defined action or output for inputs that don’t
match any specific condition.

10. Explain the concept of loops in Python with an example.

• Answer: Loops in Python are used to execute a block of code repeatedly:

– for loop: Iterates over a sequence (like a list, tuple, or range).

R
for i in range(5):

L
print(i)

N
• while loop: Repeats as long as a condition is true.

EE
i = 0
while i < 5:
print(i)
i += 1
H
AT
11. How does the break statement alter the flow of a loop?

• Answer: The break statement:


M

– Exits the loop prematurely: Immediately terminates the loop when encountered, regardless
ED

of the loop’s condition.

– Used to avoid unnecessary iterations: Helps in cases where the desired outcome is achieved
before the loop completes its natural cycle.
M

– Improves efficiency: Can reduce the number of iterations, making the loop more efficient.
M

– Example: “‘python for i in range(10):


A

if i == 5:
H

break
O

print(i)
M

12. **What is the difference between break and continue statements?**

* **Answer:** Differences between break and continue statements:

* **break:** Exits the loop entirely, stopping any further iterations.


```python
for i in range(10):

210 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

if i == 5:

break

print(i)

# Output: 0, 1, 2, 3, 4

R
• continue: Skips the current iteration and proceeds with the next iteration.

L
for i in range(10):
if i == 5:

N
continue

EE
print(i)
# Output: 0, 1, 2, 3, 4, 6, 7, 8, 9

H
13. Write a Python program to print the first ten natural numbers using a loop.
AT
• Answer:

for i in range(1, 11):


M

print(i)

5 MARKS QUESTIONS
ED

1. Write a Python program to create a simple calculator that performs basic arithmetic operations.
M

result = 0
val1 = float(input("Enter value 1: "))
M

val2 = float(input("Enter value 2: "))


op = input("Enter any one of the operators (+, -, *, /): ")
A

if op == "+":
H

result = val1 + val2


O

elif op == "-":
if val1 > val2:
M

result = val1 - val2


else:
result = val2 - val1
elif op == "*":
result = val1 * val2
elif op == "/":
if val2 == 0:
print("Error! Division by zero is not allowed. Program terminated.")
else:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 211


August 24, 2024

result = val1 / val2


else:
print("Wrong input, program terminated.")

print("The result is:", result)

This program accepts two numbers and an operator from the user, performs the corresponding arithmetic oper-
ation, and handles errors like division by zero.

2. Explain in detail the concept of flow of control with examples.

R
The flow of control refers to the order in which individual statements, instructions, or function calls are executed

L
or evaluated within a program. It is implemented using control structures, which include:

N
• Sequential: Executes statements one after another.

EE
• Selection: Uses conditions to decide which statement to execute (e.g., if, elif, else).

• Repetition: Repeats a block of statements (e.g., for, while).

Example of sequential flow:


H
AT
print("Start")
M

print("Process")

print("End")
ED

Example of selection:
M

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


M

if age >= 18:


A

print("Eligible to vote")
H

else:
O

print("Not eligible to vote")


M

Example of repetition:

for i in range(5):

print(i)

3. How can you implement a nested loop structure in Python? Provide an example.

212 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

A nested loop is a loop within another loop. Python allows any type of loop (for/while) to be nested inside
another loop.

Example of a nested loop:

for i in range(3):

print("Iteration", i+1, "of outer loop")

for j in range(2):

R
print(j + 1)

L
print("Out of inner loop")

N
print("Out of outer loop")

EE
Output:

Iteration 1 of outer loop


H
AT
1

2
M

Out of inner loop

Iteration 2 of outer loop


ED

1
M

Out of inner loop


M

Iteration 3 of outer loop


A

1
H

2
O

Out of inner loop


M

Out of outer loop

This demonstrates how a nested loop works in Python.

4. Describe the importance of control structures in managing the flow of a Python program.

Control structures are essential in programming as they dictate the flow of control through the program, enabling
decision making, looping, and branching. They help in:

• Directing execution: By choosing different paths based on conditions (selection).

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 213


August 24, 2024

• Repeating tasks: By executing a block of code multiple times (repetition).

• Structuring code: By organizing code into logical blocks, making it more readable and maintainable.

Examples include:

• Selection: if, elif, else

• Repetition: for, while

• Branching: break, continue

R
Control structures ensure that programs can handle complex logic and repetitive tasks efficiently, making the

L
code more robust and flexible.

N
5. Write a detailed explanation of the different types of selection structures in Python.

EE
Selection structures allow the execution of specific blocks of code based on certain conditions. Python supports
the following selection structures:

H
1. if statement: Executes a block of code if the condition is true.
AT
if condition:
M

# block of code

2. if..else statement: Executes one block of code if the condition is true and another block if it is false.
ED

if condition:
M

# block of code if true


else:
M

# block of code if false


A

3. if..elif..else statement: Checks multiple conditions in sequence and executes the corresponding block of
H

code for the first true condition.


O
M

if condition1:
# block of code if condition1 is true
elif condition2:
# block of code if condition2 is true
else:
# block of code if none of the above conditions are true

Example:

214 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

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


if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")

This structure allows for complex decision-making processes in programs.

R
6. How does Python handle multiple conditions using if..elif..else? Provide a code example.

Python handles multiple conditions using the if..elif..else statement by checking each condition in sequence. The

L
first condition that evaluates to true will execute its corresponding block of code, and the rest will be skipped.

N
Example:

EE
signal = input("Enter the colour: ")
if signal == "red" or signal == "RED":
print("STOP")
elif signal == "orange" or signal == "ORANGE":
H
AT
print("Be Slow")
elif signal == "green" or signal == "GREEN":
print("Go!")
M

else:
print("Invalid input")
ED

This program takes a traffic signal color as input and prints the corresponding action.

7. Describe the use of loops in Python with examples of for and while loops.
M

Loops in Python are used to execute a block of code repeatedly until a certain condition is met.
M

for loop: Iterates over a sequence (like a list, tuple, dictionary, set, or string).
A

for i in range(5):
H

print(i)
O

Output:
M

while loop: Repeats as long as a condition is true.

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 215


August 24, 2024

count = 0

while count < 5:

print(count)

count += 1

Output:

R
0

L
2

N
3

EE
4

Loops are fundamental for tasks that require repetition, such as processing items in a list, reading lines from a
file, or implementing complex iterative algorithms.
H
AT
9. Write a Python program to print all prime numbers between 1 and 50.

for num in range(2, 51):


M

is_prime = True
for i in range(2, int(num ** 0.5) + 1):
ED

if num % i == 0:
is_prime = False
break
M

if is_prime:
print(num)
M

This program checks each number from 2 to 50 to see if it has any divisors other than 1 and itself, and prints the
A

number if it is prime.
H

11. Explain the role of indentation in Python with multiple examples.


O

Indentation in Python is crucial as it defines the structure and flow of the code. Unlike many other programming
languages that use braces to define blocks of code, Python uses indentation to group statements. Each level of
M

indentation corresponds to a level of nesting. Python will throw an error if the indentation is not consistent. For
example:

num1 = 5
num2 = 6
if num1 > num2: # Block1
print("first number is larger")
print("Bye")
else: # Block2

216 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

print("second number is larger")


print("Bye Bye")

In this example, the correct indentation ensures that the statements under if and else are part of their respective
blocks.

12. Provide a detailed explanation of the continue statement and its applications with examples.

The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration only.
The loop does not terminate but continues with the next iteration. This is useful in situations where you want

R
to avoid executing part of the loop when a certain condition is met but still continue with the loop.

Example:

L
for num in range(2, 10):

N
if num % 2 == 0:

EE
continue

print(num) H
AT
Output:
M

5
ED

9
M

In this example, the loop skips the print statement when the number is even and continues with the next iteration
.
M

15. Write a Python program to simulate a basic login system, validating user input for username and
A

password.
H

correct_username = "admin"
O

correct_password = "password123"
M

username = input("Enter your username: ")

password = input("Enter your password: ")

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 217


August 24, 2024

if username == correct_username and password == correct_password:

print("Login successful!")

else:

print("Invalid username or password")

This program prompts the user to enter a username and password and checks if they match the predefined correct
credentials. If they do, it prints a success message; otherwise, it prints an error message.

R
L
EXERCISES (CHAPTER END QUESTIONS)**

N
1. What is the difference between else and elif construct of if statement?

EE
• The else construct provides an alternative set of statements that execute if none of the preceding if
or elif conditions are true. The elif construct, short for “else if,” allows for additional conditions to

H
be checked if the previous if or elif condition is false. Essentially, elif adds more conditional checks,
AT
while else handles the case where no conditions are met .

2. What is the purpose of the range() function? Give one example.


M

• The range() function in Python is used to generate a sequence of numbers. It is often used in for
loops to iterate over a sequence of numbers. The function can take up to three arguments: start, stop,
ED

and step. For example:

for i in range(0, 10, 2):


M

print(i)
M

This will output: 0 2 4 6 8 In this example, range(0, 10, 2) generates numbers from 0 to 9, incrementing by 2
.
A

3. Differentiate between break and continue statements using examples.


H

• The break statement is used to exit a loop immediately, regardless of the loop’s condition. The
O

continue statement skips the rest of the code inside the loop for the current iteration and moves to
M

the next iteration. Example of break:

for i in range(5):
if i == 3:
break
print(i)

Output: 0 1 2

Example of continue:

218 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

for i in range(5):
if i == 3:
continue
print(i)

Output: 0 1 2 4 In the first example, the loop exits when i is 3. In the second example, the iteration is skipped
when i is 3 .

4. What is an infinite loop? Give one example.

R
• An infinite loop is a loop that never terminates because its condition is always true. This can lead
to a program hanging indefinitely. Example: “‘python while True:

L
print(“This is an infinite loop”)

N
This loop will print "This is an infinite loop" endlessly because the condition True is always

EE
5. **Find the output of the following program segments:**
H
AT
(i)
```python
M

a = 110
while a > 100:
ED

print(a)
a -= 2
M

Output: 110 108 106 104 102 (ii)


M

for i in range(20, 30, 2):


print(i)
A
H

Output: 20 22 24 26 28 (iii)
O

country = 'INDIA'
for i in country:
M

print(i)

Output: I N D I A

(iv)

i = 0
sum = 0
while i < 9:
if i % 4 == 0:

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 219


August 24, 2024

sum = sum + i
i = i + 2
print(sum)

Output: 12 (v)

for x in range(1, 4):


for y in range(2, 5):
if x * y > 10:
break

R
print(x * y)

L
Output: 2 3 4 4 6 8 6 9 (vi)

var = 7

N
while var > 0:

EE
print('Current variable value: ', var)
var = var - 1
if var == 3:
break
H
AT
else:
if var == 6:
var = var - 1
M

continue
print("Good bye!")
ED

Output: Current variable value: 7 Current variable value: 5 Good bye! Current variable value: 4 Good bye!
Current variable value: 3
M

Important Questions
M

1. Define flow of control.


A

2. Mention the two control structures supported by python.


H

3. What is the significance of Indentation in Python?


4. What is Selection Control Structure? Explain its types with syntax and examples in Python.
O

5. What is Repetition Control Structure? Explain its types with syntax and examples in Python.
M

6. Explain if..else statement with syntax and example.


7. Explain if..elif…else statement with syntax and example.
8. Explain for loop structure with syntax and example.
9. Explain while loop structure with syntax and example.
10. Differentiate break and continue statements.
11. What is nested loops? Explain nested loops with syntax and example.
12. What is the difference between else and elif construct of if statement?
13. What is the purpose of range() function? Give one example.

220 L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET.,


August 24, 2024

14. What is an infinite loop? Give one example.

R
L
N
EE
H
AT
M
ED
M
M
A
H
O
M

L R MOHAMMED MATHEEN M.C.A., M.A., B.ED., UGC NET., 221

You might also like