The flow of control in a program refers to the order in which statements are executed. In Python, there are two main control structures that determine the flow of control: selection and repetition.
1. Introduction to Flow of Control:
2. Selection:
if
statement in Python is used to execute a block of code if a certain condition is true. 3. Indentation:
4. Repetition:
for
loop and the while
loop, to facilitate repetition in programming. 5. Break and Continue Statements:
break
statement is used to terminate a loop prematurely, while the continue
statement skips the current iteration and moves to the next one. 6. Nested Loops:
7. Example Program:
The if statement is used to execute a block of statements based on a condition.
if condition: statement(s)
age = int(input("Enter your age: ")) if age > 18: print("You are eligible to vote.")
The if-else statement is used to execute one block of statements if the condition is true and another block if it is false.
if condition: statement(s) else: statement(s)
age = int(input("Enter your age: ")) if age > 18: print("You are eligible to vote.") else: print("You are not eligible to vote.")
age = int(input("Enter your age "))
if age >= 18: print("Eligible to vote")
A variant of if statement called if..else statement allows us to write two alternative paths and the control condition determines which path gets executed. The syntax for if..else statement is as follows.
if condition:
statement(s)
else:
Let us now modify the example on voting with the condition that if the age entered by the user is greater than 18, then to display that the user is eligible to vote. Otherwise display that the user is not eligible to vote.
age = int(input("Enter your age: "))
if age >= 18: print("Eligible to vote")
else: print("Not eligible to vote")
Now let us use the same concept to modify program 6-1, so that it always gives a positive difference as the output. From the flow chart in Figure 6.2, it is clear that we need to decide whether num1 > num2 or not and take action accordingly.
We have to specify two blocks of statements since num1 can be greater than num2 or vice-versa as shown in program 6-2.
Many a times there are situations that require multiple conditions to be checked and it may lead to many alternatives. In such cases we can chain the conditions using if..elif (elif means else..if).
Computer SCienCe – ClaSS xi
Program 6-2
Program to print the positive difference of two numbers.
#Program 6-2
#Program to print the positive difference of two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
diff = num2 - num1
Enter first number: 5
Enter second number: 6
The difference of 5 and 6 is 1
The syntax for a selection structure using elif is as shown below.
statement(s)
elif condition:
Example 6.2 Check whether a number is positive, negative, or zero.
number = int(input("Enter a number: ")
if number > 0:
print("Number is positive")
elif number < 0:="" />
print("Number is negative")
print("Number is zero")
Example 6.3 Display the appropriate message as per the colour of signal at the road crossing.
signal = input("Enter the colour: ")
if signal == "red" or signal == "RED":
print("STOP")
elif signal == "orange" or signal == "ORANGE":
print("Be Slow")
elif signal == "green" or signal == "GREEN":
print("Go!")
Number of elif is dependent on the number of conditions to be checked. If the first condition is false, then the next condition is checked, and so on. If one of the conditions is true, then the corresponding indented block executes, and the if statement terminates.
Let's create a simple calculator program that can perform basic arithmetic operations on two numbers.
The program should:
Here is a sample program to create a calculator that performs these four basic operations:
# Program to create a four-function calculator result = 0 val1 = float(input("Enter value 1: ")) val2 = float(input("Enter value 2: ")) op = input("Enter any one of the operator (+,-,*,/): ") if op == "+": result = val1 + val2 elif op == "-": if val1 > val2: 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: result = val1/val2 else: print("Wrong input, program terminated") print("The result is ", result)
Example Input and Output:
Example Input:
Enter value 1: 84
Enter value 2: 4
Enter any one of the operator (+,-,*,/): /
Example Output:
The result is 21.0
In this program, for the subtraction (") and division (") operators, there are nested if conditions to handle specific cases. Nested if statements can be used to add multiple levels of conditions within if...else statements.
In most programming languages, statements within a block are enclosed in curly brackets. However, Python uses indentation to define both block and nested block structures. Indentation refers to the leading whitespace (spaces and tabs) at the beginning of a statement. In Python, statements at the same level of indentation are grouped together into a single block of code. The interpreter enforces indentation levels strictly and raises syntax errors if indentation is incorrect.
It is common practice to use a single tab for each level of indentation.
In Program 6-4, the if-else statement contains two blocks of statements, with each block indented by the same amount of spaces or tabs.
# Program to Find the Larger of Two Numbers
num1 = 5
num2 = 6
if num1 > num2:
# Block 1
print("First number is larger")
print("Bye")
# Block 2
else:
print("Second number is larger")
print("Bye Bye")
Repetition, also known as iteration, is a common occurrence in various tasks, such as the monthly payment of an electricity bill. In programming, repetition allows us to execute a set of statements multiple times based on a given condition. This is made possible through looping constructs.
Looping constructs enable the execution of statements repeatedly as long as a specific logical condition remains true. The condition is checked using a variable called the loop's control variable. It is essential for the programmer to ensure that this condition eventually becomes false to avoid creating an infinite loop.
In Python, there are two primary looping constructs: "for" and "while."
For example, consider the task of printing the first five natural numbers:
print(1)
print(2)
print(3)
print(4)
print(5)
count = 1
while count <= 5:="">=>
print(count)
count += 1
This example illustrates how looping makes it easier and more efficient to perform repetitive tasks in programming.
The for statement is utilized to iterate over a sequence of values or a specified range. During each iteration of the loop, the control variable checks whether all the items in the range have been processed. Once all items have been traversed, the statements within the loop are not executed any further, and control is passed to the statement immediately following the for loop.
When using a for loop, the number of iterations is predetermined. The flow of execution in a for loop is depicted in a flowchart, illustrating the process of iterating through a range of values.
(A) Syntax of the For Loop
for variable in sequence :
Program 6-6: Printing Characters in a String using a For Loop
Code:
for letter in 'PYTHON':
print(letter)
Output:
P
Y
T
H
O
N
Program 6-7: Printing Numbers in a Given Sequence using a For Loop
Code:
count = [10, 20, 30, 40, 50]
for num in count:
print(num)
Output:
10
20
30
40
50
Program 6-8: Printing Even Numbers in a Given Sequence using a For Loop
Code:
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')
Output:
2 is an even Number
4 is an even Number
6 is an even Number
8 is an even Number
Note: The body of the loop is indented with respect to the for statement.
The range()
function is a built-in feature in Python. Its syntax is as follows:
range([start], stop[, step])
range()
function must be integers. The step parameter can be either a positive or a negative integer, but it cannot be zero. Example 1: When both start and step are not specified
list(range(10))
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2: When the default step value is 1
list(range(2, 10))
Output: [2, 3, 4, 5, 6, 7, 8, 9]
Example 3: When the step value is specified as 5
list(range(0, 30, 5))
Output: [0, 5, 10, 15, 20, 25]
Example 4: When the step value is -1, generating a decreasing sequence
list(range(0, -9, -1))
Output: [0, -1, -2, -3, -4, -5, -6, -7, -8]
The range()
function is commonly used in for loops to create a sequence of numbers.
Program 6-9: Program to Print Multiples of 10 for Numbers in a Given Range
Code:
for num in range(5): if num > 0: print(num * 10)
The "while" statement repeatedly executes a block of code as long as the control condition remains true. The control condition is checked before any statement inside the loop is executed. After each iteration, the condition is tested again, and the loop continues as long as it is true. When the condition becomes false, the statements in the body of the loop are not executed, and control is transferred to the statement immediately following the loop. If the condition is false from the beginning, the body of the loop is not executed even once.
The statements within the body of the while loop must ensure that the condition eventually becomes false; otherwise, the loop will become an infinite loop, leading to a logical error in the program.
Syntax of while Loop
while test_condition:
body of while
Program 6-10: Printing the First 5 Natural Numbers Using a While Loop
count = 1
while count <= 5:
print(count)
count += 1
Output:
Program 6-11: Finding Factors of a Whole Number Using a While Loop
num = int(input("Enter a number to find its factor: "))
print(1, end=' ') # 1 is a factor of every number
factor = 2
while factor <= num/2:
if num % factor == 0:
print(factor, end=' ')
factor += 1
print(num, end=' ') # every number is a factor of itself
Output: Enter a number to find its factors: 6
1 2 3 6
Note: The body of the loop is indented with respect to the while statement, and the statements within the if condition are indented with respect to the position of the if statement.
Loops are used in programming to repeat tasks, but sometimes we need to modify how these loops work based on certain conditions. In Python, the break and continue statements give us the flexibility to control the flow of loops more precisely.
The break statement is used to exit a loop prematurely. When a break is encountered, the current loop is terminated, and the program continues with the next statement following the loop.
Program 6-12: Using Break Statement in a Loop
In this example, we demonstrate the use of the break statement within a loop.
Code:
num = 0 for num in range(10): num = num + 1 if num == 8: break print('Num has value ' + str(num)) print('Encountered break!! Out of loop')
Output:
Num has value 1 Num has value 2 Num has value 3 Num has value 4 Num has value 5 Num has value 6 Num has value 7 Encountered break!! Out of loop
Explanation:
The continue statement is used to skip the current iteration of a loop and proceed to the next iteration. It allows us to bypass certain statements within the loop based on specific conditions.
Program 6-15: Using Continue Statement in a Loop
In this example, we demonstrate the use of the continue statement within a loop.
Code:
for num in range(10): if num == 5: continue print('Num has value ' + str(num))
Output:
Num has value 0 Num has value 1 Num has value 2 Num has value 3 Num has value 4 Num has value 6 Num has value 7 Num has value 8 Num has value 9
Explanation:
In this program, we will continuously prompt the user to enter positive numbers and calculate their sum. The program will stop taking inputs and display the sum as soon as the user enters a negative number.
Code:
entry = 0 sum1 = 0 print("Enter numbers to find their sum, negative number ends the loop:") while True: entry = int(input()) if (entry < 0):="" break="" sum1="" +="entry" print("sum=", sum1)
Output:
Enter numbers to find their sum, negative number ends the loop: -1 Sum = 12
Explanation:
In this program, we will check whether a given number is prime or not. A prime number is a natural number greater than 1 that is not divisible by any other natural number except 1 and itself.
Code:
num = int(input(" enter="" the="" number="" to="" be="" checked:="" "))="" flag="0" #="" presume="" num="" is="" a="" prime="" number="" if="" num="" /> 1: for i in range(2, int(num / 2)): if (num % i == 0): flag = 1 # num is not a prime number break # no need to check any further if flag == 1: print(num, "is not a prime number") else: print(num, "is a prime number")
Output:
Enter the number to be checked: 7 7 is a prime number
Explanation:
When a continue statement is encountered, it skips the remaining statements inside the loop for the current iteration and jumps to the beginning of the loop for the next iteration. If the loop’s condition is still true, it enters the loop again; otherwise, control passes to the statement immediately following the loop.
Program 6-15: Demonstrating the Use of Continue Statement
This program prints values from 0 to 6, except for the number 3.
# Program 6-15 # Prints values from 0 to 6 except 3 for num in range(6): num = num + 1 if num == 3: continue print(num) print('End of loop')
Output
0 1 2 4 5 End of loop
In the output, the value 3 is not printed, but the loop continues to print other values until the for loop terminates.
A loop can contain another loop inside it, which is known as a nested loop. In Python, there are no restrictions on the number of loops that can be nested within each other, nor on the levels of nesting. Any type of loop, whether a for loop or a while loop, can be nested within another loop.
Program 6-16: Demonstrating Nested for Loops
The program demonstrates the use of nested for loops by iterating through a range of values.
Output:
Iteration 1 of outer loop
1
2
Out of inner loop
Iteration 2 of outer loop
1
2
Iteration 3 of outer loop
1
2
Out of outer loop
Program 6-17: Generating a Pattern Based on User Input
The program prompts the user to enter a number and generates a pattern based on the input. The pattern consists of rows of numbers, where each row contains consecutive numbers starting from 1 up to the row number.
For example, if the user enters 5, the output pattern will be:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Program 6-18: Finding Prime Numbers Between 2 and 50 Using Nested For Loops
The program uses nested loops to identify and print prime numbers between 2 and 50. A prime number is a natural number greater than 1 that is not divisible by any positive integers other than 1 and itself.
The outer loop iterates through the numbers from 2 to 49, while the inner loop checks for factors of each number. If a factor is found, the number is not prime. If no factors are found, the number is prime and is printed.
Program 6-19: Calculating Factorial of a Given Number
The program calculates the factorial of a given number using a nested for loop. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
The program prompts the user to enter a number and initializes a variable to store the factorial value. Depending on the input number, it calculates the factorial accordingly.
Factorial of a Number
Introduction
Factorial of a Number using Python
# Program to find the factorial of a number num = int(input("Enter a number: ")) fact = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1, num + 1): fact = fact * i print("Factorial of", num, "is", fact)
1. What is the importance of flow control in programming? | ![]() |
2. How do selection statements work in programming? | ![]() |
3. Why is indentation important in programming? | ![]() |
4. What are break and continue statements, and how are they used? | ![]() |
5. What are nested loops, and when should they be used? | ![]() |