I am new to this community so I hop this is the right part on the site for my question.
Iam learning myself al little of programming with the book “python crash course”. Now I have to create a dictionary of cities at question 6.11. I think i have done that and it works, but there is still one thing that I am no satisfied with. I have pasted the code below. The output looks ok but when it prints “Usa” I want to print “USA”. I want to do this with an “if” statement. Can anybody help me with this, I don’t know where to and how to do this in this program.
Create a library of 3 cities with some extra information
Create a neat output for the cities and the additional info
for city, city_info in cities.items():
country = city_info[‘country’].title()
population = city_info[‘population’]
attraction = city_info[‘attraction’].title()
print(f"\nThe captial of {country} is {city.title()}.")
print(f"{city.title()} has a poulation of {population}.")
print(f"The main attraction of {city.title()} is {attraction}.")
Thanks for the answer.I know that is also a way. Only for me too learn and out of curiosity I would like to try it with an if statement. Something like:
if countryis usa print ***.upper() els print ****.title()
Generally speaking - it doesn’t make sense to write manually and wrong and then invent solution to the problem one should avoid in the first place. Write it correctly. Another story is if you get data from source you have no influence over formatting.
Solution with if-s is not very scalable. Should this list contain all countries abbreviations (prc - Peoples Republic of China, etc)? What string method to use if one of the countries is côte d’ivoire (Côte d’Ivoire)?
Of course for assigment this solution may be appropriate. But if you look for real-life-like scenario, then much more complex solution is needed.
I already thought it wasn’t the best to solve this with an IF-statement, but I am just starting with the course. The chapter before this chapter was the IF/ELSE chapter, so I was curious how I could use this. Maybe later I will learn a total solution .
Thank you very much for the input.
I tried some answers and adjusted some parts but when I use the code below in the last part it works:
for city, city_info in cities.items():
if city_info[‘country’].upper() == ‘USA’:
country = city_info[‘country’].upper()
else:
country = city_info[‘country’].title()
population = city_info['population']
attraction = city_info['attraction'].title()
print(f"\nThe capitial of {country} is {city.title()}.")
print(f"{city.title()} has a population of {population}.")
print(f"The main attraction of {city.title()} is {attraction}.")
when you embed code snippets, try selecting said text and pressing the “</>” (Preformatted Text) button after that - you’ll get correctly indented code then…