Notes  >  Chapter Notes: Flow of Control

Flow of Control Chapter Notes PDF Download

Flow of Control

Flow of Control Chapter Notes

Introduction

Flow of Control Chapter Notes

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:

  • The flow of control in a program refers to the order in which the statements are executed.
  • In Python, the flow of control can be implemented using control structures, which determine the sequence of execution.
  • There are two types of control structures in Python: selection and repetition.

2. Selection:

  • Selection control structures allow the program to make decisions and execute specific blocks of code based on certain conditions.
  • For example, the if statement in Python is used to execute a block of code if a certain condition is true.

3. Indentation:

  • Indentation is an important aspect of Python syntax and is used to define the scope of control structures.
  • Proper indentation ensures that the code is readable and that the intended blocks of code are executed together.
  • Python uses indentation to determine the grouping of statements, making it essential for the correct flow of control.

4. Repetition:

  • Repetition control structures, such as loops, allow a block of code to be executed repeatedly based on a condition.
  • Python provides various loop constructs, such as the for loop and the while loop, to facilitate repetition in programming.

5. Break and Continue Statements:

  • The break statement is used to terminate a loop prematurely, while the continue statement skips the current iteration and moves to the next one.
  • These statements provide additional control over the flow of execution within loops.

6. Nested Loops:

  • Nested loops involve placing one loop inside another, allowing for more complex iterations and control over the flow of execution.
  • Python supports nested loops, enabling programmers to tackle intricate repetitive tasks efficiently.

7. Example Program:

  • The example program demonstrates a simple flow of control where the difference between two numbers is calculated and displayed.
  • The program takes two input numbers from the user, calculates their difference, and prints the result.
  • This illustrates the sequential execution of statements, showcasing the basic concept of flow of control in Python.

(i) if Statement

Flow of Control Chapter Notes

The if statement is used to execute a block of statements based on a condition.

  • Syntax:

    if condition: statement(s)

  • Example:

    age = int(input("Enter your age: ")) if age > 18: print("You are eligible to vote.")

(ii) if-else Statement

Flow of Control Chapter Notes

The if-else statement is used to execute one block of statements if the condition is true and another block if it is false.

  • Syntax:

    if condition: statement(s) else: statement(s)

  • Example:

    age = int(input("Enter your age: ")) if age > 18: print("You are eligible to vote.") else: print("You are not eligible to vote.")

Example 6.1

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).

noteS

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:

  • Accept two numbers from the user.
  • Prompt the user to enter an operator (+, -, *, /). If the user enters an invalid operator, display an error message.
  • For the subtraction operator (-), display only the positive difference between the two numbers.
  • For the division operator (/), if the user enters 0 as the second number, display a message saying "Please enter a value other than 0."

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.

6.3 Indentation

Flow of Control Chapter Notes

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 6-4: Finding the Larger of Two Numbers

Flow of Control Chapter Notes

# 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

Flow of Control Chapter Notes

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:

  • Without a loop:

print(1)

print(2)

print(3)

print(4)

print(5)

  • With a loop:

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 Loop

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.

(B) The Range() Function

The range() function is a built-in feature in Python. Its syntax is as follows:

range([start], stop[, step])

  • This function generates a list of integers starting from the specified start value and ending at the stop value (exclusive), with a specified step difference between each integer.
  • start, stop, and step are the parameters used by this function.
  • The start and step parameters are optional. If the start value is not provided, it defaults to 0. Similarly, if the step value is not specified, it defaults to 1.
  • All parameters in the range() function must be integers. The step parameter can be either a positive or a negative integer, but it cannot be zero.

Example 6.4

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" Loop

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.

Break and Continue Statements

Flow of Control Chapter Notes

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.

1. Break Statement

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.

Example of Break Statement

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:

  • In this program, a loop iterates through numbers from 0 to 9.
  • When the value of num reaches 8, the break statement is executed, terminating the loop.
  • The program then prints the values of num until the loop is broken, followed by a message indicating the break.

2. Continue Statement

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.

Example of Continue Statement

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, a loop iterates through numbers from 0 to 9.
  • When the value of num is 5, the continue statement is executed, skipping the rest of the loop for that iteration.
  • The program then prints the values of num for all iterations except when it is 5.

Program 6-13: Sum of Positive Numbers Until a Negative Number is Entered

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:

  • The program initializes a variable sum1 to keep track of the sum of positive numbers.
  • It enters an infinite loop where it prompts the user to enter numbers.
  • If the user enters a negative number, the loop is terminated using the break statement.
  • If the number is positive, it is added to the sum.
  • Finally, when a negative number is encountered, the program prints the total sum of positive numbers entered.

Program 6-14: Check if a Number is Prime or Not

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:

  • The program takes an integer input from the user.
  • It assumes the number is prime by default and checks for factors starting from 2 up to half of the number.
  • If a factor is found (i.e., the number is divisible by i ), the flag is set to 1, indicating the number is not prime.
  • Finally, the program prints whether the number is prime or not based on the value of flag.

Continue Statement

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.

Nested Loops in Python

Flow of Control Chapter Notes

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 is the product of all positive integers from 1 to that number.
  • For example, the factorial of 5 (written as 5!) is 5 x 4 x 3 x 2 x 1 = 120.

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)

FAQs on Flow of Control Chapter Notes

1. What is the importance of flow control in programming?
Ans. Flow control is crucial in programming as it dictates the order in which statements are executed. It allows for decision-making (selection), repetition of code (loops), and the ability to break or continue within those loops. This structure enables developers to create dynamic and responsive programs.
2. How do selection statements work in programming?
Ans. Selection statements, such as if-else statements, allow a program to execute certain blocks of code based on specific conditions. If the condition evaluates to true, the associated block of code runs; if false, an alternative block may execute. This allows for conditional logic in programs.
3. Why is indentation important in programming?
Ans. Indentation is essential for readability and structure in programming. It visually separates code blocks, making it easier to understand the hierarchy and flow of control. In languages like Python, indentation is also syntactically significant, as it defines the scope of loops and conditional statements.
4. What are break and continue statements, and how are they used?
Ans. Break and continue are control flow statements used within loops. The break statement terminates the loop entirely when a certain condition is met, while the continue statement skips the current iteration and moves to the next one. These statements provide greater control over loop execution.
5. What are nested loops, and when should they be used?
Ans. Nested loops are loops placed inside another loop, allowing for complex iterations over data structures like arrays or matrices. They are useful when dealing with multi-dimensional data or when a task requires multiple layers of iteration. However, they can lead to increased complexity and performance concerns if not managed properly.
Download as PDF
Explore Courses for exam