Python Flow Control: If-else and Loop with practical examples
- if…else Statement In Python
- for Loop In Python
- while Loop In Python
- break and continue In Python
- pass Statement In python
¶if…else Statement In Python
In the computer programming, the if
statement is a contingent statement. It is used to conduct a block of code only when a appointed condition is met. For example
If we need to assign several grades to students based on their scores.
- If a student scores upon 90, assign grade A
- If a student scores upon 75, assign grade B
- If a student scores upon 65, assign grade C
This conditional tasks can be achieved using the if
statement
¶if Statement In Python
An if
statement conduct, a block of code only if the mark condition is met.
if condition:
# body of if statement
Now, if the condition of the if
statement below:
-
True - the body of the
if
statement conduct. -
False - the body of the
if
statement is skipped from conduction.
Now see an example-
¶Example: if Statement In Python
number = 10
# check if number is greater than 0
if number > 0:
print('Number is positive')
Sample Output:
Number is positive
This statement always executes
In the upon example, we have maked a variable named number
. advertising the test condition
,
number > 0
if the number
is greater than 0, then the condition evaluates True
. Hence, the body of the if statement executes.
Sample Output 2
Let’s alternative the value of the number
to a negative integer, say -5.
number = -5
Then, when we run the program, the output will be below-
This statement always executes
This is from the value of the number
is less than 0. Here, the condition evaluates to False
. Also, the body of the if
statement is scamper.
¶if…else Statement In Python
An if
statement can have an elective else
clause. The else
statement conduct if the condition in the if
statement evaluates to False
.
if condition:
# body of if statement
else:
# body of else statement
Below, if the condition
under the if
statement evaluates to
-
True - the body of
if
conducts, and the body ofelse
is scamper. -
False - the body of
else
conducts, and the body ofif
is scamper
Now see an example-
¶Example: if…else Statement In Python
number = 10
if number > 0:
print('Positive number')
else:
print('Negative number')
print('This statement always executes')
Sample Output :
Positive number
This statement always executes
In the upon example, we have maked a variable named number
. Look that the test condition
,
Now the value of the number
is 10, then condition
evaluates to True
. Here, code under the body of if
is evolved.
¶if…elif…else Statement In Python
In if...else
statement is used to conduct a block of code among two substitutes.
Only, if we need to make a option between more than two alternatives, we conduct the if...elif...else
statement.
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Below,
-
if condition1
- This checks ifcondition1
isTrue
. Suppose it is, then program conducts code block 1. -
elif condition2
- Ifcondition1
is notTrue
, then program checkscondition2
. Ifcondition2
isTrue
, it executes code block 2. -
else
- If neithercondition1
norcondition2
isTrue
, the program incapacity to executing code block 3
Now see an example-
¶Example: if…elif…else Statement In Python
number = 0
if number > 0:
print('Positive number')
elif number <0:
print('Negative number')
else:
print('Zero')
print('This statement is always executed')
Output :
Zero
This statement is always executed
In the upon example, we have maked a variable named number
.
While the value of the number
is 0, both the test situations evaluate to False
.
Here, the statement under the body of else
is evolved.
¶if Statements Nested In Python
It is probable to include an if
statement under 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')
Output :
Number is positive
¶for Loop In Python
In system programming, loops are used to repeat a block of code.
languages = ['Swift', 'Python', 'Go']
# access items of a list using for loop
for i in languages:
print(i)
**Output : **
Swift
Python
Go
In the upon example, we have maked a list called languages
. So the list has 3 elements, the loop iterates 3 times.
The value of i
is below
-
Swift
is of the first iteration. -
Python
is of the second iteration. -
Go
is of the third iteration.
for val in sequence:
# statement(s)
Now , val
accesses every item of the sequence
on every iteration. The loop continues still we reach the last item in the order.
¶Flowchart of Python for Loop In Python program
¶Example: Loop Through a String In python
language = 'Python'
# iterate over each character in language
for x in language:
print(x)
Output :
P
y
t
h
o
n
¶for Loop with Python range() In Python
In Python Program, the range() function returns a order of numbers. For example-
values = range(4)
Above, range(4)
returns a order of 0, 1, 2 ,and 3.
You can use range()
with a for loop to iterate a particular number of times. For example-
# iterate from i = 0 to i = 3
for i in range(4):
print(i)
Output :
0
1
2
3
You used the for loop to iterate over a range from 0 to 3.
¶while Loop In Python
In Python Program, we use the while
loop to revolving a block of code until a certain agreement is met. For example-
number = 1
while number <= 3:
print(number)
number = number + 1
Output :
1
2
3
In the upon example, you have used a while
loop to print the numbers from 1 to 3. The loop runs as long as the agreement number <= 3
is satisfied.
while condition:
# body of while loop
Below,
- The
while
loop evaluates the agreement. - If the agreement is true, body of while loop is evolved. The agreement is evaluated again.
- This process continues until the agreement is
False
. - Once the agreement evaluates to
False
, the loop terminates
¶Flowchart of while Loop In Python
¶Example: while Loop In Python
# calculate the sum of five numbers entered by user
sum = 0
count = 0
while count < 5:
input_value = int(input('Enter a number: '))
sum += input_value
count += 1
print('The sum is:', sum)
Output :
Enter a number: 3
Enter a number: 2
Enter a number: 1
Enter a number: 4
Enter a number: 6
The sum is: 16
There is how the above program works in every iteration of the loop below:
¶Example: while Loop to Display Game Level In python
# variables to store game information
current_level = 1
final_level = 4
game_completed = True
# iterate until the final level is reached
while current_level <= final_level:
if game_completed:
print(f'Welcome to Level {current_level}')
current_level += 1
print('Game Over!')
Output :
Welcome to Level 1
Welcome to Level 2
Welcome to Level 3
Welcome to Level 4
Game Over!
In the upon example, we have used a while
loop to check the present level of the player and display it.
¶Infinite while Loop
If the agreement of a while
loop is all-time True
, the loop runs for infinite times, forming an infinite while loop. For example below-
age = 32
# the test condition is always True
while age > 18:
print('You can vote')
Output :
You can vote
You can vote
You can vote
.
.
.
¶break and continue In Python
In the programming, the break
and continue
statements are used to innovate the flow of loops:
-
break
passage the loop entirely -
continue
skips the present iteration and revenue to the next one
break Statement In Python
In the break
statement terminates the loop instantly when it’s encountered.
break
¶Working break Statement In Python
¶Example: break Statement with for Loop In Python
You can use the break
statement with the for
loop to terminate the loop when a certain agreement is met. For example-
for i in range(5):
if i == 3:
break
print(i)
Output :
0
1
2
In the upon example,
if i == 3:
break
terminates the loop when i
is equal to 3. here, the output doesn’t add values after 2.
¶continue Statement In Python
The continue
announcement skips the current iteration of the loop and the control flow of the program goes to the after iteration.
continue
¶Working of continue Statement in Python Program
¶Example: continue Statement with for Loop In Python
You can use the continue
statement with the for
loop to skip the present iteration of the loop and jump to the after iteration. For example-
for i in range(5):
if i == 3:
continue
print(i)
Output : In python
In Python programming, the pass statement is a null statement which can be used as a placeholder for future code.
0
1
2
4
in the upon example-
if i == 3:
continue
skips the present iteration when i
is equal to 3, and run the next iteration. Here, the output has all the values without 3.
¶pass Statement In python
In Python programming, the pass
statement is a null statement what can be used as a placeholder for in future code.
If we have a loop or a function which is not perfect yet, but you want to perfect it in the future. In like cases, we can use the pass
statement.
So the syntax of the pass statement is:
pass
¶Using pass With Conditional Statement In python
n = 10
# use pass inside if statement
if n > 10:
pass
print('Hello')
There, notice that you have used the pass
statement under the if statement .
Still, nothing happens when the pass is accomplished. Now It results in no operation (NOP).
If we didn’t use pass or just put a comment as like below-
n = 10
if n > 10:
# write code later
print('Hello')
Below, we will show an error message: IndentationError: expected an indented block
¶Use of pass Statement inside Function or Class In python
We can do the equivalent thing in an empty function or class as well. For example-
def function(args):
pass
class Example:
pass
Python File Handling Essential Tips and Tricks for Mastery
All Tutorials in this playlist
Popular Tutorials
Categories
-
Artificial Intelligence (AI)
11
-
Bash Scripting
1
-
Bootstrap CSS
0
-
C Programming
14
-
C#
0
-
ChatGPT
1
-
Code Editor
2
-
Computer Engineering
3
-
CSS
28
-
Data Structure and Algorithm
18
-
Design Pattern in PHP
2
-
Design Patterns - Clean Code
1
-
E-Book
1
-
Git Commands
1
-
HTML
19
-
Interview Prepration
2
-
Java Programming
0
-
JavaScript
12
-
Laravel PHP Framework
37
-
Mysql
1
-
Node JS
1
-
Online Business
0
-
PHP
28
-
Programming
8
-
Python
12
-
React Js
19
-
React Native
1
-
Redux
2
-
Rust Programming
15
-
SEO - Search Engine Optimization
1
-
Tailwind CSS
1
-
Typescript
10
-
Uncategorized
0
-
Vue JS
1
-
Windows Operating system
1
-
Woocommerce
1
-
WordPress Development
2
Tags
- Artificial Intelligence (AI)
- Bash Scripting
- Business
- C
- C Programming
- C-sharp programming
- C++
- Code Editor
- Computer Engineering
- CSS
- Data Structure and Algorithm
- Database
- Design pattern
- Express JS
- git
- Git Commands
- github
- HTML
- Java
- JavaScript
- Laravel
- Mathematics
- MongoDB
- Mysql
- Node JS
- PHP
- Programming
- Python
- React Js
- Redux
- Rust Programming Language
- SEO
- TypeScript
- Vue JS
- Windows terminal
- Woocommerce
- WordPress
- WordPress Plugin Development