0% found this document useful (0 votes)
3 views18 pages

Python Beginners Course Part 4

This document provides an overview of control flow in Python, focusing on If-Else statements, nested conditions, and loops. It explains the syntax and usage of if statements, if-else statements, and nested if statements, along with examples for clarity. Additionally, it covers the for and while loops, including their syntax, infinite loops, and the use of break and continue statements to control loop execution.

Uploaded by

Lohith Cyrus
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)
3 views18 pages

Python Beginners Course Part 4

This document provides an overview of control flow in Python, focusing on If-Else statements, nested conditions, and loops. It explains the syntax and usage of if statements, if-else statements, and nested if statements, along with examples for clarity. Additionally, it covers the for and while loops, including their syntax, infinite loops, and the use of break and continue statements to control loop execution.

Uploaded by

Lohith Cyrus
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

UNIT 2

If-Else statements
There are situations in real life when we need to make some decisions and based on these decisions, we
decide what we should do next.
Similar situations arise in programming also where we need to make some decisions and based on these
decisions we will execute the next block of code.

Conditional statements in Python languages decide the direction(Control Flow) of the flow of program
execution.
If-Else statements in Python are part of conditional statements, which decide the control of code. As you
can notice from the name If-Else, you can notice the code has two ways of directions.
Types of Control Flow in Python
Python control flow statements are as follows:
The if statement
The if-else statement
The nested-if statement
The if-elif-else ladder

Python if statement
The if statement is the most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not.

Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts boolean values –
if the value is true then it will execute the block of statements below it otherwise not.
Python uses indentation to identify a block. So the block under an if statement will be identified as shown
in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block will consider only statement1 to be inside its block.

Flowchart of Python if statement


Example of Python if Statement
As the condition present in the if statement is false. So, the block below the if statement is executed.

Example:
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Python If-Else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But if we want to do something else if the condition is false, we can use the
else statement with the if statement to execute a block of code when the if condition is false.

Syntax of Python If-Else:

if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Flowchart of Python if-else statement


look at the flow of code in an if-else statement
Example:
# python program to illustrate If else statement
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block

Example : Checking if a number is even or odd.

num = 4
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")

Example : Checking if a string contains a certain character

string = "hello, world"


char = "w"

if char in string:
print("The string contains the character", char)
else:
print("The string does not contain the character", char)

Outcome:
The string contains the character w

Example : Checking if a year is a leap year

year = 2000
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
else:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")

Output:

2000 is a leap year.

In this example, we use nested if statements to check if a year is a leap year. A year is a leap year if it
is divisible by 4, except for years that are divisible by 100 but not divisible by 400.
The outer if statement checks if year is divisible by 4. If it is, the inner if statement checks if it is also
divisible by 100. If it is, the innermost if statement checks if it is divisible by 400. If it is, the code
block indented below that statement will be executed, printing the message "is a leap year."
If it is not, the code block indented below the else statement inside the inner if statement will be
executed, printing the message "is not a leap year.".
If the year is not divisible by 4, the code block indented below the else statement of the
outer if statement will be executed, printing the message "is not a leap year."

Nested-if Statement & if-elif-else ladder


You can have if statements inside if statements, this is called nested if statements.
We can have an 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.
Syntax
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
The syntax of the nested if...elif...else construct will be like this
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)3
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example: #Python program to demonstrate nested if statement

num = 15
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output:
Positive number
Flow Chart of nested if else statement:

# Python program to show how to use elif condition

a, b = 9, 9

# Initializing the if-else condition


if a < b:
code = "a is less than b"
elif a == b:
code = "a is equal to b"
else:
code = "a is greater than b"

print(code)

Output: a is equal to b
Example:
# Python program to demonstrate nested if statement
i = 13
if (i == 13):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 12 and smaller than 15")

Output:

i is smaller than 15
i is greater than 12 and smaller than 15

Example:
# Python program to show the nested if-else conditions
A = 100
B = 200
C = 300
# Initializing the if-else conditions
if B > A:
if B > C:
print("B is the largest number")
else:
if A > B:
if A > C:
print("A is the largest number")
elif C > A:
if C > B:
print("C is the largest number")
else:
print("All numbers are equal")
if B % C == 0:
if A % C == 0:
print("C is a common factor of A and B")

Output:
C is the largest number
Loops in Python – For, While and Nested Loops
Python programming language provides two types of loops – For loop and While loop to handle looping
requirements. Python provides three ways for executing the loops.
While all the ways provide similar basic functionality, they differ in their syntax and condition-checking
time.
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python,
there is “for in” loop which is similar to foreach loop in other languages.
For Loop Syntax:

for iterator_var in sequence:


statements(s)
Example 1:
n=4
for i in range(0, n):
print(i)
Output:

0
1
2
3

Example 2:
list = ["MDC", "for", "Python"]
for index in range(len(list)):
print(list[index])

Flowchart of Python for Loop


Nested for loops
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}")

Output

i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
Infinite loop in Python
An infinite loop in Python is a continuous repetition of the conditional loop until some external factors like
insufficient CPU memory, error in the code, etc. occur.

There are various types of infinite loops in Python such as:

while statement.
if statement.
break statement.
continue statement.

An infinite loop does not have an explicit end (no loop termination condition is specified by the
programmer).
Example:
while True:
print("Scaler Topics")

Output
Scaler Topics
Scaler Topics
Scaler Topics
Scaler Topics
Scaler Topics
When are Infinite Loops Necessary?
In Python, an infinite loop can be useful in various scenarios. One of the prime use of an infinite loop can
be seen in a client-server architecture model in [Link] we know a server is central storage that is
always awake and ready to handle client requests. So, a server runs in an infinite loop which makes it
always awake and ready to handle various situations like new requests from the client, new connections
from the client, etc.
Another example of an infinite loop in Python can be visualized in game development. For example, an
infinite while loop is used for the main game frame which continues to get executed until the user or the
game selects some other event. Since the game developer does not know the exact iterations or the time at
which the user will do something, the game developer uses the infinite loop in Python.
While Loop in Python
In Python, a while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. When the condition becomes false, the line immediately after the loop in the 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:
count = 0
while (count < 3):
count = count + 1
print("Hello MDC")
The given Python code uses a ‘while' loop to print “Hello MDC” three times by incrementing a variable
called ‘count' from 1 to 3.

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

Working of Python break Statement


The break statement terminates the loop immediately when it's encountered.
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)

Output:
0
1
2
In the above example,if i == 3:
break
terminates the loop when i is equal to 3. Hence, the output doesn't include values after 2.

break Statement with while Loop

We can also terminate the while loop using the break statement. For example,
i=0
while I < 5:
if I == 3:
break
print(i)
i += 1

In the above example,if i == 3:


break
terminates the loop when i is equal to 3.

Working of continue Statement in Python:

• continue skips the current iteration and proceeds to the next one

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)
Output:

In the above example, if i == 3:


continue
skips the current iteration when i is equal to 3, and continues the next iteration. Hence, the output has
all the values except 3.

continue Statement with while Loop


We can skip the current iteration of the while loop using the continue statement. For example,
num = 0
while num < 10:
num += 1
if (num % 2) == 0:
continue
print(num)

Output

1
3
5
7
9

In the above example, we have used the while loop to print the odd numbers between 1 and 10. Here,if
(num % 2) == 0:
continue
skips the current iteration when the number is even and starts the next iteration.

You might also like