#​11 Python Loops

Previous post: https://codinghelp.site/wiki/python/10-python-basics-quiz/

Next post: https://codinghelp.site/wiki/python/%e2%80%8b12-python-error-handling//

The for loop & while loop

A for loop is used to iterate over an iterable sequence. Iteration means to take each item out of a sequence and perform an action to it.

A while loop is going to be ran as long as the provided condition is met.

Iteritable sequences in python are:

  • list
  • tuple
  • dictionary
  • set
  • string

There are 2 loops in python, for and while loop.

Loops Syntax

For Loop

This is how we would write an for loop.

Sequence is representing an iterable object, whilst item is representing the current item in the sequence that’s being looped through.

While loop

A while loop is going to be run as long as the condition is met. 

To stop a loop, we can use the break statement.

Nested loops are loops inside loops.

Examples

Example of a for loop 

Here, we are looping through the key list and printing each item in the list. Output of this code would be foo bar.

Example of a while loop

In this while loop, we are printing the variable m until its value is 5.

Example of a for loop with a break statement

In this example we are iterating over all items in abc list and if the current item is 1 we stop the loop. if not we print it. Output of this code would be 0.

Exercise

Make a string named abc and set its value to Hello World. Iterate over it with a for loop, if the current item is the letter W break the loop, else print the letter.

Answer Key

image