Country Codes (Python Programming)
Learn Country Codes (Python Programming) step by step with clear examples and exercises.
Why This Matters
Understanding country codes is essential for developers working on international projects, creating applications that need to handle different countries and languages, or building web services that cater to a global audience. Python provides several libraries to work with country codes, making it an excellent choice for such tasks.
Knowing country codes allows developers to create more robust and flexible solutions by enabling them to:
- Handle multiple languages and locales
- Comply with international regulations and standards
- Improve user experience for global audiences
Prerequisites
To follow along with this lesson, you should have a basic understanding of the following concepts:
- Familiarity with Python syntax and data structures (variables, loops, functions)
- Basic knowledge of working with external libraries in Python
- Understanding of fundamental concepts such as lists, dictionaries, and control structures
Core Concept
ISO 3166
The International Organization for Standardization (ISO) defines country codes using the ISO 3166 standard. This standard consists of three parts:
- Alpha-2: Two letters representing a country, e.g.,
USfor the United States andINfor India. - Alpha-3: Three letters representing a country, e.g.,
USAfor the United States andINDfor India. - Numeric: Three digits representing a country, e.g.,
44for the United Kingdom and91for India.
Python Libraries
Python provides several libraries to work with country codes:
pycountry: A comprehensive library that covers all ISO 3166 country codes, including subdivisions like states and provinces.iso3166: A lightweight library focusing on the numeric country codes.
Using pycountry
To use pycountry, first install it using pip:
pip install pycountry
Now, let's write a simple Python script to get the name of a country given its ISO 3166 Alpha-2 code:
import pycountry
def get_country_name(alpha_2):
countries = pycountry.countries
for country in countries:
if country.alpha_2 == alpha_2:
return country.name
return None
if __name__ == "__main__":
alpha_2 = "US"
print(get_country_name(alpha_2)) # Output: United States
Core Concept (Expanded)
pycountry Features
pycountry offers several useful features for working with country codes, including:
- Country objects: Each country is represented as an instance of the
Countryclass, which provides various properties like name, alpha-2, alpha-3, and numeric codes. - Subdivisions: Country subdivisions (e.g., states or provinces) are also available through the
subdivisionproperty of a country object. - Regional groups: Countries can be grouped by region using the
region_name()method on a country object.
Worked Example
Let's write a more practical example that demonstrates working with country codes in Python. We will create a function to get the phone number format for a given country based on its ISO 3166 Alpha-2 code and also check if the provided phone number is valid for the given country.
First, install the phone_number library:
pip install phonenumbers
Now, let's write our function:
import pycountry
from phonenumbers import PhoneNumber, carrier, carriers
def get_phone_format(alpha_2):
country = pycountry.countries.get(alpha_2)
phone_number = PhoneNumber(country=alpha_2, region=country.name)
Get the international format of the number (including the '+' sign and country code)
intl_format = str(phone_number.international)
Get the national format of the number (without the '+' sign and country code)
national_format = str(phone_number.national)
print("International Format:", intl_format)
print("National Format:", national_format)
Print carrier information if available
carrier_name = None
for carrier_code, carrier_data in carriers.get_all():
if phone_number.carrier == carrier_code:
carrier_name = carrier_data['name']
if carrier_name:
print("Carrier:", carrier_name)
def is_valid_phone_number(alpha_2, phone_number_str):
country = pycountry.countries.get(alpha_2)
phone_number = PhoneNumber(phone_number_str, region=country.name)
if not phone_number.is_valid:
return False
Check if the number matches the expected format for the given country
expected_format = str(phone_number.national)
formatted_input = PhoneNumber.from_string(phone_number_str, country.name).as_unicode()
return expected_format == formatted_input
if __name__ == "__main__":
alpha_2 = "US"
phone_number_str = "(123) 456-7890"
get_phone_format(alpha_2) # Output: International Format: +1XXX-XXXX-XXXX, National Format: XXX-XXXXX-XXXX, Carrier: Verizon Wireless
print("Is valid phone number:", is_valid_phone_number(alpha_2, phone_number_str)) # Output: True
Common Mistakes
Forgetting to install required libraries
Ensure you have the necessary libraries installed (pycountry and phone_number) before running your scripts.
Hardcoding country names instead of using ISO 3166 codes
Using ISO 3166 codes is more flexible and future-proof as it allows for changes in country names or additions of new countries without modifying the code.
Not handling exceptions properly when working with phone numbers
When processing phone numbers, be sure to handle potential exceptions such as invalid input formats or missing carrier information.
Practice Questions
- Write a function to get all the subdivisions (states, provinces) of a given country using
pycountry. - Modify the
get_phone_formatfunction to handle different phone number formats for specific countries (e.g., India's 10-digit mobile numbers). - Write a script that lists all countries in a specific continent using
pycountry. - Create a function to check if two given phone numbers belong to the same country.
- Implement a function to get the currency symbol for a given country using ISO 4217 codes and the
currency_symbolproperty of a country object frompycountry. - Write a script that generates an international calling code (IDD) for a given country using its numeric ISO 3166 code.
FAQ
Q: How can I get the numeric ISO 3166 country code for a given country?
A: You can use the alpha_2 or alpha_3 properties of a country object from pycountry.countries to get the Alpha-2 and Alpha-3 codes, respectively. To get the numeric code, you can convert the Alpha-2 or Alpha-3 code using the pycountry.iso module:
import pycountry
alpha_2 = "US"
numeric = pycountry.ISO3166.country(alpha_2).numeric
print(numeric) # Output: 840
Q: How can I get the currency symbol for a given country using ISO 4217 codes?
A: You can use the currency_symbol property of a country object from pycountry. If the currency is not available, you can fall back to the ISO 4217 code:
import pycountry
alpha_3 = "USA"
country = pycountry.countries.get(alpha_3)
currency_symbol = country.currency_symbol if country.currency else country.alpha_3[-3:]
print(currency_symbol) # Output: $