Python Unit 3
Control Structure
Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE
as outcome. You need to determine which action to take and which statements to
execute if outcome is TRUE or FALSE otherwise.
Python programming language assumes any non-zero and non-null values as TRUE, and if
it is either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements. Click
the following links to check their detail.
An if statement consists of a boolean expression followed by one or more statements.
If..else statement
An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.
You can use one if or else if statement inside another if or else if statement(s).
Single Statement Suites
If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.
Here is an example of a one-line if clause −
#!/usr/bin/python
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
When the above code is executed, it produces the following result −
Value of expression is 100
Good bye!
An else statement can be combined with an if statement. An else statement contains the block of code
that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else statement
following if.
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to
TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary
number of elif statements following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct.
In a nested if construct, you can have an if...elif...else construct inside another if...elif...else construct.
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Nested if example
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
count = 1
num = int (input("enter number"))
if (num < 0):
print ('Number is negative')
elif(num==0):
print('number is zero')
else:
print('number is positive')
print ("Good bye!")
Break statement
It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C.
The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while
and for loops.
If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.
# break Example
for letter in 'Python':
if letter == 'h':
break
print 'Current Letter :', letter
continue statement
It returns the control to the beginning of the while loop.. The continue statement rejects all the remaining statements in
the current iteration of the loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
# Example
for letter in 'Python':
if letter == 'h':
continue
print 'Current Letter :', letter
pass Statement
It is used when a statement is required syntactically but you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been
written yet
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
Loops in python
There may be a situation when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is
true.
Syntax
The syntax of a while loop in Python programming language is
while expression:
statement(s)
statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero
value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be
part of a single block of code. Python uses indentation as its method of grouping statements.
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop
body will be skipped and the first statement after the while loop will be executed.
while loop example
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than
9. With each iteration, the current value of the index count is displayed and then increased by 1.
for loop
It has the ability to iterate over the items of any sequence, such as a list or a string.
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the
iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var,
and the statement(s) block is executed until the entire sequence is exhausted.
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset into the sequence itself. Following is a simple example
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
print "Good bye!"
Nested loops
Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the
concept.
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows −
while expression:
while expression:
statement(s)
statement(s)
example
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
When above code executed the prime number till 100 will be printed
i=1
while(i <= 5):
j=1
while(j <= i):
j=j+1
print (i)
i=i+1
print("Hello World")
# Program to check if a number is prime or not
num = 29
# To take input from the user
#num = int(input("Enter a number: "))
# define a flag variable
flag = False
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break
# check if flag is True
if flag:
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
# Python program to find the factorial of a number provided by the user.
# change the value for a different result
num = 7
# To take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
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):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
base = 3
exponent = 4
# To take input from the user
#base = int(input("Enter a number: "))
#exponent = int(input("Enter a number: "))
result = 1
for exponent in range(exponent, 0, -1):
result *= base
print("Answer = " + str(result))