0% found this document useful (0 votes)
2 views36 pages

Python - Conditional and Loops

The document provides an overview of conditional statements and loops in Python, including if, if-else, elif, nested if-else, and match-case statements. It also covers for loops, while loops, and their control statements like break and continue, along with examples demonstrating their usage. Additionally, it discusses the range function and the else clause in loops, emphasizing the importance of ensuring loops terminate correctly.

Uploaded by

zdacoseo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views36 pages

Python - Conditional and Loops

The document provides an overview of conditional statements and loops in Python, including if, if-else, elif, nested if-else, and match-case statements. It also covers for loops, while loops, and their control statements like break and continue, along with examples demonstrating their usage. Additionally, it discusses the range function and the else clause in loops, emphasizing the importance of ensuring loops terminate correctly.

Uploaded by

zdacoseo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CONDITIONAL STATEMENTS IN

PYTHON
IF CONDITIONAL STATEMENT

 If statement is the simplest form of a conditional statement. It


executes a block of code if the given condition is true.

If Statement
if (condition):
TRUE #This block will execute
IF ELSE CONDITIONAL STATEMENT

 If Else allows us to specify a block of code that will execute if the


condition(s) associated with an if or elif statement evaluates to
False. Else block provides a way to handle all other cases that
don't meet the specified conditions.
If…Else Statement
if (condition):
TRUE #This block will execute
else:
FASLE #This block will execute
IF ELSE CONDITIONAL STATEMENT

 Example
age = 10
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
Output:
Travel for free.
ELIF STATEMENT

 elif statement in Python stands for "else if." It allows us to check


multiple conditions, providing a way to execute different blocks
of code based on which condition is true. Using elif statements
makes our code more readable and efficient by eliminating the
need for multiple nested if statements.
ELIF STATEMENT

 Example:
NESTED IF..ELSE CONDITIONAL
STATEMENT
 Nested if..else means an if-else statement inside another if
statement. We can use nested if statements to check conditions
within conditions.
NESTED IF..ELSE CONDITIONAL
STATEMENT
 Example
TERNARY CONDITIONAL STATEMENT

 A ternary conditional statement is a compact way to write an if-


else condition in a single line. It’s sometimes called a
"conditional expression."
MATCH-CASE STATEMENT

 Match-case statement is Python's version of a switch-case


found in other languages. It allows us to match a variable's value
against a set of patterns.

[Link]
SINGLE STATEMENT SUITES IN
PYTHON
SINGLE STATEMENT

 If the suite (block of code) following


the if, for or while statement consists only of one line of code,
we can place it on the same line as the statement, immediately
after the colon:
The following code falls into an infinite loop, so you’d better not run it. Instead of
writing:

[Link]
PYTHON FOR LOOPS
PYTHON 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).
 This is less like the for keyword in other programming languages,
and works more like an iterator method as found in other object-
orientated programming languages.
 With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.
WHAT IS FOR LOOP IN PYTHON?

Syntax of for Loop


for val in sequence:
loop body

 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 separated from the rest of the code using
indentation.
WHAT IS FOR LOOP IN PYTHON?

Flowchart of for Loop


EXAMPLE

Print each fruit in a fruit list:


fruits = ["apple", "banana", "cherry"]

for x in fruits:
print(x)

OUTPUT
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)
OUTPUT
THE BREAK STATEMENT

 With the break statement we can stop the loop before it has
looped through all the items:
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
OUTPUT:
SAMPLE PROBLEM

Exit the loop when x is "banana” and print the value of x:


THE CONTINUE STATEMENT

 With the continue statement we can stop the current iteration of


the loop, and continue with the next:

Example
Do not print banana: OUTPUT
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
THE RANGE() FUNCTION

 To loop through a set of code a specified number of times, we can use


the range() function,
 The range() function returns a sequence of numbers, starting from 0
by default, and increments by 1 (by default), and ends at a specified
number.
Example
Using the range() function: OUTPUT:
for x in range(6):
print(x)

Note that range(6) is not the values of


0 to 6, but the values 0 to 5.
THE RANGE() FUNCTION

 The range() function defaults to 0 as a starting value, however it


is possible to specify the starting value by adding a
parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):
Example OUTPUT:
 Using the start parameter:
for x in range(2, 6):
print(x)
THE RANGE() FUNCTION

 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 OUTPUT
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
ELSE IN FOR LOOP

 The else keyword in a for loop specifies a block of code to be


executed when the loop is finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has
ended:
for x in range(6): OUTPUT
print(x)
else:
print("Finally finished!")

Note: The else block will NOT be executed if the


loop is stopped by a break statement.
ELSE IN FOR LOOP

Example
 Break the loop when x is 3, and see what happens with the else
block:
for x in range(6): OUTPUT
if x == 3: break
print(x)
else:
print("Finally finished!")
#If the loop breaks, the else block is not executed.
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":
Example OUTPUT
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)
THE 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

# having an empty for loop like this, would raise an error without
the pass statement
UNDERSTANDING WHILE
LOOPS IN PYTHON
A basic guide to using while loops for iteration in Python
WHAT IS A WHILE LOOP?

 A 'while' loop repeatedly executes a block of code as long


as the condition is True.
 The syntax is:

 while condition:
 # Code to execute

 The loop stops when the condition becomes False.


BASIC EXAMPLE OF A WHILE LOOP

 # Example:
 counter = 1
 while counter <= 5:
 print(counter)
 counter += 1 # Increment the counter
 Output: 1 2 3 4 5
INFINITE LOOP

 A while loop can become infinite if the condition never becomes False.
 Example:

 while True:
 print("This will run forever unless stopped!")

 To avoid infinite loops, ensure that the condition will eventually become False.
BREAKING A WHILE LOOP

 You can break a while loop using the 'break' statement.

 # Example:
 counter = 1
 while True:
 if counter > 5:
 break
 print(counter)
 counter += 1

 # Output: 1 2 3 4 5
COMMON USE CASES OF WHILE LOOPS

 1. Counting or iterating through a series of numbers.


 2. Continuously prompting for user input until a valid input is received.
 3. Implementing game loops or repeating tasks until a condition is met.
SUMMARY

 - A 'while' loop runs as long as the condition is True.


 - It is important to make sure the loop will eventually stop.
 - Use 'break' to exit a while loop early.
 - Common use cases include counting, input validation, and game loops.
ASSIGNMENT

You might also like