Why doesn't it work inside the cycle for?
-
Good night.
Got a list of questions. In every question, the first word is a man's name.
Accordingly, there is a code that checks the first word on each question and, if it matches the predetermined name, the message is "Request for thewills." If the first word doesn't match the predetermined name, the message is "request for someone else."
In the code, it is implemented through the cycle for and operators if and else. Under another, there are cases where the first word of the question does not match the predetermined name. The problem is, the other doesn't work, and the program is acting like the right name is at the beginning. Can you tell me what the problem is and what needs to be corrected?
Here's the code:
def check_query(query): for r in queries: r_string = r.split() if r_string[0] == 'Анфиса,': return ('Запрос к Анфисе') else: return ('Запрос к кому-то еще')
queries = [
'Анфиса, сколько у меня друзей?',
'Андрей, ну где ты был?',
'Андрей, ну обними меня скорей!',
'Анфиса, кто все мои друзья?'
]for q in queries:
result = check_query(q)
print(q, '-', result)```
-
Because you need to be careful with your backups, you're not in the cycle.
for r in queries: r_string = r.split() if r_string[0] == 'Анфиса,': return ('Запрос к Анфисе') else: return ('Запрос к кому-то еще')
It's like this:
for r in queries: r_string = r.split() if r_string[0] == 'Анфиса,': return ('Запрос к Анфисе') else: return ('Запрос к кому-то еще')
P. S.
concerning your problem
Here's the right code:
def check_query(query): r_string = query.split() if r_string[0] == 'Анфиса,': return ('Запрос к Анфисе') else: return ('Запрос к кому-то еще')
queries = [
'Анфиса, сколько у меня друзей?',
'Андрей, ну где ты был?',
'Андрей, ну обними меня скорей!',
'Анфиса, кто все мои друзья?'
]for q in queries:
result = check_query(q)
print(q, '-', result)
You've had logical mistakes in your code:
You're moving the parameter.
check_query(q)
- List elementqueries
but you don't use that parameter in your function.def check_query(query):
for r in queries:
As a result, you have the following:
Every time in the cycle, you extract the first entry from your global list.
Анфиса, сколько у меня друзей?
You break it into words and compare it toАнфиса,
And get out of the cycle without watching the rest of the records.So it's not like it's always gonna be Anfi issue.
Besides, you don't need a cycle inside your function, because the cycle is already out of the function where the list is being re-examined.
queries
and within the function, it's only necessary to break into words and compare with the first word.P.P.S.
By the way, without breaking into words, you can compare:
if r[:7] == 'Анфиса,'