def years2days():
print("One year has 365 days!")
years2days()
One year has 365 days!
Workshop 2 – Interactive classroom
So far, we have used functions from python or other packages, such as numpy, to perform a generic task. What if there is no function for a specific task you need to carry out? If you anticipate that you will need to carry out the task again in the future, just write your own function! Moreover, if the program you’re coding is complex, it is good coding practice to partition your program into individual chunks of code (i.e., your own functions). This will help future readers substantially to understand your program.
So let’s write our first own functions!
Let’s make it more useful..
And let’s write a brief statement of what our function does into the docstring that we learned about earlier:
02_workshop/time_conversion.py
and execute the function definition of our function years2days()
years2days?
?days2hours()
into the same file.years2hours()
into the same file and re-use the previous two functions in the conversion.We have already used functions that took more than one argument. Let’s modify our function years2days()
in a way that a user could specify the number of leap years that happened in the given time period.
def years2days(years, n_leapyears=0):
days = (years * 365) + n_leapyears
return days
print(years2days(1))
print(years2days(1, n_leapyears=1))
print(years2days(1, 1))
365
366
366
The above implementation of our function makes use of two types of function arguments. years
is a positional argument. It is called this way, because its position matters (it has to be the first argument provided to the function), and it is required for the function to run successfully. n_leapyears
is called a keyword argument, and it is defined as a pair (keyword_argument=<default_value>
). The value provided with the keyword argument is a default value, so that the user can specify the number of leap years but does not have to. In case the user only provides input for years
, the function assumes n_leapyears
equal to 0
. Keyword arguments can either be provided to the function at the correct position, or by providing the keyword–value pair.