0% found this document useful (0 votes)
4 views46 pages

Conditions Statetements

The document provides an overview of flow control in programming, focusing on conditional statements (if, else, elif) and loops (for, while). It includes syntax examples, explanations of nested statements, and the use of break, continue, and pass statements. Additionally, it contrasts for and while loops, highlighting their appropriate use cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views46 pages

Conditions Statetements

The document provides an overview of flow control in programming, focusing on conditional statements (if, else, elif) and loops (for, while). It includes syntax examples, explanations of nested statements, and the use of break, continue, and pass statements. Additionally, it contrasts for and while loops, highlighting their appropriate use cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Agenda

Flow Control:
1. if...else Statement
2. Loops
 For Loop
 While Loop
3. break and continue
4. pass Statement
if...else Statement

• if statement to run a block code only when a certain condition is met.


For example, assigning grades (A, B, C) based on marks obtained by a student.

• if the percentage is above 90, assign grade A


• if the percentage is above 75, assign grade B
• if the percentage is above 65, assign grade C
Three forms of the if...else statement
• if statement
• if...else statement
• if...elif...else statement
• Nested if
if statement
The syntax of if statement

• if condition:
# body of if statement

The if statement evaluates condition.


• If condition is evaluated to True, the code inside the body of if is executed.
• If condition is evaluated to False, the code inside the body of if is skipped.
Class Example
def flow_if_exercise():
number = 10
# check if number is greater than 0
if number > 0:
print('Number is positive.')
print('General statement')

flow_if_exercise()
if...else Statement

An if statement can have an optional else clause.

The syntax of if...else statement is:


if condition:
# block of code if condition is True
else:
# block of code if condition is False

The if...else statement evaluates the given condition:


• If the condition evaluates to True,
– the code inside if is executed
– the code inside else is skipped
• If the condition evaluates to False,
– the code inside else is executed
– the code inside if is skipped
Class Example
def flow_if_else_exercise():
number = 10
if number > 0:
print('Positive number')
else:
print('Negative number')
print('This statement is always executed')
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, then
we use the if...elif...else statement.
• The syntax of the if...elif...else statement is:
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
• If condition1 evaluates to true, code block 1 is executed.
• If condition1 evaluates to false, then condition2 is evaluated.
– If condition2 is true, code block 2 is executed.
– If condition2 is false, code block 3 is executed.
Class Example
• number = 0
if number > 0:
print("Positive number")
elif number == 0:
print('Zero')
else:
print('Negative number')
print('This statement is always executed')
Nested if statements
• if statement inside of an if statement. This is known as a nested
if statement.
• The syntax of nested if statement is:
# outer if statement
if condition1:
# statement(s)
# inner if statement
if condition2:
# statement(s)
• We can add else and elif statements to the inner if statement as required.
• We can also insert inner if statement inside the
outer else or elif statements(if they exist)
• We can nest multiple layers of if statements.
Nested if Statement

• 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')
pass Statement
if statements cannot be empty, but for some reason have an if statement with
no content, put in the pass statement to avoid getting an error.
Example:

# pass statement
a = 33
b = 200
if b > a:
pass
Combined Example
# this program is about flow control
a = 12
b = 13
c = 90

def if_statment():
if (a > b):
print("a is greater than b")

def if_else_statment():
if (a > b):
print("a is greater than b")
else:
print("a is less than b")

def if_elif_else_statment():
if (a > b):
print("a is greater than b")
elif (a == b):
print("a is equal to b")
else:
print("a is less than b")

def nested_if_statment():
if (a > b):
print("a is greater than b")
if (a == b):
print("a is equal to b")
else:
print("a is less than b")

def if_pass_statment():
if (a > b):
pass
else:
print("a is less than b")

def if_elif_else_new_sameple():
if(c >= 95):
print('Assign grade A')
elif(c >= 90 and c < 95):
print('Assign grade B')
elif(c >= 80 and c < 90):
print('Assign grade C')
else:
print('Assign grade D')

if_elif_else_new_sameple()

if_statment()
if_else_statment()
if_elif_else_statment()
nested_if_statment()
if_pass_statment()
For Loops

• A for loop is used for iterating over a sequence (that is either a list, a tuple,
a dictionary, a set, or a string).

Syntax:
for var in iterable:
# statements
Example

Ex: 1
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

Ex: 2
languages = ['Swift', 'Python', 'Go', 'JavaScript‘]
for language in languages:
print(language)
Looping Through a String

• Even strings are iterable objects, they contain a sequence of characters

Example:
Loop through the letters in the word "banana“
for x in "banana":
print(x)
For Loop in Dictionary

# Iterating over dictionary


print("Dictionary Iteration")

d = dict()

d['xyz'] = 123
d['abc'] = 345
for i in d:
print("% s % d" % (i, d[i]))
Loop with range() function

• A range is a series of values between two numeric intervals.


• We use Python's built-in function range() to define a range of values.

Example:

values = range(4)
Here, 4 inside range() defines a range containing values 0, 1, 2, 3.
Example
Ex: 1
# use of range() to define a range of values
values = range(4)
for i in values:
print(i)

Ex: 2
for i in range(6):
print(i)
Using the start parameter
Example:

for x in range(2, 6):


print(x)
For Loop with a Increment number

• The range() function defaults to increment the sequence by 1, however it


is possible to specify the increment value by adding a third
parameter: range(2, 30, 3)

Example:
for x in range(2, 30, 3):
print(x)
Using a for Loop Without Accessing Items

It is not mandatory to use items of a sequence within a for loop.


Example:
languages = ['Swift', 'Python', 'Go']
for language in languages:
print('Hello')
print('Hi')
If we do not intend to use items of a sequence within the loop, we can write
the loop like this:
Example:
languages = ['Swift', 'Python', 'Go']
for _ in languages:
print('Hello')
print('Hi')
for loop with else

• A for loop can have an optional else block. The else part is executed when
the loop is exhausted (after the loop iterates through every item of a
sequence).

Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
For loop with else
• The else block will NOT be executed if the loop is stopped by
a break statement.

Example:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
break Statement

• With the break statement we can stop the loop before it has looped
through all the items
Ex 1:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Ex 2:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
continue Statement

• With the continue statement we can stop the current iteration of the loop,
and continue with the next

Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
Nested Loops

• A nested loop is a loop inside a loop.


• The "inner loop" will be executed one time for each iteration of the "outer
loop":
Ex 1:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)

Ex 2:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
For Loop with Zip()

• This code uses the zip() function to iterate over two lists (fruits and
colors) in parallel. The for loop assigns the corresponding elements
of both lists to the variables fruit and color in each iteration.

Example:
fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "green"]
for fruit, color in zip(fruits, colors):
print(fruit, "is", color)
pass Statement

• for loops cannot be empty, but if you for some


reason have a for loop with no content, put in
the pass statement to avoid getting an error.

Example:
for x in [0, 1, 2]:
pass
For Loop with Tuple

• This code iterates over a tuple of tuples using a for loop with tuple
unpacking

Example:
t = ((1, 2), (3, 4), (5, 6))
for a, b in t:
print(a, b)
While Loop

• While Loop is used to execute a block of statements repeatedly until a


given condition is satisfied. And when the condition becomes false, the
line immediately after the loop in the program is executed.
• While loop falls under the category of indefinite iteration. Indefinite
iteration means that the number of times the loop is executed isn’t
specified explicitly in advance.
Example
count = 0
while (count < 3):
count = count + 1
print(“Python Learning!")
Example
# program to calculate the sum of numbers
# until the user enters zero

def calculate_sum():
total = 0
number = int(input('Enter a number: '))

# add numbers until number is zero


while number != 0:
total += number # total = total + number
# take integer input again
number = int(input('Enter a number: '))

print('total =', total)


While loop with list

# checks if list still contains any element


def list_while():
a = [1, 2, 3, 4]

while a:
print(a.pop())
Single statement while block

# Single statement while block


def single_while():
count = 0
while (count < 5): count += 1; print("Hello Everyone")
Infinite while Loop

# To check indefinite condition


def indefinite_while():
age = 32
# the test condition is always True
while age > 18:
print('You can vote')
While loop with else

• 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
• The else block just after while is executed only
when the loop is NOT terminated by a break
statement
Example
def while_else_one():
counter = 0
while counter < 3:
print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Example
def while_else():
i=0
while i < 4:
i += 1
print(i)
else: # Executed because no break in for
print("No Break\n")
While with break
• With the break statement we can stop the loop even if the while condition
is true:
Example:
# Practice while with break
def while_break():
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
While with else and break
# Practice while with else and break
def while_else_break():
i=0
while i < 4:
i += 1
print(i)
break
else: # Not executed as there is a break
print("No Break")
Example
def while_else_break1():
counter = 0
while counter < 3:
# loop ends because of break
# the else part is not executed
if counter == 1:
break

print('Inside loop')
counter = counter + 1
else:
print('Inside else')
While with continue
• With the continue statement we can stop the current iteration, and
continue with the next:
# Practice while with continue
def while_continue():
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
for Vs while loops

• For loop is usually used when the number of iterations is known.


For example:
# this loop is iterated 4 times (0 to 3)
for i in range(4):
print(i)
for Vs while loops
• loop is usually used when the number of iterations is unknown.
For example:
while condition:
# run code until the condition evaluates to False
While loop on Boolean values

# Practice while loop on boolean value


def while_boolean():
# Initialize a counter
count = 0
# Loop infinitely
while True:
# Increment the counter
count += 1
print(f"Count is {count}")

# Check if the counter has reached a certain value


if count == 10:
# If so, exit the loop
break
# This will be executed after the loop exits
print("The loop has ended.")

You might also like