After a function is defined and will be called, it is natural to pass required information in the calling statement. In the following example, we create a function about traveling with parameter person and country, for printing the country people have recently traveled.
#define a function of travel, with two parameter, person and country
def travel(person, country):
"""Print the country people have traveled"""
print(person+ " have recently been to " + country)
#call the function
travel("Wilson", "USA")
#output
Wilson have recently been to USA
Sometimes, there are multiple elements that will be passed as the particular type of information when calling the function. Say, we assume there may have more than one country that a person have traveled in the past year, but we do not know how many. In this situation, a parameter following an asterisk can be used in function definition. Python packs all the remaining information after ‘person’ into a tuple ‘countries’.
#a function for person and countries have been traveled
def travel(person, *countries):
"""Print the country people have traveled"""
print(person+ " have recently been to ")
for country in countries:
print("- " + country)
#calling function
travel("Wilson", "USA")
#output
Wilson have recently been to
- USA
#calling function again
travel("Wilson", "USA", "Japan","China")
#output
Wilson have recently been to
- USA
- Japan
- China
Moreover, if the required information passed to a function is key value pairs, then we can add double asterisk in front of the parameter in function definition. In the following example, both the country and city information are needed for the function calling, and Python packs all the passing information into a dictionary ‘cities’.
#define a function, accepting key value pair information
def travel(person, **cities):
"""Print the country people have traveled"""
print(person+ " have recently been to ")
for key, value in cities.items():
print("- " + key + ": " + value)
#call function
travel("Wilson", USA = "Boston")
#output
Wilson have recently been to
- USA: Boston
#call function again
travel("Wilson", USA = "Boston", Japan="Tokyo",China="Shanghai")
#output
Wilson have recently been to
- USA: Boston
- Japan: Tokyo
- China: Shanghai
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…