user1824179
user1824179

Reputation: 67

Using global variables

My question is referring to my previous python problem which I was able to solve and make it work perfectly. How do I print something and then its list?

Recently, I've been introduced with global variables, but I have no idea how to use them, I've got two functions which I'm not allowed to change:

def who_exports(product):
    return products[product]

def what_exports(country):
    return countries[country]

I have to write a function called prepare_data() which prepares data and makes all variables and those two functions work. It prepares data for who_exports and what_exports. It should work like that:

who_exports("nickel")
{'Botswana', 'Colombia', 'Cuba'}

and then

what_exports("Yemen")
{' oil, coffee, fish, liquefied natural gas'}

I've been trying and trying and I either get global name "products,countries,country,..." is not defined or keyerror:"nickel".

def prepare_data():
    global products
    global product
    global countries
    global country

    countries={}
    products={}

Help would be appreciated, thanks!!

Upvotes: 0

Views: 153

Answers (2)

erbridge
erbridge

Reputation: 1386

I'm not clear why you need country and product as globals, since you can just call who_exports('nickel'), specifying the particular product.

This is what I'd do for countries and products, though.

def prepare_data():
    countries = {'Yemen' : 'oil, coffee, fish, liquefied natural gas'}
    products = {'nickel' : ['Botswana', 'Colombia', 'Cuba']}
    return countries, products

countries, products = prepare_data()

Upvotes: 1

D.Shawley
D.Shawley

Reputation: 59563

Consider using defaultdict instead of literal dictionaries.

Upvotes: 0

Related Questions