You are currently viewing Control Flow in Python
Control flow in Python

Control Flow in Python

Control flow refers to the sequence in which a program’s code is executed. Conditions, loops, and function calls all play a role in how a Python program is controlled. Control flow, also known as the flow of control, refers to the sequence in which a program’s function calls, instructions, and statements are carried out or assessed while it is operating. Control flow statements, which are present in many programming languages, specify which part of the code is executed in a program at any given time. An if/else statement is an illustration of a control flow statement.

A control flow in Python is a sequence in which a computer executes statements in a script. Unless the computer comes across the (widespread) structures that affect the control flow, such as conditionals and loops, code is executed from the first line in the file to the last line.

Python offers two kinds of control structures:

  • Sequential-Serial is the default setting.
  • Repetition-Looping, or repeatedly repeating a section of code, uses repetition.

According to the structure theorem, any computer program may be made by combining the basic control structures. A control structure, also referred to as a flow of control, is a computer construct that evaluates variables and chooses an action based on predetermined criteria. Simply described, a control structure is nothing more than a decision the computer makes. As a result, the fundamental decision-making process and control flow of a computer program determine how it reacts to situations and parameters.

Sequential

When statements are carried out sequentially, they are done so in a particular order. There is nothing further you need to do for this to occur. A group of statements that are executed in succession is referred to as a “sequential statement.” Sequential statements have the drawback of causing the execution of the source code to crash if any of the lines’ reasoning breaks.

The program can decide which statement should be performed next thanks to decision-making statements. When we want one set of instructions to be followed in one context and another set of instructions to be followed in another, we employ decision-making statements. Python may be used to implement decision-making by using,

  1. if statements
  2. if-else statements
  3. if-elif-else statements
  4. nested if statements

if statement

If statements are control flow statements that assist us in running specific code but only in the event that a specific condition is satisfied. In a basic if, there is only one condition to test. Branching is a decision-making process that involves selecting between two or more alternative paths.

Syntax of If statement

if condition:
     statement 1
     statement 2
      â€”——-—-—-
      statement n

Python starts and ends a decision-making statement’s body with an indentation.

If the condition is met in this case, the if condition will be entered, and the statements will begin to be executed until they reach the end of the indent. Following the end of the indent, more statements will be executed. “True” here denotes a non-zero value, while “false” or “none” denotes a zero.

# Write a program to implement if statement
temperature =”sunny”

if temperature==”sunny”:
  print(“The day is hot”)

Output
The day is hot

if-else statement

If the test condition is True, the body of the if statement will be executed. If the test condition is False, the body of the else statement will be executed.

If we pay attention to the if statement above, it will only assess the true assertion. However, we may assess the fraudulent claims using if-else statements. The syntax for if-else statements is shown below.

Syntax of if-else statement

if condition:
    statement
else 
    statement

# Write a program to check if a number is even or odd

n= int(input(“Enter the number “))

if n%2==0:
     print(“The number is even”)
else:
     print(“The number is odd”)

Output
Enter the number 23
The number is odd

if-elif -else statements

The if-elif-else statement is used to execute a statement or a block of statements only if certain conditions are met.

We’ll utilize “if elif else” control statements to assess one statement from a group of statements.

Syntax of if-elif-else statement

if condition:
    statement
elif condition:
   statement
else:
    statement

# Write a program to implement the if-elif-else condition

watson= 43
ram =34
arnold= 64

if watson>ram:
    print(“the age of Watson is greater than ram”)
    
elif watson<arnold:
    print(“the age of Watson is greater than arnold”)

else:
    print(“the age of ram is greater than Watson”)

Output
the age of Watson is greater than ram

Nested if else

An if statement enclosed within another if statement is known as a “nested” if statement.

Syntax of Nested if else

if condition:
   if condition:
           statement
   else:
           statement
else:
    statement
# Write a program to implement nested if else

watson= 43
ram =34
arnold= 64

if watson>ram:
    if watson<arnold:
        print(“the age of watson is less than than arnold”)    
    else:
        print(“dont; plant”)
        
else:
    print(“nothing”)

Output
the age of watson is less than than arnold

Repetition

To repeat a set of programming instructions, use a repetition statement. There are typically two loops, or repetitive statements, in Python:

  • For loop: Iterating through a sequence that is either a list, tuple, dictionary, or set is made using a loop. A collection of statements can be run once for each element in a list, tuple, or dictionary.
  • While loop: While loops are used in Python to repeatedly run a block of statements until a specified condition is met. The expression is then verified once more, and if it is still true, the body is run once more. This keeps happening until the expression loses its meaning.

In computer programming, these control structures can be mixed. A sequence may contain several loops, nested loops, or sequences with loops and additional conditionals on each of the two branches of a conditional. You can learn about Python’s control structures and statements from the lessons that follow.

While loop

In Python, the while statement allows for the repeated execution of a single statement or a group of related statements that are subject to a conditional expression. The syntax for the while clause is as follows:

while expression: 
        statement(s)

A while statement can also contain an else clause, break, or continue statement. A typical while statement looks like this:

i=1
while (i<5):
   print(i)
   i+=1

Output
1
2
3
4

For loop

In Python, the for statement allows for the repeated execution of a single statement or a set of related statements that are subject to an iterable expression. The syntax for the statement is given below:

Syntax of for loop

for i in iterables:
    statement

In this case, “in” is a keyword that is part of the syntax of the “for” statement but has no functional connection to the in-operator used for membership testing, which should be noted. As we’ll discuss in a moment, a for statement can also contain an else clause, break, and continue statements.

Here is an example of for statement:

m=”boy”
for i in m: 
     print(i)

Output
b
o
y

Expression, sometimes referred to as the loop condition, is first assessed. The whole clause comes to an end if the condition is false. The statement or statements that make up the loop body are performed if the loop condition is met. The loop condition is once again assessed after the loop body has finished running to determine whether another iteration is necessary. When the loop condition is no longer true, the procedure is repeated, and the while statement is then terminated.

Unless an exception is raised or the loop body performs a break statement, the loop body should contain code that finally causes the loop condition to be false. If a return statement is executed within the body of a loop that is part of a function, the function as a whole also stops.

The range Statement

A sequence of numbers within predetermined constraints can be created using the range() method. It takes three parameters starting_point, ending point, and the step size. The starting point parameter value is set to 0 by default.

Syntax of range

range(starting_point, ending_point-1, step size)

for i in range(0,5):
       print(i)

Output
0
1
2
3
4

for i in range(0,21,5):
       print(i)

Output
0
5
10
15
20

The Break Statement

Only inside a loop body is the break statement permitted. The loop ends when the break is called. Break only ends the innermost nested loop when a loop is nested inside of additional loops. In actual practice, a break statement is typically placed inside of an if clause in the body of the loop so that it runs conditionally.

The implementation of a loop that selects whether to continue looping only in the middle of each loop iteration is one frequent application of break:

# Write a program that takes n input from the user if the n is odd then break the loop and print the remaining ones.

n= int(input(“Enter n number “))
for i in range(0,n):
  number= int(input(“Enter your number: “))
  if number %2==0:
    print(number)
  else:
    break

Output
Enter n number 5
Enter your number: 4
4
Enter your number: 2
2
Enter your number: 1

The Continue Statement

Only within the body of a loop is the continue statement permitted. The current iteration of the loop body ends when the continue command is used, and the next iteration of the loop is then executed. For the loop body to execute conditionally, a continue statement is typically placed inside some clause of an if statement.

Deeply nested if statements within a loop can be replaced with the continue statement. For instance:

# Wap which takes n input from the user and if the user input is divisible by 5 then skip that number and print the remaining ones

n= int(input(“Enter n number “))

for i in range(0,n):
    number=int(input(“Enter the number “))
    if number % 5==0:
        continue
    else:
        print(number)


Output
Enter n number 5
Enter the number 5
Enter the number 10
Enter the number 11
11
Enter the number 12
12
Enter the number 13
13

The Pass Statement

A Python compound statement must have at least one statement in its body; it cannot be empty. When a statement is syntactically necessary but you don’t have anything specific to accomplish, you can use the pass statement as a stand-in because it has no effect. Here is an illustration of using pass in a conditional statement to test mutually exclusive conditions as part of relatively complex logic:

# write a program

i=5
while(i>5):
pass

Conclusion

Consequently, we learned about Python flow control in this post. We explored how to regulate the flow of the code by making decisions about which statements should be performed and which ones can be skipped. To accomplish this, we have learned about many forms of conditional statements, such as the if, if-else, and if-else-else conditions. We also spoke about while and for loops and their applications.