Writing your own functions (5/5)
But what if in our examples we pass as country argument some inappropriate name or name which does not exist in our dictionary? Let's predict it with some conditional statements!
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# data
countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942)}
countries_dict["Brazil"] = (8515767, 212559417)
countries_dict["India"] = (3166391, 1380004385)
# modify our function
def country_information_mod(d, name):
if name not in d.keys():
print("There is no information about", name)
else:
print("Country:", name)
print("Area:", d[name][0], 'sq km')
print("Population:", round(d[name][1]/1000000, 2), 'mln')
# test our function
country_information_mod(countries_dict, "Ukraine")
country_information_mod(countries_dict, "USA")
1234567891011121314151617# data countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942)} countries_dict["Brazil"] = (8515767, 212559417) countries_dict["India"] = (3166391, 1380004385) # modify our function def country_information_mod(d, name): if name not in d.keys(): print("There is no information about", name) else: print("Country:", name) print("Area:", d[name][0], 'sq km') print("Population:", round(d[name][1]/1000000, 2), 'mln') # test our function country_information_mod(countries_dict, "Ukraine") country_information_mod(countries_dict, "USA")
Oppgave
Swipe to start coding
Modify your previous function (name new as people_information_mod
) so now it will detect if the name is in the dictionary. If not, print "There is no information about name"
Løsning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# people dictionary
people_d = {'Alex': (23, 178), 'Noah': (34, 189), 'Peter': (29, 175)}
people_d["John"] = (41, 185)
people_d["Michelle"] = (35, 165)
def people_information_mod(d, name):
if name not in d.keys():
print("There is no information about", name)
else:
print("Name:", name)
print("Age:", d[name][0])
print("Height:", d[name][1])
# test your function
people_information_mod(people_d, "Alex")
people_information_mod(people_d, "Richard")
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 7. Kapittel 6
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# people dictionary
people_d = {'Alex': (23, 178), 'Noah': (34, 189), 'Peter': (29, 175)}
people_d["John"] = (41, 185)
people_d["Michelle"] = (35, 165)
def people_information_mod(d, name):
if name not in _._ _ _():
print("There is no information about", _ _ _)
else:
print("Name:", _ _ _)
print("Age:", _ _ _)
print("Height:", _ _ _)
# test your function
people_information_mod(people_d, "Alex")
people_information_mod(people_d, "Richard")
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår