An Introduction to Python For Undergraduate Engineers/For Loops

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.

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:

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;

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:

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.