2021年4月23日星期五

How can I get input from the user and check if part of it is a key in my dictionary?

I need to get input from the user and check if the word following 'city' is inside of my dictionary (the key).

This is my dic:

mydic = {'Paris':132, 'Rome':42, 'San Remo':23}  

I need the user to write 'city' (they will do so, given instructions that I gave them) but after it they have to write a city name. So they will write something like: 'city paris' and that has to return: 'Paris has 132 churches' or if they write 'city san remo' it has to return: 'San remo has 23 churches'.

The code has a conditional because if the user types 'city gba' then it returns a specific thing. So the issue is in the elif part where there are a lot more city options.

This is what I thought could work but doesn't for obvious reasons:

user_input = input().lower()    if user_input == 'city gba':      print('City gba has', city_data.get('gba'), 'churches')  elif user_input.split() == 'city' + '':          for x in user_input:              if x in mydic.keys():                  print(x, 'has', city_data.get(x), ' churches.')  

How else can I do this? Thank you.

https://stackoverflow.com/questions/67238203/how-can-i-get-input-from-the-user-and-check-if-part-of-it-is-a-key-in-my-diction April 24, 2021 at 08:21AM

没有评论:

发表评论