V
V
verbalistus2020-04-15 11:32:33
Python
verbalistus, 2020-04-15 11:32:33

YandexPracticum, why does the bot not see the nested function?

Given the task:

A lot of requests come to the servers - from different users or from other servers. Change the process_query() function (the request handler) to support multiple different queries instead of just one.
Add a query argument to the process_query() function. This argument will tell you which request to process.
At the top of the process_query() function, add a check for the value of the query variable:
if the value is 'How many friends do I have?' - print the answer to this question, as in the previous task;
otherwise print '<unknown query>';
Anfisa should say hello at any request.
Add a process_query('How many friends do I have?') call to the main body of the program.
Add another process_query('What's my name?') call to the main body of the program.
Tip

Use the comparison if query == ... to define a query.

Start code:

FRIENDS = ['Серёга', 'Соня', 'Дима', 'Алина', 'Егор']
friends_count = 0
def print_friends_count(friends_count):
    if friends_count == 1:
        print('У тебя 1 друг')
    elif 2 <= friends_count <= 4:
        print('У тебя ' + str(friends_count) + ' друга')
    elif friends_count >= 5:
        print('У тебя ' + str(friends_count) + ' друзей')

def process_query():
# перенесите в функцию process_query() вот этот код:
    print("Привет, я Анфиса!")
    count = len(FRIENDS)
    print_friends_count(count)


Nashkodil solution:
FRIENDS = ['Серёга', 'Соня', 'Дима', 'Алина', 'Егор']
count = len(FRIENDS)
def process_query(query):
    print('Привет, я Анфиса!')
    if query == 'Сколько у меня друзей?':
        def print_friends_count(count):
            if count == 1:
                print('У тебя',count,'друг')
            elif 2 <= count <= 4:
                print('У тебя',count,'друга')
            elif count >= 5:
                print('У тебя',count,'друзей')
        print_friends_count(count)
    else:
        print('<неизвестный запрос>')
process_query('Сколько у меня друзей?')
process_query('Как меня зовут?')


The result satisfies the task questions:

Hello, I'm Anfisa!
You have 5 friends
Hi, I'm Anfisa!
<unknown request>


However, the bot does not accept the response, it writes "The print_friends_count() function does not exist. Do not delete it."
I can't understand what is the reason :(

And another question:
The print_friends_count(count) function is launched by the print_friends_count(count) command. If possible, please explain why calling the process_query(query) function is unacceptable in this program. If you call it after the operator ELSE, with the process_query(query) command, then a cyclic output to the screen occurs, depending on the place of the function call (indents +/- 4 spaces on the next line after ELSE):

Hello, I'm Anfisa!
You have 5 friends
Hi, I'm Anfisa!
You have 5 friends
...


or

Hello, I'm Anfisa!
You have 5 friends
Hi, I'm Anfisa!
unknown request
Hi, I'm Anfisa!
unknown request
...

Answer the question

In order to leave comments, you need to log in

6 answer(s)
S
Sergey Pankov, 2020-04-15
@trapwalker

A function in python is an object of the first kind.
Everything in python is an object. And function and number and string and list and dictionary and class and class instance.
Each object can have many names. Think of the name of an object like a tag attached to a tea bag.
print_friends_count(count)
Here print_friends_count is the name of the variable, and the brackets after it cause the object available as a function to be called with that name. The call is made with a single argument, which is available by name count .
If in the python code in some expression (and a function call is an expression; the result of the call is always some value, for example None; yes, None is also an object, it is returned by the default function) there is some name , then this name is searched in the local scope of this function (that is, in the function itself), then in the scope where the function is declared, then even higher, and so on up to the module itself. The topmost - global scope - is the module. If the name was not found anywhere, even in the module, then it will be looked up among __builtins__ - this is such a dictionary with names and objects available everywhere. If it is not found there, then there will be an error.
In your case, the function should have been left at the module level. It will be possible to call it anywhere inside the module, but on the condition that the function declaration statement has already been executed.
When you run a program (or import a module), all statements are executed in turn (imports, function/class declarations, naming the results of some expressions...)
I think you should download Lutz's book about learning python from scratch and read it thoughtfully. In order.

N
Nikolay, 2020-04-16
@SODINNER

I advise you not to go to the toaster, but to Yandex Practicum, I took an introductory course there, support helps even without paying for the main course, and I assure you, they will help you better than people on the toaster.

S
SvetlanaOmsk, 2020-06-11
@SvetlanaOmsk

Hello, did you find a solution? My code is like this, but I have a different problem. The bot writes: "Anfisa should always say a greeting at the beginning of each answer!"... How is this to be understood? What is the problem? An error in the code? Algorithm? or what? The curator does not answer.
The result appears to be normal, if you remove an element from the list, the word "friends" declines as it should, the number of elements also changes. I have already tried to put the greeting everywhere: right at the beginning of the function, and in each condition separately, and as a separate function, the error remains.
Because of this problem, until I figure it out, I can not move on.

FRIENDS = ['Серёга', 'Соня', 'Дима', 'Алина', 'Егор']
def process_query(query):
# перенесите в функцию process_query() вот этот код:
    
    if query=="Сколько у меня друзей?":
        print("Привет, я Анфиса!")
        count = len(FRIENDS)
        print_friends_count(count)
        return

    else:
        print("Привет, я Анфиса!")
        print("<неизвестный запрос>")
def print_friends_count(friends_count):
    if friends_count == 1:
        print('У тебя 1 друг')
    elif 2 <= friends_count <= 4:
        print('У тебя ' + str(friends_count) + ' друга')
    elif friends_count >= 5:
        print('У тебя ' + str(friends_count) + ' друзей')

process_query("Сколько у меня друзей?")
process_query("Как меня зовут?")

S
Stikkibr, 2021-03-27
@Stikkibr

it turned out like this
FRIENDS = ['Seryoga', 'Sonya', 'Dima', 'Alina', 'Egor']
def print_friends_count(friends_count):
if friends_count == 1:
print('You have 1 friend')
elif 2 <= friends_count <= 4:
print('You have ' + str(friends_count) + ' friend')
elif friends_count >= 5:
print('You have ' + str(friends_count) + ' friends')
# move it to the process_query() function here is the code:
def process_query(query):
print("Hi, I'm Anfisa!")
if query == 'How many friends do I have?':
count = len(FRIENDS)
print_friends_count(count)
elif query == 'Who are all my friends?':
count = ', '.join(FRIENDS)
print('Your friends are: ' + count)
else:
print("<unknown query>")
process_query('How many friends do I have?')
process_query('What's my name?')
process_query('Who are all my friends?')

L
Lamefox, 2021-04-14
@Lamefox

Hey! For task No. 2, he took torment, then he realized that he had to act according to the instructions, not giving the thought to turn around where it was not necessary. It turned out like this:
def process_query(query):
print("Hi, I'm Anfisa!")
count = len(FRIENDS)
#print_friends_count(count) # - set to zero so that the function is not called twice. Check from the task below:
if query == 'How many friends do I have?': # - is in the tooltips, but it's clear.
print_friends_count(count)
else:
print('<unknown query>')
process_query('How many friends do I have?')
process_query('What's my name?')
Task #3 is solved like this:
def process_query(query):
print("
count = len(FRIENDS)
#print_friends_count(count)
if query == 'How many friends do I have?':
print_friends_count(count)
elif query == 'Who are all my friends?':
print('Your friends: '+ ', ' .join(FRIENDS))
else:
print('<unknown query>')
#process_query('How many friends do I have?')
process_query('What's my name?')
process_query('Who are all my friends?') - # Task : Add a call to process_query('Who are all my friends?') in the body
# of the main program.

T
tw1sted0s, 2021-09-28
@tw1sted0s

Answer to task 2

FRIENDS = ['Серёга', 'Соня', 'Дима', 'Алина', 'Егор']

def print_friends_count(friends_count):
    if friends_count == 1:
        print('У тебя 1 друг')
    elif 2 <= friends_count <= 4:
        print('У тебя ' + str(friends_count) + ' друга')
    elif friends_count >= 5:
        print('У тебя ' + str(friends_count) + ' друзей')


# перенесите в функцию process_query() вот этот код:
def process_query(query):
    print("Привет, я Анфиса!")
    count = len(FRIENDS)
    if query == 'Сколько у меня друзей?':
        print_friends_count(count)
    else:
        print('<неизвестный запрос>')

    

process_query('Сколько у меня друзей?')
process_query('Как меня зовут?')

Answer to task 3
FRIENDS = ['Серёга', 'Соня', 'Дима', 'Алина', 'Егор']

def print_friends_count(friends_count):
    if friends_count == 1:
        print('У тебя 1 друг')
    elif 2 <= friends_count <= 4:
        print('У тебя ' + str(friends_count) + ' друга')
    elif friends_count >= 5:
        print('У тебя ' + str(friends_count) + ' друзей')


# перенесите в функцию process_query() вот этот код:
def process_query(query):
    print("Привет, я Анфиса!")
    count = len(FRIENDS)
    if query == 'Сколько у меня друзей?':
        print_friends_count(count)
    elif query == 'Кто все мои друзья?':
        print('Твои друзья: '+', '.join(FRIENDS))
    else:
        print('<неизвестный запрос>')

process_query('Сколько у меня друзей?')
process_query('Как меня зовут?')
process_query('Кто все мои друзья?')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question