Hello and Welcome to Blog #6, Python: Loops. This blog will introduce loop in Python, what they are used for, and how to use them.
Loops are used to repeat a set of code over and over until a certain requirement is met. There are two types of loops in Python, for loops, and while loops.
For loops:
For loops are used to execute a set of code for every element in an array, or every character in a string. For example, say we have variable, count, and its value is 0. We want to add 1 to count for every element in an array, cars. First, lets define count and cars:
count = 0
cars = ["Ferrari","Honda","Nissan"]
Now, we will use a for loop to run through the array cars, and increase count by 1 for every element:
for car in cars:
count += 1
The line, 'for car in cars' start the for loop. It basically means, for every car in the cars array. When you say, 'for car,' it creates a variable, car, and assigns its value to the first element in the array, cars. Then, it enter the loop, and looks at the line, count += 1. This line adds 1 to the value of count. After this it will go back to the 'for car in cars' line, and set the value of the 'car' variable to the next element of the array. Then, it will once again enter the loop, and go to the 'count += 1' line, and so on and so forth, until either it goes through all the elements, or the break command is used. When the break command is used, the loop will be quit. To use the break function, you must simply type, 'break' on its own line. Make sure to use the break command only after the loop has executed whatever you want it to. Any code that is in the loop, but comes after the break command is unreachable, because the loop will quit before reaching that code.
While loops:
While loops are used to execute a set of code, while a certain statement is valid. Once again, say we have a variable, count, which has a value of 0. We want to increase count by 1, while it is lesser than or equal to 5.
count = 0
Now we will use a while loop to increase count by 1 while it is lesser than or equal to 5.
while count <= 5:
count += 1
The line, "while count <= 5:" starts the while loop, or defines it. It just means, while the value of count is lesser than or equal to 5. The colon at the end of the line is python syntax. The next line, count += 1, adds one to the value of count. It is indented 4 spaces, as per python syntax. Basically, the program arrives at the first line and enters the loop. Count is increased by 1. It then goes back to the first line and verifies the condition to make sure it is still valid. It will continue like this until the condition becomes false, or, once again, the break command is used.
This concludes Python: Loops. Thank you for reading. Please leave any comments and questions in the comments section below!
Comments
Post a Comment