FunctionsPython Functions

In Python, a function is defined using the keyword def. When you need to call a defined function, just use the function name followed by parenthesis (). Here is an example:

# -*- coding: UTF-8 -*-

# A function without parameters
def my_function_1():
  print("Hello world!")



Hello world!

Inside the parentheses, you can add parameters to functions. If there are multiple parameters, they should be separated by a comma.

# A function with string and number as the parameters
def my_function_2(sports, hours):
  print("I started to play " + sports + " about " + str(hours) + " hours ago\n")

my_function_2("basketball", 2)

# A function with a list as the parameter
def my_function_3(colors):
  print("My favorite colors:")
  for x in colors:

fav_colors = ["Green", "Red", "Blue"];


I started to play basketball about 2 hours ago

My favorite colors:

You can use a default parameter value. After you set a default value for the parameter, the function will use it when no value is passed to the parameter. This feature is very useful for avoiding runtime error caused by missing input value.

def my_function_4(language = "Python"):
  print("I like coding with " + language)



I like coding with Java
I like coding with C++
I like coding with Python
I like coding with Python


Python has a set of functions that are always available for use, such as print(). These functions are called built-in functions. In Python, the string module is widely used and it contains some deprecated legacy functions. In addition, there are four collection data types in Python programming language. They include List, Tuple, Set and Dictionary. These data types have their own functions. In the following pages, we will provide simple examples to help you learn how to use these functions.

© 2021, all rights reserved. Privacy Policy | Contact Us