N
N
NubasKontrabas2021-11-24 23:15:06
Python
NubasKontrabas, 2021-11-24 23:15:06

How to select the second option in the dictionary using if-else? (Python, task from Yandex Practicum)?

Hello,

the task sounds like this:
Why not go to Khabarovsk? It would be great to meet friends there. But do any of them live there?
Teach Anfisa how to solve this problem - write the is_anyone_in(collection, city) function.
The function should take as input the friends dictionary and the name of the city you want to go to.
For each inappropriate city in the dictionary, the function should print the phrase
I have a friend in the city <city_name>, but I don't need to go there.
If one of the friends lives in the requested city, the function should print the phrase <friend_name> lives in the
city <city_name>. We're going to visit!

how to make it so that if it does not match with Khabarovsk, another city is displayed?
the code looks like this:

friends = {
    'Серёга': 'Омск', 
    'Соня': 'Москва', 
    'Дима': 'Челябинск', 
    'Алина': 'Хабаровск', 
    'Егор': 'Пермь'
}

def is_anyone_in(collection, city):
    for friend in collection:
        if collection[friend] == city: 
            print("В городе " + city + " живёт " + friend + ". Едем в гости!")
        else:
            print("В городе " + city + " у меня есть друг, но мне туда не надо.")
    
is_anyone_in(friends, 'Хабаровск')

the result is this:(
I have a friend in the city of Khabarovsk, but I don’t need to go there.
I have a friend in the city of Khabarovsk, but I don’t need to go there.
I have a friend in the city of Khabarovsk, but I don’t need to go there.
In the city of Khabarovsk Alina lives. We're going to visit!
I have a friend in the city of Khabarovsk, but I don't need to go there.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xawad, 2022-01-21
@xawad

friends = {
'Seryoga': 'Omsk',
'Sonya': 'Moscow',
'Dima': 'Chelyabinsk',
'Alina': 'Khabarovsk',
'Egor': 'Perm'
}
def is_anyone_in(collection, city) :
for friend in collection:
if collection[friend] == city:
print(" + friend + " lives in the city " + collection[friend] + ". I'll definitely come visit!")
else:
print("In the city " + collection[friend] + "I have a friend, but I don't need to go there.")
is_anyone_in(friends, 'Khabarovsk')
don't forget to properly indent

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question