0% found this document useful (0 votes)
189 views52 pages

03 Python - Decision Making and Looping

This document discusses decision making and looping in Python. It covers if-else statements, if-elif-else statements, nested if-else statements, and using logical operators like 'and' and 'or' in conditions. It also discusses while and for loops, the range() function, break, continue and pass statements, and nesting of loops. Examples are provided for different types of decision making and looping programs. Exercises are included at the end to reinforce the concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
189 views52 pages

03 Python - Decision Making and Looping

This document discusses decision making and looping in Python. It covers if-else statements, if-elif-else statements, nested if-else statements, and using logical operators like 'and' and 'or' in conditions. It also discusses while and for loops, the range() function, break, continue and pass statements, and nesting of loops. Examples are provided for different types of decision making and looping programs. Exercises are included at the end to reinforce the concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 52

Python : Decision Making and Looping

Tushar B. Kute,
http://tusharkute.com
Decision Making Statement
if-elif-else

if condition: if condition:
1 statements statement-1
elif condition:
Statement-2
if condition: else: 3
2 Statement-1 Statement-3
else:
Statement-2
if-else

Previous line of indentation

Indentation
if-elif-else
Condition in if-else

• The condition in if-statement is parenthesis


free.
• The condition can have ‘and’ and ‘or’ operator.
• It should end with a colon.
• It must return either True or False.
• The zero value is considered as False
otherwise True.
– Example:
if True:
Exercise

• Write a program to read a number from


user and find whether number is odd or
even.
Nesting of if-else

• Example:
– Read three numbers from keyboard and
find largest of them. You are not allowed to
use ‘and’ and ‘or’ operators.
Example:
Example:

• Read an year and find whether that year is leap


or not?
• Conditions for being leap year:
– It should be divisible by four.
– If its a century year, it should be divisible by
400 also.
Solution:
Using ‘and’ and ‘or’
Repeatable elif

• Read marks in percentages from student and find


the grade of it as per below condition:
– Above 75% : ‘Distinction’
– 60% to below 75%: ‘First Class’
– 50% to below 60%: ‘Second Class’
– 40% to below 50%: ‘Pass Class’
– Below 40%: ‘Failed’
Solution
Another way
Creating menu based programs

• Python does not have switch-case


statement. So menu based programs are
created simply using if-elif-else.
• Example:
– Read a number from user and do the following
by showing menu:
• Find its square
• Find cube
• Check odd / even
• Check positive / negative
Solution:
Exercises

• Write a Python program to calculate profit or loss. Input is


selling cost and actual cost.
• Write a Python program to check whether a character is
uppercase or lowercase alphabet.
• Write a Python program to input electricity unit charges and
calculate total electricity bill according to the given condition:
– For first 50 units Rs. 0.50/unit
– For next 100 units Rs. 0.75/unit
– For next 100 units Rs. 1.25/unit
– For unit above 250 Rs. 1.50/unit
– An additional surcharge of 17% is added to the bill
Exercises

• Input -> basic salary


• Output -> gross salary
DA = 75% of basic
HRA = 20% of basic
• Conditions:
< 10000 : gross = da + basic
>= 10000 and < 20000 : gross = da + basic + 50% of hra
>= 20000 : gross = basic + da + hra
• Sample: Input and Output
5000 : 3750 + 5000 = 8750
12000 : 9000 + 12000 + 1200 = 22200
24000 : 18000 + 24000 + 4800 = 46800
Loops
The while loop

while condition: #compulsory


statement1
statement2
else: #optional
statements
Example-1

• Print your name for 10 number of times.


Exercise

• Find addition of first ten natural numbers. That


is, find addition of numbers from 1 to 10.
Solution
Exercise

• Find addition of all the odd numbers from 1 to


20. That is, find addition of numbers 1, 3, 5 …
19.
Solution
More about ‘while’
Infinite loop

• Be careful while using a while loop. Because if you


forget to increment the counter variable in python,
or write flawed logic, the condition may never
become false.
• In such a case, the loop will run infinitely, and the
conditions after the loop will starve.
• To stop execution, press Ctrl+C. However, an
infinite loop may actually be useful.
• While is the only loop where we can make while
loop intentionally infinite.
Examples:

2
The else statement

• A while loop may have an else statement after it.


When the condition becomes false, the block under
the else statement is executed.
• However, it doesn’t execute if you break out of the
loop or if an exception is raised.
Single statement while

• We can write single statement in while loop.


This statements will be separated by semicolon.
The ‘for’ loop

• Python for loop can iterate over a sequence or


collection of items.
• The structure of a for loop in Python is different
than that in C++ or Java.
• That is, for(int i=0;i<n;i++) won’t work here. In
Python, we use the ‘in’ keyword.
• Syntax:
for n in sequence:
statements
n : variable
sequence: collection of elements
while vs for loop

while loop for loop

Can have condition for


Don’t have any loop condition
iteration
The counter can be The loop can iterate through
incremented or decremented sequence by one increment
by any number only

The loop can be infinite This loop can’t be infinite


Examples:

>>> for n in 1,6,7,8,4:


... print(n, end=' ') Same sequence

...
1 6 7 8 4
>>> for n in 1,6,7,8,4:
... print(n*n, end=' ') Operation on data

...
1 36 49 64 16
>>> for n in 'h',23,3.12,12:
... print(n, end=' ') Mixed Elements
...
h 23 3.12 12
More on ‘for’ loop
The range( ) function

• This function yields a sequence of numbers. When called


with one argument, say n, it creates a sequence of
numbers from 0 to n-1.
• Example:
>>> arr = range(10)
>>> list(arr)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arr = range(1,6)
>>> list(arr)
[1, 2, 3, 4, 5]
>>> arr = range(1,12,2)
Using range( ) function

>>> for x in range(10):


print(x, end=' ')

0 1 2 3 4 5 6 7 8 9
>>> for x in range(1,10,2):
print(x, end=' ')

1 3 5 7 9
The range( ) decrement operation

>>> arr = range(12,2,-2)


>>> list(arr)
[12, 10, 8, 6, 4]
Iterating through sequence

X = [4,7,9,1,5] # list
>>> for num in x:
print(num, end=' ')

4 7 9 1 5
>>> s = 'MITU Skillologies' # string
>>> for data in s:
print(data, end=' ')

M I T U S k i l l o l o g i e s
Collection of strings

>>> col = ['Mar','Hin','San','Nep']


>>> for name in col:
print(name)
Mar
Hin
San
Nep
The else statement

• Like a while loop, a for-loop may also have an else


statement after it. When the loop is exhausted,
the block under the else statement executes.
>>> for x in range(10):
print(x, end=' ')
else:
print('Loop Ended')

0 1 2 3 4 5 6 7 8 9 Loop Ended
Example:

• Print your name 10 times using for loop.


Example:

• Find addition of first 10 natural numbers using


for loop.
Example:

• Find addition of all odd numbers from 1 to 20


using for loop.
Exercises

• Read a number from user and find the factorial of


the number.
• Take a number user input and find sum of digits of
this number.
• Write a program to print all the odd numbers from
10 to 30.
• Read a number from keyboard and print it in
reverse.
• Write a program to print Fibonacci series up to n
terms.
Nesting of loops

• You can also nest a loop inside another.


• You can put a for loop inside a while, or a while
inside a for, or a for inside a for, or a while inside
a while.
• Or you can put a loop inside a loop inside a loop.
You can go as far as you want.
Nesting of loops
The ‘break’ statement

• When you put a break statement in the body of


a loop, the loop stops executing, and control
shifts to the first statement outside it. You can
put it in a for or while loop.
The ‘continue’ statement

• When the program control reaches the continue


statement, it skips the statements after ‘continue’.
• It then shifts to the next item in the sequence and
executes the block of code for it. You can use it
with both for and while loops.
The ‘pass’ statement

• We use the pass statement to implement stubs.


• When we need a particular loop, class, or function
in our program, but don’t know what goes in it, we
place the pass statement in it.
• It is a null statement.
• The interpreter does not ignore it, but it performs a
no-operation (NOP).
• It is used to fill indented space
Exercises

• Write a program to check whether entered number if prime


or not.
• Write a program to print all the prime numbers from 5 to 50.
• Print following pattern:
1
22
333
4444
55555
• Find power of x raised to y from user input.
Thank you
This presentation is created using LibreOffice Impress 5.1.6.2, can be used freely as per GNU General Public License

/mITuSkillologies @mitu_group /company/mitu- c/MITUSkillologies


skillologies

Web Resources
http://mitu.co.in
http://tusharkute.com

contact@mitu.co.in
tushar@tusharkute.com

You might also like