Holla Tech - Learn

Loops
 

Sometimes, you need to perform code on each item in a list. This is called iteration, and it can be accomplished with a while loop and a counter variable.
For example: 

words = [“hello”, “world”, “spam”, “eggs”]
counter = 0
max_index = len(words) 1

while counter <= max_index:
   word = words[counter]
   print(word + “!”)
   counter = counter +

 

Result: 

>>
hello!
world!
spam!
eggs!
>>> 

 

NOTE!
The example above iterates through all items in the list, accesses them using their indices, and prints them with exclamation marks.

for Loop
 

Iterating through a list using a while loop requires quite a lot of code, so Python provides the for loop as a shortcut that accomplishes the same thing.
The same code from the previous example can be written with a for loop, as follows:

words = [“hello”, “world”, “spam”, “eggs”]
for word in words:
  print(word + “!”

 

Result:

>>
hello!
world!
spam!
eggs!
>>> 

 

NOTE!
The for loop in Python is like the foreach loop in other languages.

for Loops
 

The for loop is commonly used to repeat some code a certain number of times. This is done by combining for loops with range objects.

for i in range(5):
  print(“hello!”

 

Result: 

>>
hello!
hello!
hello!
hello!
hello!
>>> 

 

NOTE!
You don’t need to call list on the range object when it is used in a for loop, because it isn’t being indexed, so a list isn’t required.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE PYTHON MAIN COURSE PAGE. 

PYTHON MAIN COURSE PAGE

 


©️ License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT