Python basics
  • Tutorial
  • Exercices
  • About
  1. Fundamentals
  2. 8-Functions
  • Introduction
    • Python
  • Fundamentals
    • 0-Basic Syntax
    • 1-Variables
    • 2-Data types
    • 3-Numbers
    • 4-Strings
    • 5-Lists
    • 6-Booleans
    • 7-Loops
    • 8-Functions
    • 9-Dictionary
  • Advanced
    • 10-Numpy
    • 11-Matplotlib
    • 12-DataFrame
  • CLI
    • Exercices
    • Solutions
  • Git
    • Git introduction
    • Git branch
    • Git exercices
  • SQL
    • SQL Exercices
    • SQL Solutions

On this page

  • Creation
  • Call a function
  • Arguments
  • Return
  • Number of arguments
  • Default parameter
  • Keyword argument
  1. Fundamentals
  2. 8-Functions

8-Functions

Notebook

Link to the Google Colaboratory notebook: 8-Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creation

To define a function, one should use the def keyword:

def hello_world(): 
    print("Hello World !")

Call a function

To call a function, use the function named followed by parenthesis:

hello_world()
Hello World !

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

def square_function(x): 
    print(x**2)
square_function(2)
square_function(8)
square_function(9)
4
64
81

Return

To get access to the output of a function, it should have a return inside.

The return will stop the function and code after it will not be considered.

def square_function(x): 
    return x**2

y = 2
y_square = square_function(y)
print("2 times y**2", 2*y_square)
2 times y**2 8

Number of arguments

By default, a function must be called with the correct number of arguments.

Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

def sum_numbers(x, y):
    return x+y
z = sum_numbers(3,4)
# z = sum_numbers(3,4, 5) # it will not work
print(z)
7

Default parameter

You can specify a default value for a parameter within the definition of the function.

def show_country(country = "France"):
    print("My country is", country)

show_country()
show_country("Spain")
My country is France
My country is Spain

Keyword argument

You can specify the order of the argument if needed.

def my_function(a,b,c): 
    print(a+b+c) 

my_function(b=3, a=2, c=5)
my_function(a=2, b=3, c=5)
10
10
7-Loops
9-Dictionary
 

Copyright 2023, Clément Bernard