Python Control Flow
Python Control Flow
The order in which the program‘s codes are executed is called its control flow. Conditional statements, loops and function calls regulate the control flow of a python program.
Sequential statements
When statements are executed in a sequence one after another is when the term is used. They help in maintaining the order of the program. They always tend to work as per the main program.
Decision-making statements
As the name suggests they help to make a decision within the program as per the requirements of the user.
There are 3 statements included in the decision-making statements
IF Statements
When one condition is false and the justification is in the requirement for one condition IF Statement is applied. Only depending on whether the text expression is true, the statements are executed. Indentation indicates the body of the IF Statement in python.
Python often interprets non-zero values as True whereas None and 0 are interpreted as False.
Flowchart:
IF ELSE STATEMENTS:
When the test condition is true, the IF ELSE statement evaluates test expression and will execute and If the condition is False, the body of ELSE is executed. Indentation is used to separate the blocks.
Flowchart:
IF –ELIF -ELSE STATEMENTS:
Elif standing short for else gives a possibility to check multiple expressions. If the condition for if is False ,it moves ahead and check the next elif block. If all the conditions are False, body of else is executed. Only one block among the several if…elif…else blocks is executed according to the condition. The if block can have only one else block on the other hand can have multiple elif blocks.
Flowchart:
Control statements
Based on the values and logic Control statements are used to execute the program. python provides 3 types of Control statements
If loop statement
It is a condition-based looping statement used to repeat it for 1 time when the condition is met.
They can be further divided into 3 types
- simple if – if u have 1 condition
- if…else – if u have 2 conditions
- nested if – more than 2 conditions
if Statement syntax:
if(condition) statement;
if…else Statement syntax:
if(condition) statement; else statement;
nested…if Statement syntax:
if(condition) statement; elif(condition); statement; else statement;
while loop:
Repeatable looping statement used to repeat the instructions until cond. failed
Syntax:
while(condition) Statements;
Example :
wap to check given no is +ve r not if it +ve u need to repeat ur name for that many no of times
Assign:
i/p:5
o/p:6,7,8,9,10
Example Programs:
- palindrome or not
- universal Armstrong no or not
- 153=the sum of cubes of Indian number
- 1=number power 1
- 23=the sum of squares of the individual number
- 1535=the sum of power 4 of the individual number
Click Here-> Get Python Interview Questions and Answers