Reading about Python? Actually practice it.

Python Tutorial

chart flask

Python hosting: PythonAnywhere — host, run and code Python in the cloud. Free tier available.

A function is reusable code that can be called anywhere in your program. Functions improve readability of your code: it's easier for someone to understand code using functions instead of long lists of instructions.

On top of that, functions can be reused or modified which also improve testability and extensibility. Related Course:

Function definition

We use this syntax to define as function:

def function(parameters):
    instructions
    return value

The def keyword tells Python we have a piece of reusable code (A function). A program can have many functions.

Practical Example

We can call the function using function(parameters).

#!/usr/bin/python

def f(x): return(x*x) print(f(3))

Output:

9

The function has one parameter, x. The return value is the value the function returns. Not all functions have to return something.

Parameters

 We can pass multiple variables:

#!/usr/bin/python

def f(x,y): print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)) print('x * y = ' + str(x*y))

f(3,2)

Output:

You called f(x,y) with the value x = 3 and y = 2
x * y = 6
BackNext
Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser — no install needed.