Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

L10_M1_Python If-else_loops_

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

L10_M1_Python If-else_loops_

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Amity School of Engineering &

Technology

PYTHON IF-ELSE STATEMENTS


Amity School of Engineering &
Technology
What are Conditional Statements?
Conditional Statement in Python perform different computations or actions
depending on whether a specific Boolean constraint evaluates to true or false.
Conditional statements are handled by IF statements in Python.

Python if Statement Syntax


if test expression:
statement(s)

Here, the program evaluates the test expression and will execute statement(s)
only if the test expression is True.

If the test expression is False, the statement(s) is not executed.


Amity School of Engineering &
Technology
Example: Python if Statement
# If the number is positive, we print an
appropriate message

num = 3
if num > 0:
print(num, "is a positive number.")
print("This is for 3.")

num = -1
if num > 0:
print(num, "is a negative number.")
print("This is for -1.")

When you run the program, the output will be:

3 is a positive number
This is for 3
This is for -1
Amity School of Engineering &
Technology

Indentation
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for
this purpose.
Amity School of Engineering &
Technology
Python if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else

The if..else statement evaluates test expression and will execute the body of if
only when the test condition is True.

If the condition is False, the body of else is executed. Indentation is used to


separate the blocks.
Amity School of Engineering &
Technology
Example of if...else

# Program checks if the number is positive


or negative
# And displays an appropriate message

num = 3

# Try these two variations as well.


# num = -5
# num = 0

if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Amity School of Engineering &
Technology
Python if...elif...else Statement
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

The elif is short for else if. It allows us to check for multiple expressions.

If the condition for if is False, it checks the condition of the next elif block and so
on.

If all the conditions are False, the body of else is executed.

Only one block among the several if...elif...else blocks is executed according to
the condition.

The if block can have only one else block. But it can have multiple elif blocks.
Amity School of Engineering &
Technology

Example of if...elif...else
'''In this program, we check if the number is positive or negative or zero and
display an appropriate message'''

num = 3.4

# Try these two variations as well:


# num = 0
# num = -4.5

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Amity School of Engineering &
Python Nested if statements Technology

We can have a if...elif...else statement inside another if...elif...else statement.


This is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation
is the only way to figure out the level of nesting. They can get confusing, so
they must be avoided unless necessary.
'''In this program, we input a number check if the number is positive or negative
or zero and display an appropriate message This time we use nested if
statement'''
num = float(input("Enter a number: ")) Output 2
if num >= 0:
if num == 0: Enter a number: -1
print("Zero") Negative number
else:
print("Positive number")
else: Output 3
print("Negative number")
Enter a number: 0
Output 1 Zero
Enter a number: 5
Positive number
Amity School of Engineering &
Technology
Loops
There are two types of loops in Python, for and while.
for in Loop: For loops are used for sequential traversal. For example: traversing a
list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i+
+). There is “for in” loop which is similar to for each loop in other languages. Let us
learn how to use for in loop for sequential traversals.

Syntax:

for iterator_var in sequence:


statements(s)

Example : It can be used to iterate over a range and iterators.


# Python program to illustrate Output :
# Iterating over range 0 to n-1
0
n=4 1
for i in range(0, n): 2
print(i) 3
Amity School of Engineering &
Technology
# Python program to illustrate
# Iterating over a list
print("List Iteration")
l = [“AMITY", “UNIVERSITY", “GWALIOR"]
for i in l:
print(i)
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = (“amity", “university", "gwalior")
for i in t:
print(i)
# Iterating over a String
print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)
# Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))
Amity School of Engineering &
Technology
Iterating by index of sequences: We can also use the index of elements in the
sequence to iterate. The key idea is to first calculate the length of the list and in
iterate over the sequence within the range of this length.

example: # Python program to illustrate


# Iterating by index

list = [“amity", “university", "gwalior"]


for index in range(len(list)):
print list[index]
Amity School of Engineering &
Technology
Using else statement with for loops: We can also combine else statement with for
loop like in while loop. But as there is no condition in for loop based on which the
execution will terminate so the else block will be executed immediately after for
block finishes execution.
Example explains how to do this:
# Python program to illustrate
# combining else with for

list = [“amity", “university", "gwalior"]


for index in range(len(list)):
print list[index]
else:
print "Inside Else Block"

Output:

amity
university
gwalior
Inside Else Block
Amity School of Engineering &
Technology
Nested Loops: Python programming language allows to use one loop inside
another loop. Following section shows few examples to illustrate the concept.
Syntax:

for iterator_var in sequence:


for iterator_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)

A final note on loop nesting is that we can put any type of loop inside of any other
type of loop. For example a for loop can be inside a while loop or vice versa.
Amity School of Engineering &
Technology

# Python program to illustrate


# nested for loops in Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()

Output:

?????
Amity School of Engineering &
Technology
Loop Control Statements: Loop control statements change execution from its
normal sequence. When execution leaves a scope, all automatic objects that were
created in that scope are destroyed. Python supports the following control
statements.
Continue Statement: It returns the control to the beginning of the loop.

# Prints all letters except ‘t' and ‘y'


for letter in ‘amity':
if letter == 'e' or letter == ‘m':
continue
print 'Current Letter :', letter
var = 10

Output:?
Amity School of Engineering &
Technology
Break Statement: It brings control out of the loop
for letter in ‘amityuniversitygwalior':

# break the loop as soon it sees ‘w'


# or ‘o'
if letter == ‘w' or letter == ‘o':
break

print 'Current Letter :', letter

Output:

Current Letter : e
Amity School of Engineering &
Technology
Pass Statement: We use pass statement to write empty loops. Pass is also
used for empty control statement, function and classes.

# An empty loop
for letter in ‘amity':
pass

Output:

Exercise: How to print a list in reverse order (from last to first item) using while
and for in loops.
Amity School of Engineering &
Technology
While Loop:
In python, while loop is used to execute a block of statements repeatedly until a
given a condition is satisfied. And when the condition becomes false, the line
immediately after the loop in program is executed.
Syntax :

while expression:
statement(s)

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.
Example:

# Python program to illustrate


# while loop Output:
count = 0
while (count < 3):
count = count + 1
print("Hello Amity")
Amity School of Engineering &
Technology
Using else statement with while loops: As discussed above, while loop executes
the block until a condition is satisfied. When the condition becomes false, the
statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you
break out of the loop, or if an exception is raised, it won’t be executed.
If else like this:

if condition:
# execute these statements
else:
# execute these statements

while condition:
# execute these statements
else:
# execute these statements
Amity School of Engineering &
Technology
Example: Output:
#Python program to illustrate
# combining else with while
count = 0
while (count < 3):
count = count + 1
print("Hello amity")
else:
print("In Else Block")

Single statement while block: Just like the if block, if the while block consists
of a single statement the we can declare the entire loop in a single line as
shown below:
Note: It is suggested not to use this
# Python program to illustrate
type of loops as it is a never ending
# Single statement while block
infinite loop where the condition is
count = 0
always true and you have to
while (count == 0): print("Hello amity")
forcefully terminate the compiler.
Amity School of Engineering &
Technology

You might also like