Decision & Repetition
Decision & Repetition
1. Decision Control.
In simple terms, the Python if statement selects actions to perform. Along with its
expression counterpart, it’s the primary selection tool in Python and represents much of the
logic a Python program possesses.
Following is the general form of a typical decision making structure found in most of the
programming languages-
if statements
if statement consists of a Boolean expression followed by one or more statements.
if...else statements
An if statement can be followed by an optional else statement, which executes when
the Boolean expression is FALSE.
if...elif...elif...else
The elif statement allows you to check multiple expressions for TRUE.
nested if statements
You can use one if or else if statement inside another if or else if statement(s).
THE IF STATEMENT
>>> if 1:
print('true')
true
>>>
>>>
When we enter the input value up to 18, then the if condition checks if age <= 18 i.e.,
the expression is evaluated and return TRUE value so the next statement of the if
block runs and print the results.
Similarly when we enter a value higher than the range i.e., greater then 18, then the
expression evaluates and return FALSE so the Python interpreter do not execute the
if block at all and so come out of it.
The next statement which is not a part of the if block will execute.
Note: In Python the block of code will be treated as one block as per the indentation, after
the conditional statement followed by a colon as shown in the above examples.
Example : A Supermarket offers you, a discount of 10% if the quantity purchased is more
than 2000. Write a program to calculate the total expenses and enter the quantity and price
per item as input through the keyboard.
var = 100
if ( var == 100 ) :
print ("Value of expression is 100")
print ("Good bye!")
Example: In the below program the current year and the year in which the employee joined
the organization are entered through the keyboard using input() function. If the number of
years for which the employee has served the organization is greater than 2 then a bonus of
USD 1500/- is given to the employee. If the years of service are not greater than 2, then the
program should do nothing.
bonus = 0.0
currentyear = int(input("Enter current year :"))
yearofjoining = int(input("Enter year of joining :"))
yearofservice = currentyear – yearofjoining
if(yearofservice >2):
bonus = 1500
print("Bonus =%d" %bonus)
print("Congratulation! We are happy to provide you a bonus of %d" %bonus)
print("We appreciate your long term association with us!")
print("\nThis statement is not part of the above if condition because it is not indented as a
part of the if statement")
Example : In a xyz company, an employee is paid his remuneration under these condition:
If his basic salary is less than USD. 2000, then HRA = 10% of basic salary and DA = 90%
of basic salary. If his salary is either equal to or above USD. 2000, then HRA = 5% and DA
= 80% of basic salary. We will write a program to find his gross salary.
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example
Core Python does not provide switch / case statements as in other languages, but we can
use if..elif... statements to simulate switch case as follows:
Example :
Pizza choice example: Suppose you have visited a Pizza restaurant and you want to order a
pizza of your choice. Select Pizza from the menu.
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example
var = 1000
if var < 2000:
print ("Expression value is less than 2000")
if var == 1500:
print ("Which is 1500")
elif var == 1000:
print ("Which is 1000")
elif var == 500:
print ("Which is 500")
elif var < 500:
print ("Expression value is less than 500")
else:
print ("Could not find true expression")
In the above example, the variable var is assigned the value 1000 and
the first if statement checks if the var has less than 2000, the answer is yes,
the print statement is executed and
the below if condition is false,
so the elif statement executed,
it’s value is 1000 which is equal to the value in var so this is printed.
After that the rest statement is false so did not executed.
Finally the print statement which is outside of the if-elif-else construct is executed.
IF COMPREHENSION
example:
When reporting the number of characters in a string, instead of printing “0 character(s)”, “1
character (s)” or 10 character(s), we could use a couple of conditional expressions:
This will print “no characters”, “1 character”, “6 characters”, etc, which gives a much more
professional impression.
2. LOOPS.
A loop statement allows us to execute a statement or group of statements multiple times.
The following diagram illustrates a loop statement. Python programming language provides
a while loop to handle looping requirements.
The code in a while clause will be executed as long as the while statement’s condition is
True. In code, a while statement always consists of the following:
>>> x = 'spam'
>>> while x: # While x is not empty
print(x, end=' ') # In 2.X use print x,
x = x[1:]
spam pam am m
Note the end=' ' keyword argument used here to place all outputs on the same line
separated by a space;
0123456789
Compiled by: Michael Devine. 8884009669
PROGRAMMING WITH PYTHON 3.X.x – DECISION & REPETITION
You could also use a loop to ensure that the user enters a name, as follows:
name = ''
while not name:
name = input('Please enter your name: ')
print( 'Hello, %s!' % name)
name = ''
while not name or name.isspace():
name = input('Please enter your name: ')
print( 'Hello, %s!' % name)
name = ''
while not name.strip():
name = input('Please enter your name: ')
print( 'Hello, %s!' % name)
We could use relational or logical operators in the while loop for example:
while(i<=10)
while(i>=10 and j <=20)
while(j > 10 and (b<15) or c<20))
x=1
while x <= 10:
print( x);
x += 1
Calculation of simple interest. Ask user to input principal, rate of interest, number of years
counter = 1
while(counter <= 3):
principal = int(input("Enter the principal amount :"))
numberofyears = int(input("Enter the number of years :"))
rateofinterest = float(input("Enter the rate of interest :"))
simpleinterest = principal * numberofyears * rateofinterest/100
print("Simple interest =%.2f" %simpleinterest)
counter = counter + 1
Now that we’ve seen a few Python loops in action, it’s time to take a look at two simple
statements that have a purpose only when nested inside loops—the break and continue
statements.
While we’re looking at oddballs, we will also study the loop else clause here because it is
intertwined with break, and Python’s empty placeholder statement, pass (which is not tied
to loops per se, but falls into the general category of simple one-word statements).
In Python:
break
Jumps out of the closest enclosing loop (past the entire loop statement)
continue
Jumps to the top of the closest enclosing loop (to the loop’s header line)
pass
Does nothing at all: it’s an empty statement placeholder
Loop else block
Runs if and only if the loop is exited normally (i.e., without hitting a break)
If you use break , it will only take you out of the most recent loop
If you have a while ... : loop that contains a for ... in ... : loop indented within it, a
break within the for ... in ... : will not break out of the while ... : .
Both while ... : and for ... in ... : loops can have an else: statement at the end of the
loop, but it will be run only if the loop doesn’t end due to a break statement.
while test:
statements
if test:
break # Exit loop now, skip else if present
if test:
continue # Go to top of loop now
statements
statements
else: # Run if we didn't hit a 'break'
statements
PASS
If you want to code an infinite loop that does nothing each time through, do it with a
pass:
Because the body is just an empty statement, Python gets stuck in this loop. pass is roughly
to statements as None is to objects—an explicit nothing.
ELSE
The loop else clause is unique to Python. In its most complex form, the while
statement consists of a header line with a test expression, a body of one or more normally
indented statements, and an optional else part that is executed if control exits the loop
without a break statement being encountered. Python keeps evaluating the test at the top
and executing the statements nested in the loop body until the test returns a false value:
BREAK
There is a shortcut to getting the program execution to break out of a while loop’s
clause early. If the execution reaches a break statement, it immediately exits the while
loop’s clause. In code, a break statement simply contains the break keyword.
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
The first line creates an infinite loop; it is a while loop whose condition is always True.
The program execution will always enter the loop and will exit it only when a break
statement is executed.
CONTINUE
When the program execution reaches a continue statement, the program execution
immediately jumps back to the start of the loop and re-evaluates the loop’s condition.
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
ctr = 2
num = int(input("Enter a Number :"))
while(ctr <= num-1):
if(num % ctr == 0):
print("Number is not prime!")
break;
ctr = ctr + 1
The following piece of code determines whether a positive integer y is prime by searching
for factors greater than 1:
Rather than setting a flag to be tested when the loop is exited, it inserts a break where
a factor is found. This way, the loop else clause can assume that it will be executed
only if no factor is found;
If you don’t hit the break, the number is prime.
The loop else clause is also run if the body of the loop is never executed, as you don’t
run a break in that event either;
In a while loop, this happens if the test in the header is false to begin with.
Thus, in the preceding example you still get the “is prime” message if x is initially
less than or equal to 1 (for instance, if y is 2).