
#bootcamp
#python
Loops - Wonder what the heck is that? Magic of abstraction and logic.
In the last chapter, we have explained what lists are and how to print items from lists, but what when we want to print more items or all the items without needing to write a statement for every print? Here loops come into the game.
Python has FOR loops and WHILE loops, they can take a range, or conditions to determine how long should they run, and they can even run indefinitely.
For instance, we can write FOR loop in two ways.
#we can print all items in the list by creating something like an iterator that will
#progress thru the list and print every element in it
for i in [1,2,3,4]:
print(i)
#can do the same with strings
for c in "Hello":
print(i)
#and the second way is to use the built-in range method
for i in range(10):
print(i)
It is very simple and useful, for instance, if you want to update a list for a cars with hundred items.
#we can nest dictionaries in lists
cars = [
{"model": "BMW", "color": "blue"},
{"model": "Buggati", "color": "blue"},
{"model": "Buggati", "color": "orange"}
]
#we will change all colors to red for Buggati
for i in cars:
if i["model"] == "Buggati":
i["color"] = "red"
print(i["model"] + " --color-- " + i["color"])
We can even create lists with for loops, why don't you try that on your own?
WHILE loops are similar but they work with the more explicit condition like BOOLEAN. Often it will be in format until true or until false, until less or more than some value. Like this.
condition = 10
while condition > 0:
print("Hi, babe!")
#we use the -= decrement sign to decrement by one on every round
# += increments
condition-=1
#inifinte loop
while True:
print("Dogs are awesome!")
#break condition
green = True
#will run just once
while green:
print("Run")
green = False
There are more combinations on how we can use them but these are a good starting point, you can play with them for a while, combining them with previous conditional statements and data types, and nesting them in other loops. Next Chapter
[root@techtoapes]$ Author Luka
Login to comment.