'Scalar' data types
an_int = 3
a_string = 'foobat'
a_double = 3.9
a_bool = True
'Compound' data types combine multiple pieces of data into a bigger whole.
a_list = [3, 4, 72, 'wombat']
a_dict = {
'name': 'wombat',
'location': 'australia',
'lethality': 'medium'
}
In C++:
class animal {
public:
const string& name();
private:
string name;
string location;
string lethality;
}
animals = [
{
'name': 'wombat',
'location': 'australia',
'lethality': 'medium',
'possible_colors': ['brown', 'grey']
},
{
'name': 'rabbit',
'location': 'england',
'lethality': 'low',
'possible_colors': ['white', 'black', 'grey', 'brown', 'purple']
},
{
'name': 'white rabbit',
'location': 'england',
'lethality': 'high',
'nemesis': 'King Arthur',
'possible_colors': ['white']
}
]
It's useful to structure our lists so that everything in a list is the same kind of thing with the same basic structure. Otherwise, our loops have to do complex things to figure out what on earth they're looking at.
Where do things live?
for animal in animals:
if animal['lethality'] == 'low':
leth_msg = 'will probably not'
elif animal['lethality'] == 'medium':
leth_msg = 'might'
elif animal['lethality'] == 'high':
leth_msg = 'will probably'
else:
leth_msg = 'may or may not, it\'s unclear,'
print('The {} lives in {}. It {} try to kill you.'.format(animal['name'], animal['location'], leth_msg))
print('It can appear in the following colors:')
for color in animal['possible_colors']:
print('- ' + color)
if 'nemesis' in animal:
print('Its nemesis is {}'.format(animal['nemesis']))
# The 'key' parameter provides an expression to extract an attribute
# Sort will then sort by that, instead of trying to sort dictionaries
for animal in sorted(animals, key=lambda a: a['name']):
print(animal['name'])
# Let's sort the other way
for animal in sorted(animals, key=lambda a: a['name'], reverse=True):
print(animal['name'])