Part 1 Block 2 - Problem Solving in Python Flashcards
When writing an algorithm, do we usually number our steps?
No, because we often make revisions and it could be confusing.
In a ‘for’ loop, how do we tell the program that we need, say, 5 iterations?
range(5)
If we use just one number to specify range, i.e. how many iteration we require, does Python count from 0 or 1?
From 0
So, range(5) would count: 0, 1, 2, 3, 4
How would we write the number of iterations (e.g. range( )) if we have two number, e.g. 1 to 5?
What number would Python start counting from in this case?
range(1, 5)
It would count from 1.
Lists in variable
How would we store the following numbers as a list for a variable called ‘results’:
1,7, 13, 8, 9
results = [1, 7, 13, 8, 9]
What would I type if I wanted to access the second number in my variable list?
results[1]
When counting numbers in a variable list in Python like ‘results’ do we start from ‘0’ or ‘1’?
0
When considering the variable ‘results’ which stores a list of values, what would we type to find the length of the list, and what result would we get?
len(results)
5
What would I type if I wanted to add all the values in the variable list?
What answer would I get?
What would be a faster way of doing the same thing?
Can the range for the loop can be specified by using just one number, e.g.
for index in range(len(results)):
total = results[0] + results[1] +results[2] +
results[3] + results[4]
38
total = 0
for index in range(0, len(results)):
total = total + results[index]
Yes, it can!
When swapping elements of the list, it will be useful to hold one of them in an extra variable – call this variable _____________.
temp
Look at the following example to help you. Let’s say we have a variable a that has the value 1, and a variable b that has the value 2.
What happens if we try to swap them, using the following code:
a = b
b = a
How can we avoid losing a value?
Both will end up with a value of 2.
We can avoid ‘losing a value’ using a variable, temp. Consider the following code:
temp = a
a = b
b = temp
In the following code, what is the name of the counter?
for shape in range(1, number_of_shapes + 1):
# Draw a triangle
for sides in range(1, 4):
forward(40)
left(120)
shape