Humanities/Arts Exam  >  Humanities/Arts Notes  >  Computer Science for Class 11  >  Chater Notes: Flow of Control

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts PDF Download

Introduction

When we write a program in Python, the computer follows the instructions exactly as they are written, one after the other, from the beginning to the end. This is similar to how a bus driver follows a specific road to reach the school, milestone by milestone. This basic way of executing instructions is called "sequence."

Program: Program to print the difference of two numbers.

#Program to print the difference of two input numbers 
num1 = int(input("Enter first number: ")) 
num2 = int(input("Enter second number: ")) 
diff = num1 - num2 
print("The difference of",num1,"and",num2,"is",diff)

Output: 

Enter first number 5 
Enter second number 7 
The difference of 5 and 7 is -2

Selection

A decision involves selecting from one of the two or more possible options. In programming, this concept of decision making or selection is implemented with the help of if..else statement.

 Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Introduction to Selection in Programming 

  • Selection in programming refers to the process of making choices based on specific conditions. Just like choosing between different paths on a map or picking a pen from a variety, programming often requires us to decide which action to take based on certain criteria.
  • In Python, this concept is implemented using the if...else statement.

Example: 

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:      
  statement(s)

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, so that it always gives a positive difference as the output. From the flow chart in Figure, 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).

Program: Program to print the positive difference of two numbers.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Output:

Enter first number: 5 
Enter second number: 6 
The difference of 5 and 6 is 1

Indentation in Python

In many programming languages, code blocks are enclosed within curly brackets. However, Python adopts a different approach by using indentation to define blocks of code, including nested structures. Indentation refers to the leading whitespace (comprising spaces and tabs) at the beginning of a line. In Python, statements with the same level of indentation are grouped together into a single block of code.

The Python interpreter enforces indentation levels strictly and will raise a syntax error if the indentation is not consistent. It is common practice to use a single tab (or a consistent number of spaces) for each level of indentation.

For example, in an if-else statement, the blocks of code following the conditions are indented to the same level to indicate they belong to the respective blocks.

Example: Program to find the larger of the two pre-specified numbers.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Repetition in Programming

  • Repetition in programming is similar to tasks we do regularly, like paying an electricity bill every month. Just as this task repeats, programming allows us to repeat a set of instructions using looping constructs.

Life Cycle of a Butterfly

  • The life cycle of a butterfly involves four stages: laying eggs, hatching into a caterpillar, becoming a pupa, and maturing into an adult butterfly.
  • This cycle illustrates the concept of iteration, where a process is repeated.

Example: Printing Numbers

Initially, if asked to print the first five natural numbers, one might write:

print(1)
print(2)
print(3)
print(4)
print(5)

Output: 

1
2
3
4
5

However, to print the first 100,000 natural numbers, writing 100,000 print statements would be inefficient. Instead, using a loop is a better solution.

  • The logic involves:
  • Setting a variable count  to 1.
  • Printing the value of count.
  • Incrementing  count by 1.
  • Repeating these steps while  count  is less than or equal to 100,000.

Looping Constructs

  • Looping constructs allow the execution of a set of statements repeatedly based on a condition.
  • The statements in a loop are executed as long as a specific logical condition is true.
  • This condition is checked using a variable called the loop’s control variable.
  • When the condition becomes false, the loop terminates.
  • It is essential for the programmer to ensure that the condition eventually becomes false to avoid an infinite loop.
  • For example, in the previous case, without the condition  count <= 100000  , the program would run indefinitely.
  • There are two main looping constructs in Python: for and while.

The 'For' Loop

The 'for' statement is utilized to iterate over a specified range of values or a sequence. During each iteration of the for loop, the control variable checks whether each value in the range has been traversed. When all items in the range have been exhausted, the statements within the loop are not executed, and control is transferred to the statement immediately following the for loop.

When using a for loop, the number of iterations is known in advance.

(A) Syntax of the For Loop

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Program: Program to print the characters in the string ‘PYTHON’ using for  loop.

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

Output: 

P
Y
T
H
O
N

Program: Program to print the numbers in a given sequence using for loop.

#Print the given sequence of numbers using for loop 
count = [10,20,30,40,50] 
for num in count:      
     print(num)

Output: 

10
20
30
40
50

(B) The Range() Function

The range() function is a built-in function in Python. Its syntax is: range([start], stop[, step]). This function generates a sequence of integers starting from the specified start value up to, but not including, the stop value, with increments or decrements defined by the step value.

We will explore functions in the next chapter, but for now, understand that functions use parameters to perform operations. In the range() function, start, stop, and step are its parameters.

The start and step parameters are optional. If start is not provided, it defaults to 0. If step is not specified, it defaults to 1, meaning the sequence increases by 1 at each step. All parameters in the range() function must be integers. The step value can be positive or negative but cannot be zero.

Example: Using the range() Function

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

The function range() is often used in for loops for generating a sequence of numbers.

Program: Program to print the multiples of 10 for numbers in a given range.

#Print multiples of 10 for numbers in a given range 
for num in range(5):      
    if num > 0:          
         print(num * 10)

Output: 

10
20
30
40

The “While” Loop

A “while” loop in programming is used to execute a block of code repeatedly as long as a specified condition is true. Here’s a detailed explanation of how it works:

  • Control Condition: The condition that controls the loop is checked before any statements inside the loop are executed.
  • Execution: If the condition is true, the code inside the loop runs. After each execution, the condition is checked again.
  • Termination: The loop continues to execute as long as the condition remains true. If the condition becomes false, the loop stops, and control moves to the statement immediately following the loop.
  • Initial False Condition: If the condition is false from the beginning, the code inside the loop does not run even once.
  • Avoiding Infinite Loop: It’s crucial that the statements within the loop eventually make the condition false. If they don’t, the loop will run forever, causing a logical error in the program.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

The basic syntax of a “while” loop is as follows:

while test_condition:

Program: Program to print first 5 natural numbers using while loop.

#Print first 5 natural numbers using while loop 
count = 1 
while count <= 5:      
     print(count)     
     count += 1

Output: 

1
2
3
4
5

Program: Program to find the factors of a whole numberusing while loop.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Note:

  • The body of the loop (the indented code) is executed repeatedly as long as the condition is true.
  • The statements inside the if condition are also indented to show that they belong to the if statement.

Break and Continue Statement

Looping constructs help programmers efficiently repeat tasks. In some cases, when a specific condition is met, we may need to exit the loop permanently or skip certain statements before continuing. This can be accomplished using the break and continue statements. Python offers these statements to provide programmers with greater control over the flow of execution in a program.

Break Statement

  • The break statement is used to change the usual flow of execution in a program. It does this by ending the current loop and continuing with the statement that comes after the loop.

Program: Program to demonstrate use of break statement.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

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

Note: When the value of num reaches 8, the break statement is triggered, and the for loop ends.

Program: Find the sum of all the positive numbers entered by the user. As soon as the user enters a negative number, stop taking in any further input from the user and display the sum.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Output:

Enter numbers to find their sum, negative number ends the loop: 
3
4
5
-1
Sum = 12

Continue Statement

When a continue statement is executed, it skips the remaining code inside the loop for the current iteration and jumps back to the start of the loop for the next iteration. If the loop's condition is still true, the loop will be executed again; otherwise, the control will move to the statement following the loop.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Program: Program to demonstrate the use of continue statement.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts
Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Output: 

Num has value 1 
Num has value 2 
Num has value 4 
Num has value 5 
Num has value 6 
End of loop

Nested Loops

Nested loops are loops that exist within another loop. In Python, there are no restrictions on the number of loops that can be nested within each other, nor are there restrictions on the types of loops that can be nested. For example, a for loop can be nested within a while loop, and vice versa.

Program: Program to demonstrate working of nested for loops.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Output:

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Python does not impose any restriction on how many loops can be nested inside a loop or on the levels of nesting. Any type of loop (for/while) may be nested within another loop (for/while).

Program: Program to print the pattern for a number input by the user.

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

Output:

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

The document Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Computer Science for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
33 docs|11 tests

FAQs on Chater Notes: Flow of Control - Computer Science for Class 11 - Humanities/Arts

1. What is the importance of indentation in Python?
Ans. Indentation in Python is crucial because it defines the blocks of code. Unlike many programming languages that use braces or keywords to denote code blocks, Python relies on indentation levels to indicate how the code is structured. Proper indentation makes the code readable and helps avoid syntax errors. It is essential for controlling the flow of execution, especially in loops and conditional statements.
2. How do break and continue statements work in Python?
Ans. The `break` statement in Python is used to exit a loop prematurely when a certain condition is met, while the `continue` statement skips the current iteration and moves to the next iteration of the loop. These statements are useful for controlling the flow of loops and can help optimize the execution of the program based on specific conditions.
3. What are nested loops, and how are they used in Python?
Ans. Nested loops are loops that are contained within another loop. In Python, you can place a loop inside the body of another loop, which allows for more complex iterations, such as iterating over multi-dimensional data structures. They are commonly used in tasks requiring the comparison of elements across multiple lists or matrices.
4. How does selection control flow work in Python?
Ans. Selection control flow in Python is managed using conditional statements like `if`, `elif`, and `else`. These statements allow the program to execute certain blocks of code based on specific conditions. The flow of control is determined by evaluating boolean expressions, making it possible to implement decision-making logic in the program.
5. What are the common pitfalls to avoid with loops in Python?
Ans. Common pitfalls when using loops in Python include infinite loops, which occur when the loop's exit condition is never met, and off-by-one errors, which happen when you miscount the iterations. Additionally, improper use of `break` and `continue` can lead to unexpected behavior and make the code harder to read. It's important to test loop conditions carefully and ensure they are logically sound.
Related Searches

practice quizzes

,

study material

,

Semester Notes

,

shortcuts and tricks

,

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

,

mock tests for examination

,

Free

,

pdf

,

Extra Questions

,

past year papers

,

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

,

Previous Year Questions with Solutions

,

Important questions

,

ppt

,

MCQs

,

Exam

,

video lectures

,

Viva Questions

,

Objective type Questions

,

Sample Paper

,

Summary

,

Chater Notes: Flow of Control | Computer Science for Class 11 - Humanities/Arts

;