0% found this document useful (0 votes)
19 views15 pages

Python Control Flow

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
19 views15 pages

Python Control Flow

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

Python if...

else Statement

In computer programming, the if statement is a conditional statement. It is used to

execute a block of code only when a specific condition is met. For example,

Suppose we need to assign different grades to students based on their scores.

1. If a student scores above 90, assign grade A

2. If a student scores above 75, assign grade B

3. If a student scores above 65, assign grade C

These conditional tasks can be achieved using the if statement.

Python if Statement

An if statement executes a block of code only when the specified condition is met.

Syntax

if condition:
# body of if statement

Here, condition is a boolean expression, such as number > 5, that evaluates to

either True or False.

 If condition evaluates to True, the body of the if statement is executed.


 If condition evaluates to False, the body of the if statement will be skipped from

execution.

Let's look at an example.

Working of if Statement

Example: Python if Statement


number = int(input('Enter a number: '))

# check if number is greater than 0


if number > 0:
print(f'{number} is a positive number.')

print('A statement outside the if statement.')

Python if...else Statement


An if statement can have an optional else clause. The else statement executes if
the condition in the if statement evaluates to False.
Syntax
if condition:
# body of if statement
else:
# body of else statement

Here, if the condition inside the if statement evaluates to


 True - the body of if executes, and the body of else is skipped.
 False - the body of else executes, and the body of if is skipped
Let's look at an example.

Working of if…else Statement

Example: Python if…else Statement


number = int(input('Enter a number: '))

if number > 0:
print('Positive number')
else:
print('Not a positive number')

print('This statement always executes')

Python if…elif…else Statement


The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, we use
the if...elif...else statement.
Syntax

if condition1:
# code block 1

elif condition2:
# code block 2

else:
# code block 3

Let's look at an example.

Working of if…elif…else Statement

Example: Python if…elif…else Statement


number = -5

if number > 0:
print('Positive number')

elif number < 0:


print('Negative number')

else:
print('Zero')

print('This statement is always executed')

Python Nested if Statements


It is possible to include an if statement inside another if statement. For example,
number = 5

# outer if statement
if number >= 0:
# inner if statement
if number == 0:
print('Number is 0')

# inner else statement


else:
print('Number is positive')

# outer else statement


else:
print('Number is negative')

Ternary Operator in Pythonif...else


Python doesn't have a ternary operator. However, we can use if...else to work like a ternary
operator in other languages. For example,
grade = 40
if grade >= 50:
result = 'pass'
else:
result = 'fail'

print(result)
Run Code
can be written as
grade = 40

result = 'pass' if number >= 50 else 'fail'

print(result)
If needed, we can use logical operators such as and and or to create complex
conditions to work with an if statement.
age = 35
salary = 6000

# add two conditions using and operator


if age >= 30 and salary >= 5000:

print('Eligible for the premium membership.')


else:
print('Not eligible for the premium membership')

Python for Loop


In Python, we use a for loop to iterate over sequences such
as lists, strings, dictionaries, etc.
languages = ['Swift', 'Python', 'Go']

# access elements of the list one by one


for lang in languages:
print(lang)
In the above example, we have created a list named languages. As the list has 3
elements, the loop iterates 3 times.
The value of lang is
 Swift in the first iteration.
 Python in the second iteration.
 Go in the third iteration.

 for loop Syntax


 for val in sequence:
 # body of the loop

 The for loop iterates over the elements of sequence in order. In each iteration, the
body of the loop is executed.
 The loop ends after the last item in the sequence is reached.

 Indentation in Loop
 In Python, we use indentation to define a block of code, such as the body of a loop. For
example,
 languages = ['Swift', 'Python', 'Go']

 # Start of loop
 for lang in languages:
 print(lang)
 print('-----')
 # End of for loop

 print('Last statement')
 Run Code

 Example: Loop Through a String


 language = 'Python'

 # iterate over each character in language
 for x in language:
 print(x)

for Loop with Python range()


In Python, the range() function returns a sequence of numbers. For example,

values = range(4)

Here, range(4) returns a sequence of 0, 1, 2 ,and 3.


Since the range() function returns a sequence of numbers, we can iterate over it using
a for loop. For example,
# iterate from i = 0 to i = 3
for i in range(4):
print(i)
Here, we used the for loop to iterate over a range from 0 to 3.
This is how the above program works.
Iteration Value of i print(i) Last item in sequence?

1st 0 Prints 0 No

2nd 1 Prints 1 No

3rd 2 Prints 2 No

Yes
4th 3 Prints 3
The loop terminates.

Tip: We can end a for loop before iterating through all the items by using a break
statement.

A for loop can have an optional else clause. This else clause executes after the
iteration completes.
digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")
We can also use for loop to repeat an action a certain number of times. For example,
languages = ['Swift', 'Python', 'Go']

# looping to repeat an action without using the list elements


for language in languages:
print('Hi')
Run Code
Output

Hi
Hi
Hi

Here, we used the list languages to run the loop three times. However, we didn't use
any of the elements of the list.
In such cases, it is clearer to use the _ (underscore) as the loop variable.
The _ indicates that a loop variable is a placeholder and its value is intentionally being
ignored.
For example,
languages = ['Swift', 'Python', 'Go']
# using _ for placeholder variable
for _ in languages:
print('Hi')
Run Code
Here, the loop still runs three times because there are three elements in
the languages list. Using _ indicates that the loop is there for repetition and not for
accessing the elements.

A for loop can also have another for loop inside it. For each cycle of the outer loop,
the inner loop completes its entire sequence of iterations. For example,
# outer loop
for i in range(2):
# inner loop
for j in range(2):
print(f"i = {i}, j = {j}")

Python while Loop


In Python, we use a while loop to repeat a block of code until a certain condition is
met. For example,
number = 1

while number <= 3:


print(number)
number = number + 1

while Loop Syntax

while condition:
# body of while loop

Here,
1. The while loop evaluates condition, which is a boolean expression.
2. If the condition is True, body of while loop is executed. The condition is evaluated again.
3. This process continues until the condition is False.
4. Once the condition evaluates to False, the loop terminates.

Tip: We should update the variables used in condition inside the loop so that it eventually
evaluates to False. Otherwise, the loop keeps running, creating an infinite loop.
Flowchart of Python while Loop

Flowchart of Python while Loop

Example: Python while Loop


# Print numbers until the user enters 0
number = int(input('Enter a number: '))

# iterate until the user enters 0


while number != 0:
print(f'You entered {number}.')
number = int(input('Enter a number: '))

print('The end.')

Infinite while Loop


If the condition of a while loop always evaluates to True, the loop runs continuously, forming
an infinite while loop. For example,
age = 32

# The test condition is always True


while age > 18:
print('You can vote')
We can use a break statement inside a while loop to terminate the loop immediately
without checking the test condition. For example,
while True:
user_input = input('Enter your name: ')

# terminate the loop when user enters end


if user_input == 'end':
print(f'The loop is ended')
break

print(f'Hi {user_input}')
in Python, a while loop can have an optional else clause - that is executed once the
loop condition is False. For example,
counter = 0

while counter < 2:


print('This is inside loop')
counter = counter + 1
else:
print('This is inside else block')

Python break and continue


In programming, the break and continue statements are used to alter the flow of loops:
 break exits the loop entirely
 continue skips the current iteration and proceeds to the next one

Python break Statement


The break statement terminates the loop immediately when it's encountered.
Syntax

break

Working of Python break Statement

Working of break Statement in Python


The above image shows the working of break statements in for and while loops.

Note: The break statement is usually used inside decision-making statements such as if...else.
Example: break Statement with for Loop
We can use the break statement with the for loop to terminate the loop when a certain
condition is met. For example,
for i in range(5):
if i == 3:
break
print(i)

Python continue Statement


The continue statement skips the current iteration of the loop and the control flow of
the program goes to the next iteration.
Syntax

continue

Working of continue Statement in Python

Example: continue Statement with for Loop


We can use the continue statement with the for loop to skip the current iteration of
the loop and jump to the next iteration. For example,
for i in range(5):
if i == 3:
continue
print(i)
Python range() Function
The Python range() function generates a sequence of numbers.
By default, the sequence starts at 0, increments by 1, and stops before the specified
number.
Example
# create a sequence from 0 to 3
numbers = range(4)

# iterating through the sequence


for i in numbers:
print(i)

range() Syntax

range(start, stop, step)

The start and step arguments are optional.

range() Return Value


The range() function returns an immutable sequence of numbers.

Example 1: range(stop)
# create a sequence from 0 to 3 (4 is not included)
numbers = range(4)

# convert to list and print it


print(list(numbers)) # Output: [0, 1, 2, 3]

Example 2: range(start, stop)


# create a sequence from 2 to 4 (5 is not included)
numbers = range(2, 5)
print(list(numbers)) # [2, 3, 4]

# create a sequence from -2 to 3


numbers = range(-2, 4)
print(list(numbers)) # [-2, -1, 0, 1, 2, 3]

# creates an empty sequence


numbers = range(4, 2)
print(list(numbers)) # []

Example 3: range(start, stop, step)


# create a sequence from 2 to 10 with increment of 3
numbers = range(2, 10, 3)
print(list(numbers)) # [2, 5, 8]

# create a sequence from 4 to -1 with increment of -1


numbers = range(4, -1, -1)
print(list(numbers)) # [4, 3, 2, 1, 0]

# range(0, 5, 1) is equivalent to range(5)


numbers = range(0, 5, 1)
print(list(numbers)) # [0, 1, 2, 3, 4]
Run Code

range() in for Loop


The range() function is commonly used in for loop to iterate the loop a certain number
of times. For example,
# iterate the loop five times
for i in range(5):
print(f'{i} Hello')

Python pass Statement


In Python programming, the pass statement is a null statement which can be used as a
placeholder for future code.
Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. In such cases, we can use the pass statement.
The syntax of the pass statement is:

pass

Using pass With Conditional Statement


n = 10

# use pass inside if statement


if n > 10:
pass

print('Hello')
Run Code
Here, notice that we have used the pass statement inside the if statement .
However, nothing happens when the pass is executed. It results in no operation (NOP).
Suppose we didn't use pass or just put a comment as:
n = 10

if n > 10:
# write code later

print('Hello')
Here, we will get an error message: IndentationError: expected an indented
block

Note: The difference between a comment and a pass statement in Python is that while
the interpreter ignores a comment entirely, pass is not ignored.

Use of pass Statement inside Function or Class


We can do the same thing in an empty function or class as well. For example,

def function(args):
pass
class Example:
pass

You might also like