Learning Python: Functions
Introduction
Declaring functions in Python differs from languages such as JavaScript and PHP. When declaring a function in either of those languages we use the keyword function
(in JavaScipt's case, it is prior to the introduction of arrow functions in ES6). Python uses the keyword def
to declare a function.
Examples
No parameters
def message(): print('Hello World!')
Single parameter
def message(msg): print(msg)
Multiple parameters
def messages(msg1, msg2): print(msg1) print(msg2)
Setting a default value for a parameter
def message(msg = 'Hello'): print(msg)
Multiple returns
def messages(msg1, msg2): print(msg1) print(msg2) return msg1, msg2
Explicity stating data type for a parameter
def message(msg: str): print(msg)
Explicitly stating the return data type for a function
def message(msg: str) -> str: print(msg)
There are two important points that should be noted when dealing with parameters in functions: First, they are passed by reference. Second, all data types in Python are considered objects. Some of those data types are also immutable. That is, if you make a function call with a parameter with a specific value and modify the value of that parameter within the function, the value of that parameter that has been modified in the function will be the original value. An example of this case is as follows:
def some_function(num): num = 2 a_num = 1 some_function(a_num) print(a_num) # 1
This blog post was originally published on my blog Communicode, where I write about different tech topics.