The problem lies in the color_count
function.
# You wrote:
def color_count(colour):
for colour in thread_sold_split:
count = thread_sold_split.count(colour)
return count
There are a number of problems with the above snippet of code.
- Firstly, the parameter of your function is
colour
. Whatever input is passed as the argument to the color_count
function will be assigned to this parameter. That is fine and as intended.
But, in the very next statement,
for colour in thread_sold_split:
you discard the argument. The above loop will iterate over all the elements of the thread_sold_split
list and in each iteration, an element will be assigned to the loop variable colour
. You should choose a different name for the loop variable. You shouldn’t use the same variable name for both the loop variable and the parameter. Consider the following trivial example,
# In this version, the argument is overwritten since the
# loop variable n has the same name as the parameter n.
def func(n):
for n in [1, 2, 3]:
print(n)
print(n)
func(10)
# 1
# 2
# 3
# 3
# Compare with this version which uses i as the loop variable and
# hence avoids corrupting the value assigned to the parameter n.
def func(n):
for i in [1, 2, 3]:
print(i)
print(n)
func(10)
# 1
# 2
# 3
# 10
- Secondly, your function will only complete one iteration and then exit immediately because of the indentation of the
return
statement. Consider the following example,
# In this version, the return statement is indented as part of the
# loop body. As soon as the return statement is executed, we
# exit the function. Only the first iteration is completed.
def f():
total = 0
for i in [1, 2, 3]:
total += i
return total
print(f())
# 1
# In this version, the return statement is not part of the loop body.
# Notice the indentation. The return statement is indented as the
# body of the function, but not indented as part of loop body.
# The loop will complete all iterations and then the return
# will be executed.
def f():
total = 0
for i in [1, 2, 3]:
total += i
return total
print(f())
# 6
- Thirdly, even if you fix the indentation, your code will not work properly. Instead, consider the following:
def color_count(colour):
count = thread_sold_split.count(colour)
return count
Since you have decided to use the count
method, so the loop is unnecessary. The count
method will automatically iterate over the thread_sold_split
list and keep a running total of all elements that match the colour provided as the argument. You can then simply return the count. This should give you the correct results.
If you didn’t want to use the count
method, then you could write an explicit loop and use an if statement to increment the total whenever a match is found. Once the loop finishes, you can return the total. But with the count
method, the looping is implicitly handled by the method.
If something is unclear, share your thoughts on what you find confusing.