0% found this document useful (0 votes)
28 views15 pages

Software Book

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

Software Book

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

UNIT II

CONTROL STRUCTURE

A control statement determines the control flow of a set of instructions. There are three
fundamental forms of control statements - sequential control , selection control , and iterative
control.
 Sequential control is an implicit form of control in which instructions are executed in the
order that they are written.

 Selection control is a control statement that selectively executes instructions.

 Iterative control is an iterative control statement that repeatedly executes instructions.

Boolean Expressions (Conditions)

A Boolean expression evaluates to a Boolean value- True and False in Python.

Boolean expressions are used to denote the conditions for selection and iterative control
statements.

Relational Operators:The relational operators in Python perform the usual comparison


operations, These operators not only apply to numeric values, but to strings also.
Membership Operators: These operators can be used to easily determine if a particular value
occurs within a specified list of values.
The in operator is used to determine if a specific value is in a given list, returning True if found,
and False otherwise. The not in operator returns the opposite result

Logical/Boolean Operators:
Boolean algebra contains a set of Boolean operators denoted by and, or, and not in Python. These
logical operators can be used to construct arbitrarily complex Boolean expressions. The Boolean
operators are shown in Figure 3-5.

Logical and is true only when both its operands are true—otherwise, it is false.

Logical or is true when either or both of its operands are true, and thus false only when both
operands are false.

Logical not simply reverses truth values—not False equals True, and not True equals False.

Selection Control

A selection control statement is a control statement providing selective execution of instructions.


A selection control structure is a given set of instructions and the selection control statement(s)
controlling their execution.

Python’s selection control statement are

 if statements

 if-else statements
 if-elif statements
 nested if statements
if Statement

An if statement is a selection control statement based on the value of a given Boolean


expression.

Syntax:

if <condition>:

statements-block1

In the above syntax if the condition is true statements - block 1 will be executed.

Example

x=20
y=10
if x > y :
print(" X is bigger ")

Indentation in Python
In Python the amount of indentation of each program line is important.It is used to associate and
group statements, as shown in Figure.

A header in Python is a specific keyword followed by a colon. In the figure, the if-else statement
contains two headers, if and else. Headers that are part of the same compound statement must be
indented the same amount—otherwise, a syntax error will result.
The set of statements following a header in Python is called a suite (commonly called a block ).
The statements of a given suite must all be indented the same amount. A header and its
associated suite are together referred to as a clause .
A compound statement in Python may consist of one or more clauses. While four spaces is
commonly used for each level of indentation, any number of spaces may be used.
if..else statement
The if .. else statement provides control to check the true block as well as the false block.

Syntax:

if <condition>:

statements-block 1

else:

statements-block 2

x=10

y=20

if x > y :

print(" X is bigger ")

else :

print(" Y is bigger ")

Multi-Way Selection:
Multi-Way Selection is one involving multiple nested if statements, and the other involving a
single if statement and the use of elif headers.
if..elif...statement: When we need to construct a chain of if statement(s) then ‘elif’ clause can
be used instead of ‘else’.
Syntax:

if <condition-1>:

statements-block 1

elif <condition-2>:
statements-block 2

else:

statements-block n

In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then


statements-block1 is executed, otherwise the control checks condition-2, if it is true statements-
block2 is executed and even if it fails statements-block n mentioned in else part is executed.

eg)

x=500

if x > 500 :

print(" X is greater than 500 ")

elif x < 500 :

print(" X is less than 500 ")

elif x == 500 :

print(" X is 500 ")

else :

print(" X is not a number ")

Nested if statements

if statement inside another statement.

Syntax:

if condition:

if condition:

statements

else:

statements

else:

statements
eg) mark = 72

if mark > 50:

if mark > = 80:

print ("You got A Grade !!")

elif mark > =60 and mark < 80 :

print ("You got B Grade !!")

else:

print ("You got C Grade !!")

else:

print("You failed!!")

Iterative Control
An iterative control statement is a control statement providing the repeated execution of a set
of instructions. An iterative control structure is a set of instructions and the iterative control
statement(s) controlling their execution. Because of their repeated execution, iterative control
structures are commonly referred to as “loops.”

Python provides two types of looping constructs:

(i) while loop

(ii) for loop

(i) while loop

The syntax of while loop in Python:

Syntax:

while <condition>:

statements block 1

[else:

statements block2]

 In the while loop, the condition is any valid Boolean expression returning True or False.
 The statements block1 is kept executed till the condition is True

 The else part of while is optional part of while..

If the else part is written, it is executed when the condition is tested Falsei=10 # intializing part
of the control variable

while (i<=15): # test condition

print (i,end='\t') # statements - block 1

i=i+1 # Updation of the control variable

else:

print ("\nValue of i when the loop exit ",i)

 An infinite loop is an iterative control structure that never terminates.

 A loop becomes infinite loop if a condition never becomes FALSE.

 The loop that never ends is called an infinite loop.

eg1) while True:

print("hello")

Definite vs. Indefinite Loops

A definite loop is a program loop in which the number of times the loop will iterate can be
determined before the loop is executed.

A indefinite loop is a program loop in which the number of times the loop will iterate is not
known before the loop is executed.

eg1)

sum = 0

current = 1

n =input('Enter value: ')

while current <= n:

sum = sum + current

current =current + 1
eg2)i = input("Enter selection: ")

while i ! = 'F' and i ! = 'C':

which = input("Please enter 'F' or 'C': ")

ii)for loop

A for loop is used for iterating over a sequence.

 Syntax:
for <variable> in <sequence>:

# body_of_loop

Here <variable> is a variable that is used for iterating over a <sequence>.

On every iteration it takes the next value from <sequence> until the end of sequence is
reached.

Looping Through a String

Eg1)

for x in "banana":
print(x)

Looping Through a Tuple

Eg2)

numbers = (1,2,3,4,5)

sum = 0

for val in numbers:

sum = sum+val

print("The sum is", sum)

Eg2)

numbers = [1, 2, 4, 6, 11, 20]

sq = 0

for val in numbers:


sq = val * val

print(sq)

Range function

A range() function in for loop to iterate over numbers defined by range().

 range(n): generates a set of whole numbers starting from 0 to (n-1).


eg)
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]

eg)

for val in range(8):

print(val)

 range(start, stop): generates a set of whole numbers starting from start to stop-1.
eg)
range(5, 9) is equivalent to [5, 6, 7, 8]

 range(start, stop, step_size): The default step_size is 1 which is why when we didn’t
specify the step_size, the numbers generated are having difference of 1. However by
specifying step_size we can generate numbers having the difference of step_size.
eg)
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]

 In Python we can have an optional ‘else’ block associated with the loop.

 The ‘else’ block executes only when the loop has completed all the iterations.

Lets take an example:

for x in range(6):
print(x)
else:
print("Finally finished!")

 When a for loop is present inside another for loop then it is called a nested for loop.

 Lets take an example of nested for loop.

Eg)
for num1 in range(3):

for num2 in range(10, 12):

print(num1, ",", num2)

Loop Control Statements

 Loop control statements change execution from its normal sequence.

Python supports the following control statements

 The break statement is used for premature termination of the current loop.

 The break statement can be used in both while and for loops.

The syntax for a break statement in Python is as follows −

break

for letter in 'Python': # First Example

if letter == 'h':

break

print ('Current Letter :', letter)

 The continue statement in Python returns the control to the beginning of the current loop.

 When encountered, the loop starts next iteration without executing the remaining
statements in the current iteration.

 The continue statement can be used in both while and for loops.
Syntax

Continue

for letter in 'Python': # First Example

if letter == 'h':

continue

print ('Current Letter :', letter)

 The pass statement is a null operation; nothing happens when it executes.

 The pass statement is also useful in places where your code will eventually go, but has
not been written yet i.e. in stubs.

Syntax

pass

for letter in 'Python':

if letter == 'h':

pass

print ('This is pass block')

print ('Current Letter :', letter)

print ("Good bye!")

List Structures
A list is a linear data structure , meaning that its elements have a linear ordering in which each
item in the list is identified by its index value .

 It is customary in programming languages to begin numbering sequences of items with


an index value of 0 rather than 1. This is referred to as zero-based indexing

Operations commonly performed on lists include retrieve, update, insert, delete (remove) and
append
List Traversal list traversal , a way of accessing each of the elements of a given list. A list
traversal is a means of accessing, one-by-one, the elements of a list. For example, to add up
all the elements in a list of integers, each element can be accessed one-by-one, starting with the
first, and ending with the last element.
A list in Python is a mutable, linear data structure of variable length, allowing mixed-type
elements. Mutable means that the contents of the list may be altered. Lists in Python use
zerobased
indexing. Thus, all lists have index values 0 ... n-1, where n is the number of elements
in the list. Lists are denoted by a comma-separated list of elements within square brackets as
shown below,
[1, 2, 3] ['one', 'two', 'three'] ['apples', 50, True]

An empty list is denoted by an empty pair of square brackets.

Elements of a list are accessed by using an index value within square


brackets,
lst 5 [1, 2, 3] lst[0] ➝ 1 access of fi rst element
lst[1] ➝ 2 access of second element
lst[2] ➝ 3 access of third element
Tuples
A tuple is an immutable linear data structure. Thus, in contrast to lists, once a tuple is defi ned, it
cannot be altered. Otherwise, tuples and lists are essentially the same. To distinguish tuples from
lists, tuples are denoted by parentheses instead of square brackets as given below,

nums=(10, 20, 30)


student = ('John Smith', 48, 'Computer Science', 3.42)

Sequences
A sequence in Python is a linearly ordered set of elements accessed by an index number. Lists,
tuples, and strings are all sequences. Strings, like tuples, are immutable ; therefore, they cannot
be altered.
 We give sequence operations common to strings, lists, and tuples in Figure 4-6.

Python’s for loop and while loop provides a convenient means of iterating over lists (and
other sequences).
Iterate through list in Python using a for Loop

 A for statement is an iterative control statement that iterates once for each element in a
specified sequence of elements.

Syntax:for loop_variable in sequence:

eg)for k in ['Apple', 'Banana', 'Pear']:

print(k)

for k in (4, 2, 3, 1):

print(k)

for k in 'Apple':

print(k)

Iterate through list in Python using range() method

 Python’s range() method can be used in combination with a for loop to traverse and
iterate over a list in Python.

 The range() method basically returns a sequence of integers

lst = [10, 50, 75, 83, 98, 84, 32]

for x in range(len(lst)):

print(lst[x])

Iterate through list in Python with a while loop

 In the while loop version, loop variable must be initialized to 0 and incremented by 1
each time through the loop.

while(condition) :

Statement

eg) nums = [10, 50, 75, 83, 98, 84, 32]

k=0

while k < len(nums):

print(nums[k])
k=k+1

Iterating Over List Elements vs. List Index Values

An index variable is a
variable whose changing value is used to access elements of an indexed data structure .lst = [10,
20,30,40,50]

for k in lst:

sum=sum+k

print(sum)

lst = [10, 20,30,40,50]

for k in range(len(lst)):

sum=sum+lst[k]

print(sum)

You might also like