KEMBAR78
Py Module 2 | PDF | Control Flow | Computer Science
0% found this document useful (0 votes)
5 views9 pages

Py Module 2

This document covers control structures in Python, including sequential, selection, and repetition controls. It explains various types of selection statements (if, if-else, nested if, if-elif-else) and repetition statements (for and while loops), along with break, continue, and pass statements. Additionally, it discusses infinite loops, their management, and the distinction between definite and indefinite loops.

Uploaded by

mspvlit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Py Module 2

This document covers control structures in Python, including sequential, selection, and repetition controls. It explains various types of selection statements (if, if-else, nested if, if-elif-else) and repetition statements (for and while loops), along with break, continue, and pass statements. Additionally, it discusses infinite loops, their management, and the distinction between definite and indefinite loops.

Uploaded by

mspvlit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

MODULE 2

Control Structure -Selection Control- If Statement - Indentation in Python - Multi-


Way Selection - Iterative Control - While Statement - Input Error Checking - Infinite
loops - Definite vs. Indefinite Loops

A program’s control flow is the order in which the program’s code executes.

The control flow of a Python program is regulated by conditional statements, loops, and
function calls.

Python has three types of control structures:

 Sequential - default mode


 Selection - used for decisions and branching
 Repetition - used for looping, i.e., repeating a piece of code multiple times.

1. Sequential

Sequential statements are a set of statements whose execution process happens in a


sequence. The problem with sequential statements is that if the logic has broken in any
one of the lines, then the complete source code execution will break.

1
2
3
4
5
6
## This is a Sequential statement

a=20
b=10
c=a-b
print("Subtraction is : ",c)

2. Selection/Decision control statements


In Python, the selection statements are also known as Decision control
statements or branching statements.

The selection statement allows a program to test several conditions and execute
instructions based on which condition is true.

Some Decision Control Statements are:

 Simple if
 if-else
 nested if
 if-elif-else

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


Simple if: If statements are control flow statements that help us to run a particular code,
but only when a certain condition is met or satisfied. A simple if only has one condition to
check.

n = 10
if n % 2 == 0:
print("n is an even number")

if-else: The if-else statement evaluates the condition and will execute the body of if if the
test condition is True, but if the condition is False, then the body of else is executed.

n=5
if n % 2 == 0:
print("n is even")
else:
print("n is odd")

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


nested if: Nested if statements are an if statement inside another if statement.

a=5
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
print("c value is big")
elif b > c:
print("b value is big")
else:
print("c is big")

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


if-elif-else: The if-elif-else statement is used to conditionally execute a statement or a
block of statements.

x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")

3. Repetition

A repetition statement is used to repeat a group(block) of programming instructions.

In Python, we generally have two loops/repetitive statements:

 for loop
 while loop

for loop: A for loop is used to iterate over a sequence that is either a list, tuple, dictionary,
or a set. We can execute a set of statements once for each item in a list, tuple, or
dictionary.

lst = [1, 2, 3, 4, 5]
for i in range(len(lst)):
print(lst[i], end = " ")

for j in range(0,10):
print(j, end = " ")

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


while loop: In Python, while loops are used to execute a block of statements repeatedly
until a given condition is satisfied. Then, the expression is checked again and, if it is still
true, the body is executed again. This continues until the expression becomes false.

m=5
i=0
while i < m:
print(i, end = " ")
i=i+1
print("End")

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


Break, Continue and Pass Statements
Break Statements
In Python, the break statement is employed to end or remove the control from the
loop that contains the statement. It is used to end nested loops (a loop inside another
loop), which are shared with both types of Python loops. The inner loop is completed, and
control is transferred to the following statement of the outside loop.
Code
for i in range(1,50):
print(i)
if i == 18:
break
print ("Stopped at 18")

The code display number from 1 to 18, otherwise, the interpreter will print a
message mentioning that the candidate is Stopped at 18 in the console.

Continue Statements
When a Python interpreter sees a continue statement, it skips the present iteration's
execution if the condition is satisfied. If the condition is not satisfied, it allows the
implementation of the current iteration. It is employed to keep the program running even
when it meets a break while being executed.

Code
# Python program to show how to control the flow of a loop using a continue statement
# Printing only the letters of the string
for l in 'I am a coder':
if l == ' ':
continue
print ('Letter: ', l)

Output:
Letter: I Letter: a Letter: m Letter: a Letter: c Letter: o Letter: d
Letter: e Letter: r
In this code, when the if-statement encounters a space, the loop will continue to the
following letter without printing the space.

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


Pass Statements
If the condition is met, the pass statement, or a null operator, is used by the coder to leave
it as it is. Python's pass control statement changes nothing and moves on to the following
iteration without stopping the execution or skipping any steps after completing the current
iteration.
A coder can put the pass statement to prevent the interpreter from throwing an error
when a loop or a code block is left empty.

Code
# Python program to show how to create empty code blocks using a pass statement
for l in 'Python':
if l == 't':
pass
print('Letter: ', l)
Output:

Letter: P Letter: y Letter: t Letter: h Letter: o Letter: n

Even if the condition was satisfied in the code above, as we can see, the pass statement
had no effect, and execution went on to the subsequent iteration.

Infinite loops in python


Infinite loops in Python are loops that continue indefinitely until a specific condition
is met or until the program is interrupted. They are useful in certain scenarios, but you
need to be careful while using them because they can cause your program to hang or
consume excessive system resources if not handled properly.

Example
a=2
while a<10:
print(a)
a=a-1

The above example a is always less than 10, so always the loop will repeat giving a
value.

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


Solution for Infinite loop
In this example, we can exit the loop using a break statement when a specific
condition is met. For instance:
a=2
while a<10:
print(a)
a=a-1
if(a < 0):
break;
It's important to ensure that your infinite loop has an exit condition, or else your
program may become unresponsive. In some cases, you can use external events or signals
to break out of the loop, such as keyboard interrupts (Ctrl+C) or specific input values.

Remember, when working with infinite loops, it's crucial to handle them carefully
and provide a way to exit the loop to prevent your program from running indefinitely.

Definite and indefinite loops


A definite loop is a loop in which the number of times it is going to execute is known
in advance before entering the loop. In an indefinite loop, the number of times it is going
to execute is not known in advance and it is going to be executed until some condition is
satisfied. There are two types of loops that exist in programming, including in Python.

Definite Loops (also known as "for" loops):


Definite loops are used when you know in advance how many times you want to iterate or
loop over a block of code. These loops are commonly used when you have a specific
collection or sequence of elements that you want to iterate through. In Python, the for
loop is commonly used for definite loops.
Here's an example of a definite loop using a for loop in Python:

python
Copy code
for i in range(5):
# Code that will be executed 5 times
print(i)
In this example, the loop will iterate five times, and the variable i will take the values 0, 1,
2, 3, and 4. Definite loops are useful when you know the exact number of iterations
needed.

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605


Indefinite Loops (also known as "while" loops):
Indefinite loops are used when you don't know in advance how many times you want to
loop or when the looping condition depends on certain dynamic factors. These loops
continue until a specific condition is met. In Python, the while loop is commonly used for
indefinite loops.

Here's an example of an indefinite loop using a while loop in Python:

while condition:
# Code that will be executed repeatedly
# ...
In this example, the loop will continue as long as the condition remains true. The condition
is usually checked at the beginning or end of the loop block. Indefinite loops are useful
when you need to repeat a block of code until a particular condition is satisfied.

It's important to ensure that an exit condition is provided in indefinite loops to prevent
them from running indefinitely. Otherwise, the program may become unresponsive or
consume excessive resources.

Both definite and indefinite loops have their uses, and choosing the appropriate type of
loop depends on the specific requirements and constraints of your program.

J. JAGADEESAN, ASST. PROFESSOR OF COMPUTER SCIENCE, AAGASC, Karaikal-609605

You might also like