Tuesday, 22 May 2018

InfoTech Seniors May 22, 2018 Python Loops

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple or a string).
This is less like the for keyword in other programming language, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)


The for loop does not require an indexing variable to set beforehand, as the for command itself allows for this. 

The break Statement

With the break statement we can stop the loop before it has looped through all the items:

Example

Exit the loop when i is 3:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    break
  print(x)

The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue wit the next:

Example

Do not print banana:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)


No comments:

Post a Comment