For next loop

This type of loop checks for a condition and repeats the instructions inside the loop until the condition is met:

for <incremental variable> in final value:
statements

Here's an example of printing numbers from 1 to 10 in a for loop:

As we can see, we use a built-in range(starting value, max value) function, which specifies the loop to repeat from the starting value until the incremental value reaches the maximum value. In this case, the variable x is incremented by 1 and in each loop, the value is printed out. This is repeated until the value of x reaches 10, where the for loop terminates.

In a similar way, we can also iterate through the items in a given list:

PowerShell sample for the preceding Python code is as follows:

#PowerShell sample code:
$countries="India","UK","USA","France"
foreach ($country in $countries)
{
write-host ($country+" is good")
}

Here, we can see that the values are assigned to the countries variable as a list. The for loop now iterates through each item in the list, and the print statement adds the string value to another string value and prints the result. This loop is repeated until all the items in the list are printed.

There might be times when we do not want to parse through an entire for loop. To break from the loop while it is iterating, we use a break statement. Here's an example in which we want to stop printing after UK in the country list:

 for country in countries:
if 'UK' in country:
break
else:
print (country)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset