An Introduction to Python For Undergraduate Engineers/For Loops< An Introduction to Python For Undergraduate Engineers
For loops give you a way to repeatedly do something. This can be either a set number of times, or to repeat a part of your program several times, but each time with a different value of a variable each time.
for i in [1,2,3,4,5]: print(i)
This will continually loop around, printing the value of i each time. This is a good time to quickly introduce you to two things, list and the range() command. As you have seen in the example, we can produce a list by using square brackets containing the values of our list, each one separated by a comma. For example, we can produce a variable and assign a list of values to it as follows:
countlist = [1,2,3,4,5,6,7,8,9,10]
This variable is now of type 'list' and contains multiple entries. We can save ourselves the effort of writing out a long list just to count simply by using the range(startvalue,endvalue) command;
countlist = range(1,11)
Note that the end value is 10, and not 11 as you might expect. This is because the range() does not include the end value. We can use this in our 'for' loop, as a quick way to repeat some part of our program with a list of values in a set range, for example:
for i in range(1,20): answer = i**2 print("The value of i squared is... " + str(answer))
This will tell you the value of i squared, starting with i=1, up to i=19. Note that we have had to use the str() command to get Python to print out the message and the value of 'answer'. This converts the integer value of 'answer' to a string, so that it can be added to the message (which itself is a string!). Give it a go and try playing around with different values and different calculations.