Continue from part 2.
A (user-defined or from libraries) function is a block of code which only runs when it is called, to do a complete job (module), is named, and can be called to execute multiple times at many places in the program.
What will happen if you don’t use function? What I can think about is repetitive works, hard to debug, hard to expand the whole code, so usually when working on a large project you need to split your code into many small modules.
To use library functions (built-in functions or another existing user-defined ones), we need to declare the library containing it in the from.. import declaration.
Creating a Function
In Python a function is defined using the def keyword. You can pass data, known as parameters, into a function:
def name (parameter list):
Difference between Parameters and Arguments? Answer: The terms parameter and argument (args) can be used for the same thing: information that are passed into a function. From a function’s perspective, a parameter is the variable listed inside the parentheses in the function definition, and an argument is the value that is sent to the function when it is called.
As we knew that a script can take argv and function is essentially doing the same thing. When calling a function, we like to know if it needs parameters, or returns data as a result.
If it returns a result: Result=FunctionName([parameters]) (use a variable to store result)
def double(n): return 2*n x = double(3) print(x)
If there is no result: FunctionName([parameters])
def my_function(): print("It's a function") my_function()
If we call the function without argument, it uses the default value specified in the list). For example:
def FN(n, m=0): s = 0 for i in range(1, m + n, 1): s += i # the same as doing s = s + 1 but involves less typing. You can call this the "increment by" operator. return s print(FN(5)) # default parameter m = 0 if not specified. # 10 print(FN(5, 1)) # 15
Arbitrary Arguments *args
If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. By this way, the function will receive a tuple (unmodified list) of arguments, and can access the items accordingly. Arbitrary Arguments are often shortened to *args in Python documentations. It is similar to your argv parameter but for function.
Let”s try something:
def my_function(*args): for arg in args: print("My number is " + arg) my_function("One", "Two", "Three") # My number is One # My number is Two # My number is Three
Examples in “Learn Python 3 The Hard Way” book are also very good for practice.
I’ll take a break before diving into next part, or maybe come back to fix my mess of a blog, hah. You can see, while I’m writing this down, I’m also memorizing what I’ve learned.
See you later then.