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

Module II

Module II covers control flow and data structures in Python, including logical operators, loops, and data types such as lists, dictionaries, and tuples. It explains selection structures (if, if-else, if-elif-else) and repetition structures (for and while loops), along with their syntax and examples. Additionally, it discusses string manipulation and indexing, highlighting the importance of indentation in Python programming.

Uploaded by

REMI N R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module II

Module II covers control flow and data structures in Python, including logical operators, loops, and data types such as lists, dictionaries, and tuples. It explains selection structures (if, if-else, if-elif-else) and repetition structures (for and while loops), along with their syntax and examples. Additionally, it discusses string manipulation and indexing, highlighting the importance of indentation in Python programming.

Uploaded by

REMI N R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Module II - Control Flow and Data Structures

Logical operators, if, If-Else, While loop, For loop, List value, length,
operation and
deletion, Dictionary operation & methods, Tuples

Flow of Control
The order of execution of the statements in a program is known as flow of
control. The flow of
control can be implemented using control structures. Python
supports two types of control
structures—selection and repetition.

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

1. SELECTION

A selection is 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.

1. Simple if statement

The syntax of if statement is:

if condition:
statement(s)

In the following example, if the age entered by the user is greater than
18, then print that the
user is eligible to vote. If the condition is true, then the indented
statement(s) are executed.

The indentation implies that its execution is dependent on the condition.


There is no limit on
the number of statements that can appear as a block under the if
statement.

Example 6.1
age = int(input("Enter your age "))
if age >= 18:
print("Eligible to vote")

2. if .. else Statement

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

3. if .. elif .. else Statement

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

The syntax for a selection structure using elif is as shown below.


if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
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.

Example 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")
else:
print("Number is zero")

Example 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!")
Program 6-3 Write a program to create a simple calculator
performing only 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)
Output:
Enter value 1: 84
Enter value 2: 4
Enter any one of the operator (+,-,*,/): /
The result is 21.0

4. Nested if Statements
Nested if .. statements is one if… statement inside another if… statement.

In the program, for the operators "-" and "/", there exists an if..else
condition within the elif
block. This is called nested if. We can have many levels of nesting inside
if..else statements.

2. INDENTATION

In most programming languages, the statements within a block are put


inside curly brackets.
However, Python uses indentation for block as well as for nested
block structures. Leading
whitespace (spaces and tabs) at the beginning of a statement is called
indentation. In Python,
the same level of indentation associate statements into a single block of
code. The interpreter
checks indentation levels very strictly and throws up syntax errors if
indentation is not correct.
It is a common practice to use a single tab for each level of indentation.

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


#Program to find larger of the two numbers
num1 = 5
num2 = 6
if num1 > num2: #Block1
print("first number is larger")
print("Bye")
else: #Block2
print("second number is larger")
print("Bye Bye")
Output:
second number is larger
Bye Bye

3. REPETITION
Often, we repeat a tasks, for example, payment of electricity bill, which is
done every month.
Consider the life cycle of butterfly that involves four stages, i.e., a
butterfly lays eggs, turns into
a caterpillar, becomes a pupa, and finally matures as a butterfly. The
cycle starts again with
laying of eggs by the butterfly.
This kind of repetition is also called iteration. Repetition of a set of
statements in a program is
made possible using looping constructs.

1. The ‘for’ Loop

The for statement is used to iterate over a range of values or a


sequence. The for loop is
executed for each of the items in the range. These values can be either
numeric, or, as we shall
see in later chapters, they can be elements of a data type like a string,
list, or tuple. With every
iteration of the loop, the control variable checks whether each of the
values in the range have
been traversed or not. When all the items in the range are exhausted, the
statements within
loop are not executed; the control is then transferred to the statement
immediately following
the for loop. While using for loop, it is known in advance.

(A) Syntax of the For Loop

for <control-variable> in <sequence/items in range>:


<statements inside body of the loop>
else: #optional
<statements inside else>

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:
PYTHON

#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
Program to print even numbers in a given sequence using for loop.

#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')
Output:
2 is an even Number
4 is an even Number
6 is an even Number
8 is an even Number
10 is an even Number
(B) The Range() Function

The range() is a built-in function in Python. Syntax of range() function is:

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

It is used to create a list containing a sequence of integers from the given


start value up to stop
value (excluding stop value), with a difference of the given step
value. We will learn about
functions in the next chapter. To begin with, simply remember that
function takes parameters
to work on. In function range(), start, stop and step are parameters.
The start and step parameters are optional. If start value is not specified,
by default the list
starts from 0. If step is also not specified, by default the value increases
by 1 in each iteration.
All parameters of range() function must be integers. The step parameter
can be a positive or a
negative integer excluding zero.

Example
#start and step not specified
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#default step value is 1
>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]
#step value is 5
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
#step value is -1. Hence, decreasing sequence is generated
>>> list (range (0, -9, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8]

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

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

2. while loop

The while statement executes a block of code repeatedly as long as the


control condition of the
loop is true. The control condition of the while loop is executed before any
statement inside the
loop is executed. After each iteration, the control condition is tested
again and the loop
continues as long as the condition remains true. When this
condition becomes false, the
statements in the body of loop are not executed and the control is
transferred to the statement
immediately following the body of while loop. If the condition of the while
loop is initially false,
the body 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>
else:
<body of else>
The else block just after for/while is executed only when the loop is
NOT terminated by a
break statement

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
Python program to show how to use a while loop
counter = 0
# Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")

#Python program to show how to use else statement with the while loop
counter = 0

# Iterating through the while loop


while (counter < 10):
counter = counter + 3
print("Python Loops") # Executed until condition is met
# Once the condition of while loop gives False this statement will be
executed
else:
print("Code block inside the else statement")

Jumps in Loops
Looping constructs allow programmers to repeat tasks efficiently. In
certain situations, when some
particular condition occurs, we may want to exit from a loop or skip some
statements of the loop before
continuing further in the loop. These requirements can be achieved
by using break and continue
statements, respectively. Python provides these statements as a tool
to give more flexibility to the
programmer to control the flow of execution of a program. Jumps
statements in Python are:
1. break
2. continue
3. pass

1. Break Statements
The break statement alters the normal flow of execution as it terminates
the current loop and resumes
execution of the statement following that loop.

# pass is just a placeholder for functionality to be added later

sequence = {‘p’,’a’,’s’,’s’}
for val in sequence:
pass

STRINGS
String is a sequence which is made up of one or more UNICODE
characters. Here the character
can be a letter, digit, whitespace or any other symbol. A string can be
created by enclosing one
or more characters in single, double or triple quote.

Example
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''’

str1, str2, str3, str4 are all string variables having the same value 'Hello
World!'. Values stored in
str3 and str4 can be extended to multiple lines using triple codes as can
be seen in the following
example:

>>> str3 = """Hello World!


welcome to the world of Python"""
>>> str4 = '''Hello World!
welcome to the world of Python'''

Accessing Characters in a String


Each individual character in a string can be accessed using a
technique called indexing. The
index specifies the character to be accessed in the string and is written in
square brackets ([ ]).
The index of the first character (from left) in the string is 0 and the last
character is n-1 where n
is the length of the string. If we give index value out of this range then we
get an IndexError.
The index must be an integer (positive, zero or negative).

#initializes a string str1


>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]

You might also like