Почему такое сравнение не работает?

town = {'Kyiv': 'Ukraine', 'Athens': 'Greece', 'Baku': 'Azerbaijan', 'Berlin': 'Germany', 'Washington': 'USA', 'Brussels': 'Belgium', 'Dakar': 'Senegar', 'Cairo': 'Egypt', 'Caracas': 'Venezuela', 'Lisbon': 'Portugal'}

while True:
    text_user = input('Input town:')
    if text_user == 'stop':
        print('The game is stopped')
        break
    try:
        if town != text_user:
            print(f'This is the capital of {town[text_user]}')
        else:
            print('This is not the capitalq')
    except:
        print('This is not the capital')

Почему когда if if town == text_user: то оно не работает. Так же логично, не так ли?


Ответы (2 шт):

Автор решения: elderberry17

Если я верно понимаю, вы пытаетесь получить в input'е столицу, и по ней вывести юзеру государство с этой столицей из вашего словаря. В таком случае будет корректно проверить, есть ли данная столица в ключах вашего словаря (ключи у вас -- города, значение по ключу -- страна) Сделать это можно с помощью условия:

if text_user in town:
    print(f'This is the capital of {town[text_user]}'
→ Ссылка
Автор решения: Сергей Ш

dict.get(key[, default]) - возвращает значение ключа, но если его нет, не бросает исключение, а возвращает default (по умолчанию None).

town = {'Kyiv': 'Ukraine', 'Athens': 'Greece', 'Baku': 'Azerbaijan', 'Berlin': 'Germany', 'Washington': 'USA',
            'Brussels': 'Belgium', 'Dakar': 'Senegar', 'Cairo': 'Egypt', 'Caracas': 'Venezuela', 'Lisbon': 'Portugal'}

text_user = 'Kyiv'  # input('Input town:')
cap = 'This is not the capital'
if town.get(text_user):
    cap = f'This is the capital of {town[text_user]}'
print(cap)

try-except

text_user = 'Baku'  # input('Input town:')
try:
    cap = f'This is the capital of {town[text_user]}'
except KeyError:
    cap = 'This is not the capital'
print(cap)

Тернарный оператор

text_user = 'Cairo'  # input('Input town:')
print(f'This is the capital of {town[text_user]}' if town.get(text_user) else 'This is not the capital')
→ Ссылка