UNIT 2 FINAL - New
UNIT 2 FINAL - New
PYTHON IF…ELSE
In this article, you will learn to create decisions in a Python program using different forms of
if..else statement.
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the
text expression is True.
If the text expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.
Python if Statement Flowchart
3 is a positive number
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only
when test condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the
blocks.
Python if..else Flowchart
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")
In the above example, when num is equal to 3, the test expression is true and body of if is
executed and body of else is skipped.
If num is equal to -5, the test expression is false and body of else is executed and body
of if is skipped.
If num is equal to 0, the test expression is true and body of if is executed and body of else is
skipped.
if test expression:
Body of if
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, 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.
Flowchart of if...elif...else
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")
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
In this article, you'll learn to iterate over a sequence of elements using the different variations
of for loop.
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is
The sum is 48
This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().
print(range(10))
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
We can use the range() function in for loops to iterate through a sequence of numbers. It can
be combined with the len() function to iterate though a sequence using indexing. Here is an
example.
# Program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])
I like pop
I like rock
I like jazz
break statement can be used to stop a for loop. In such case, the else part is ignored.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts,
it executes the block of code in the else and prints
No items left.
Loops are used in programming to repeat a specific block of code. In this article, you will
learn to create a while loop in Python.
We generally use this loop when we don't know beforehand, the number of times to iterate.
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
Flowchart of while Loop
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as our counter variable i is
less than or equal to n (10 in our program).
We need to increase the value of counter variable in the body of the loop. This is very
important (and mostly forgotten). Failing to do so will result in an infinite loop (never ending
loop).
# Example to illustrate
# the use of else statement
# with the while loop
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Output
Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string Inside loop three times.
On the forth iteration, the condition in while becomes False. Hence, the else part is
executed.
In this article, you will learn to use break and continue statements to alter the flow of a loop.
Loops iterate over a block of code until test expression is false, but sometimes we wish to
terminate the current iteration or even the whole loop without checking test expression.
If break statement is inside a nested loop (loop inside another loop), break will terminate the
innermost loop.
Syntax of break
break
Flowchart of break
The working of break statement in for loop and while loop is shown below.
Output
s
t
r
The end
In this program, we iterate through the "string" sequence. We check if the letter is "i",
upon which we break from the loop. Hence, we see in our output that all the letters up
till "i" gets printed. After that, the loop terminates.
Syntax of Continue
continue
Flowchart of continue
The working of continue statement in for and while loop is shown below.
Output
s
t
r
n
g
The end
This program is same as the above example except the break statement has been replaced
with continue.
We continue with the loop, if the string is "i", not executing the rest of the block. Hence, we
see in our output that all the letters except "i" gets printed.
In this article, you'll learn about pass statement. It is used as a placeholder for future
implementation of functions, loops, etc.
Syntax of pass
pass
Suppose we have a loop or a function that is not implemented yet, but we want to implement
it in the future. They cannot have an empty body. The interpreter would complain. So, we
use the pass statement to construct a body that does nothing.
Example: pass Statement
# pass is just a placeholder for
# functionality to be added later.
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
def function(args):
pass
class example:
pass