Search⌘ K
AI Features

Loops

Explore how to implement loops in Python, including for loops, while loops, and nested loops, with parallels to MATLAB. Understand Python's indentation rules, efficient loop syntax, and practical examples of looping structures. This lesson equips you with essential control flow skills for transitioning from MATLAB to Python.

Loops are used to execute a block of code repeatedly. Let’s have a look at the execution of loops in MATLAB and Python.

Loops in MATLAB and Python
Loops in MATLAB and Python

The for loop

A for loop allows us to repeat a block of code a fixed number of times.

The basic syntax for a for loop in MATLAB is as follows:

Python 3.10.4
for i = 1:3:10 % A sequence from 1 to 10 with a step of 3
disp(i)
end
  • Line 1: We use a for loop with the iteration variable i to iterate over the array [1,4,7,10].

  • Line 2: We use the disp() command to print the iteration variable i.

Python uses the for keyword, followed by the loop variable, in keyword, and the range() function, which accepts the starting value and end value plus one. We can also tell the range() function about the step size using a third argument.

The basic syntax for a for loop in Python is as follows:

Python 3.10.4
for i in range(1, 11, 3): # A sequence from 1 to 10 with a step of 3
print(i)
  • Line 1: We use a for loop with the iteration variable i to iterate over the array [1,4,7,10]. Note that in the range() function, the step size of 3 is given as the third argument. In MATLAB, the step size is given in the middle of range values.

  • Line 2: We use the print() command to print the iteration variable i. ...