I have tuple variables which are France, Germany. I'm trying to give a value to my bring_cities function and if it's France or Germany, I like to see the France and Germany tuple objects. Is there any shortcut to not use if loops like I did in the below ?
France = (
('Paris', 'Paris'),
('Lyon', 'Lyon'),
)
Germany = (
('Frankfurt', 'Frankfurt'),
('Berlin', 'Berlin'),
)
cities = (('', ''),) France Germany
def bring_cities(country):
if country == 'France':
return France
if country == 'Germany':
return Germany
...
CodePudding user response:
You can create a dictionary so you don't have to write an if statement for each country. You can use the following code for that.
France = (
('Paris', 'Paris'),
('Lyon', 'Lyon'),
)
Germany = (
('Frankfurt', 'Frankfurt'),
('Berlin', 'Berlin'),
)
dictionary = {"France": France, "Germany": Germany}
def bring_cities(country):
return dictionary[country]
to make it even shorter you can define your Countries inside the dictionary.
dictionary = {
"France": (('Paris', 'Paris'), ('Lyon', 'Lyon')),
"Germany": (('Frankfurt', 'Frankfurt'), ('Berlin', 'Berlin'),)
}
CodePudding user response:
Resuming gerda's answer
France = (
('Paris', 'Paris'),
('Lyon', 'Lyon'),
)
Germany = (
('Frankfurt', 'Frankfurt'),
('Berlin', 'Berlin'),
)
dictionary = {"France": France, "Germany": Germany}
def bring_cities(country):
print(dictionary[country])
user_choice = input("Enter a Country (France/Germany) and we will give you Cities in it: ")
bring_cities(user_choice)