Starting up with Python – Part12

In the last Python post, we have seen Default parameters. In this article, it will be dedicated to Multiple Parameters, Parameter types, and tuples as parameters. Here is a recap from the last article on Python

python_logo_by_bluex_pl

27. Multiple Parameters

Now, we will see how to put multiple parameters in functions. A simple example where we want to make a profile for manager's name having different ages. In the example below, we have the asterisk in front of ages to be able to define as many age we want.

>> def profile(name, *ages):
 ... print name
 ... print ages
 ...

The first value will be treated as a name and everything else after it will be considered as ages. Now, we can call the profile function.

>> profile ('toto', 20,30,40)
 toto
 (20, 30, 40)
The parameter 'toto' is treated as a name and other as ages.28. Parameter typesNow, will we see how to use parameters to convert it into a dictionary? Let's create a function. Imagine we have a hackers group in Mauritius and we will need to categorized how many are there in the south, center, east, west and north. The idea is to use a double asterisk in from of Mauritius.
>> def hackers(**mauritius):
 ... print mauritius
 ...
>> hackers(south=1,center=3,east=1,west=0,north=0)
 {'west': 0, 'east': 1, 'north': 0, 'center': 3, 'south': 1}

This is how we get a dictionary instead of a tuple. Let's now combine both to use a dictionary inside a parameter.

> def hackers(country,nickname,*age,**projects):
 ... print country, nickname
 ... print age
 ... print projects
 ...
 >>> hackers('mauritius', 'TheTunnelix', 29,30, tarsnap=2, kernel=1)
 mauritius TheTunnelix
 (29, 30)
 {'kernel': 1, 'tarsnap': 2}

29.Tuples as Parameters

Now, we will gather information from a dictionary and tuples and use that information as parameters. Instead of creating dictionaries, we can use pre-existing ones as parameters. Let's look at the code below

>> def country(a,b,c):
... return a+b+c

Consider, I already have a tuple as indicated below and we can place the tuple inside the parameter.

>> sum=(4,2,7)
>>> country(*sum)
13

As you can see it output the sum of it. The first star in front sum means that I am working with a tuple and 2 stars means working with a dictionary. In the example below, it gives an example of using the 2 stars.

>> def test(**hello):
... print hello
... 
>>> hackers={'mauritius':5,'india':2,'usa':10}
>>> test(**hackers)
{'mauritius': 5, 'india': 2, 'usa': 10}

This is useful when gathering data from an outside source.