Without a loop, a script needs one line for each port:
print(f"interface {ports[0]}") print(f"interface {ports[1]}") print(f"interface {ports[2]}")A for loop runs the same lines for each item of a list:
![The script ports = ["Gi0/1", "Gi0/2", "Gi0/3"], for port in ports, print(f"interface {port}") prints interface Gi0/1, interface Gi0/2 and interface Gi0/3.](https://dphfzu3i54bzu.cloudfront.net/media/10269/python-for-loop.png)
Figure 1 - The for Loop Runs Once per Item
The
forline ends with:and the lines under it start with four spaces, like withif.In the lab, use a loop on the list
vlansto printvlan 10,vlan 20andvlan 30.
Click Run to get the flag.Answer the question below
Enter the flag you obtained.
The variable after
foris the loop variable.
At each round, it holds the next item of the list:
Figure 2 - The Loop Variable Changes at Each Round
A variable that you create before the loop keeps its value from one round to the next.
You can use it to count the rounds:count = 0 for port in ports: count = count + 1 print(count) # Output: 3In the lab, count the devices that the loop handles.
Print the total after the loop to get the flag.Answer the question below
Enter the flag you obtained.
You can put an
ifinside a loop to treat some items in another way.continueskips the rest of the round and goes to the next item:
Figure 3 - continue Skips One Round
In the lab, the script shuts down every port, even the uplinks.
Make it skip the ports of the listuplinksto get the flag.Answer the question below
Enter the flag you obtained.
To get a series of numbers without typing them, you use
range().
You give it the first number and the number where it stops:
Figure 4 - range() Stops Before the Second Number
In a
forloop, you userange()in place of a list:for number in range(1, 4): print(f"interface Gi0/{number}") # Output: interface Gi0/1 # interface Gi0/2 # interface Gi0/3In the lab, print the commands
interface Gi0/1tointerface Gi0/24with a loop to get the flag.Answer the question below
Enter the flag you obtained.
To repeat lines without a list, you use a while loop.
It repeats its lines as long as a test is True:
Figure 5 - The Test of a while Loop
Without the line
tries = tries + 1, the test stays True and the loop never stops.In the lab, the script tries SW1 5 times.
Make it stop after 3 tries, then printSW1 does not answerafter the loop to get the flag.Answer the question below
Enter the flag you obtained.