#11 Loops

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

Next post: https://codinghelp.site/knowledgebase/python/12-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 on it.

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

Iterable 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 a for loop:

The sequence is representing an iterable object, whilst the 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

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.