Loops in python

Have you ever felt like you are doing certain tasks again and again in life? Well, I’m no expert in helping with your life! Although, if you would ever face the same situation in a programming language I can help you with that.

In programming, we can repeat certain tasks using loops. Let’s go through them one by one.

for loop

  • for loop in python repeats over each item of a given sequence (a list or a string), in the order that they appear in the sequence.

Example: Alt Text

Output:

I want to watch a movie directed by James Cameron
I want to watch a movie directed by Christopher Nolan
I want to watch a movie directed by Steven Spielberg
  • But, let’s say you are a programmer who needs to iterate over a sequence of numbers, given the limit you want. Well, then you can make use of the built-in function range() which generates arithmetic progressions: Alt Text

Output:

0
1
2
3
4

while loop

  • while loop in python repeats any given set of code until the give condition returns true.

Example: Alt Text

Output:

0
1
1
2
3
5
8

Code along and have fun.

Aswin Barath

Aswin Barath

My name is Aswin Barath. I’m a technical blogger and budding software engineer