Learning Python: Functions


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.


No parameters

def message():
    print('Hello World!')

Single parameter

def message(msg):

Multiple parameters

def messages(msg1, msg2):

Setting a default value for a parameter

def message(msg = 'Hello'):

Multiple returns

def messages(msg1, msg2):
    return msg1, msg2

Explicity stating data type for a parameter

def message(msg: str):

Explicitly stating the return data type for a function

def message(msg: str) -> str: 

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
print(a_num) # 1

This blog post was originally published on my blog Communicode, where I write about different tech topics.

Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.