By introducing loops into scripts it is possible to repeat a block of code multiple times without having to write the same code over and over again. This makes your code more concise, more readable, and more maintainable.
There are two main types of loops in Python: for loops and while loops.
For Loops
Are used to iterate over a sequence of values, such as a list or a string.
While Loops
Are used to repeat a block of code as long as a certain condition is true.
By being able to repeat code blocks it is possible to automate repetitive tasks and perform operations on large amounts of data. For example, you might use a loop to process a large dataset, or to automate a series of calculations that would be tedious to do by hand.
4th Python Script
The fourth python script created is:
These loops have varying complexity to achieve different outputs. It is important to note the use of indentation when working within a loop. Not only does this make the code easier to read, but python will not be able to execute a loop if it has not been correctly indented.
for Loop 1
Loop 1 creates a variable called x, assigns it the value of each different character in the string provided (NorthGreen) and outputs the value of x to the terminal
for Loop 2
Loop 2 achieves the same as Loop 1 but is working with an array. This is a defined list of values. As such the value of x is no longer the individual characters within the “NorthGreen” string, it is instead the value of each object in the array
for Loop 3
Loop 3 introduces an else statement. An else statement can be used in an if loop to specify an action to take in the event of the if statement being false or the loop completing. This loop will print each day of the week, and when it has completed the else statement will be executed
for Loop 4
Loop 4 demonstrates the ability to have a nested loop. Nested loops are loops that run within a loop. In this example it is possible to see that the first loop “for x in days:” is used to execute the secondary loop “for y in meals:”
Indentation is again important for this kind of code section as it is important for python to understand which code segment belongs to which loop.
While Loop 1
While loops are used to execute a command for as long as a condition is true. In the first while loop,
The value of “i” is printed to the terminal and increased by 1 for as long as the value is less than or equal to 5. This condition is created at the beginning of the loop by using the command:
While Loop 2
While Loop 2 expands on this loop and adds an else statement that is used to execute a command when the conditions of the while loop are no longer valid. This means that when “i” is incremented to the value of 7 the following is no longer true
as such the else statement is now executed