P
P
Programmer_Jr2020-09-19 16:33:20
Python
Programmer_Jr, 2020-09-19 16:33:20

Yandex Practicum. Lesson 6 "Counters". I can't find the error in the code, can you help?

Counters, Yandex Practicum, lesson 6.
The task is as follows:
There are lists of average daily temperatures in Moscow for May 2017 and 2018. Create a comfort_count(temperatures) function to count comfortable days in the passed list — days with air temperature between 22 and 26 degrees inclusive.
As a result of the work, the function should display the string 'Number of comfortable days this month: N', where N is the result of the calculation in the loop with the condition. First, count the comfortable days in May 2017, and then in May 2018.

Here is the code:
may_2017 = [24, 26, 15, 10, 15, 19, 10, 1, 4, 7, 7, 7, 12, 14, 17, 8, 9, 19, 21, 22, 11, 15, 19, 23, 15, 21, 16, 13, 25, 17, 19]
may_2018 = [20, 27, 23, 18, 24, 16, 20, 24, 18, 15, 19, 25, 24, 26, 19, 24, 25, 21, 17, 11, 20, 21, 22, 23 , 18, 20, 23, 18, 22, 23, 11]

# add code below

N = 0
def comfort_count(temperatures):
    for temp in temperatures:
        if temp >=22 and temp <=26:
            N = N + 1
            print("Количество комфортных дней в этом месяце: ", N)

#do not change the code further
comfort_count(may_2017) # find out what happened in May 2017
comfort_count(may_2018) # find out what happened in May 2018

My code is written in bold
The error is:

Traceback (most recent call last):
File "main.py", line 12, in
comfort_count(may_2017) # find out what happened in May 2017
File "main.py", line 9, in comfort_count
N = N + 1
UnboundLocalError: local variable 'N' referenced before assignment

Answer the question

In order to leave comments, you need to log in

4 answer(s)
_
_, 2020-09-19
@mrxor

your counter was outside the function, do this:

def comfort_count(temperatures):
    n = 0
    for temp in temperatures:
        if temp >= 22 and temp <= 26:
            n += 1
    print("Количество комфортных дней в этом месяце: ", n)

S
Sergey Gornostaev, 2020-09-19
@sergey-gornostaev

It was worth reading the textbook before taking on the Yandex workshop.

D
Dmitry, 2020-09-19
@dimoff66

Put N inside the procedure, why is it declared outside? And also print should not be inside a loop, otherwise it will produce a new number each time it finds a matching element and not for the whole month.

I
InnOn, 2021-01-10
@InnOn

def comfort_count(temperatures):
count = 0
for temp in temperatures:
if 22 <= temp and temp <= 26:
count += 1
print('Number of comfortable days this month: ' + str(count))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question