Outcomes Writing Loops Using For: Gibson Lam and David Rossiter
Outcomes Writing Loops Using For: Gibson Lam and David Rossiter
COMP1021 • After completing this presentation, you are • Previously, we have discussed the use of while
Introduction to Computer Science expected to be able to: loops to do things repeatedly in Python
1. Use the range command to make a range of • In this presentation, we will look at another
numbers way of doing loops, using for loops
Using For Loops 2. Write loops using the for command • Using a for loop:
– you can perform some actions a particular
number of times, or:
Gibson Lam and David Rossiter – you can loop through a set of data, performing
the same actions on every item in the set
COMP1021 Using For Loops Page 2 COMP1021 Using For Loops Page 3
COMP1021 Using For Loops Page 4 COMP1021 Using For Loops Page 5 COMP1021 Using For Loops Page 6
Controlling a For Loop Printing Things Using ‘end’ Using a ‘Fixed’ List in a For Loop
• As you can see from the previous slide the range • When you print things using the print command it • You can use a ‘fixed’ list instead of a list of
command can be used to control: moves to the next line after it finishes printing numbers given by the range command
– how many times the content of a for loop is • In the previous examples, we use the ‘end’ value to ask • For example, you can use any numbers you like:
repeatedly executed the print command to print a space at the end instead for i in [33, 19, 5, -7]:
– the number each time the loop content is executed • The end value is useful when you have multiple print print(i, end=" ")
commands that print things on the same line, e.g:
• Here are some more examples: You use a pair of brackets, i.e. [],
print("These are ", end="") In this example, to enclose the list of items
for i in range(0, 6): nothing, i.e. "",
print("shown on ", end="")
print(i, end=" ") print("the same line!") is printed at the • Or, you can choose not to use any numbers at all:
end of the text for word in ["How", "are", "you"]:
for i in range(1, 6, 2):
print(i, end=" ") print(word, end=" ")