Log in to save your progress.
Home
Next >>
Note! The window is too narrow to use Pythonlab.dev. Use a device with a keyboard!

Reference

Click on a function to read more.
Basics part 1
Syntax
Short description
break
break interrupts code that is repeated
continue
continue interrupts a repetition and starts the next
elif
elif is a combination of else and if
else
else can be used last in an if-statement
float()
Converts to type float (decimal number)
if
if controls the code to do different things depending on a condition
input()
Receives input from the user
int()
Converts to type int (integer)
randint()
Generates a random integer
round()
Rounds a number
str()
Converts to type string
while
while is used to repeat code
Basics part 2
Syntax
Short description
abs
Absolute value
append
Adds an element to a list
def
Defines a function
for
for is used to repeat code
len
Returns the number of elements in an object
max
Returns the largest element
min
Returns the smallest element
pop
Removes an element from a list
return
Returns data from a function
sum
Sums the elements in an object

Functions

In this section you will learn to

What is a function?

A function is a block of code that performs a specific task. The function can, but does not have to, receive a number of parameters as input. The function can also, but does not have to, return a value that can be used where the function was called.

In programming, we want to avoid writing the same code in multiple places. With functions, you can write the code in one place and then use it over and over again. In many situations, it can also be good with functions even if they are not to be used in multiple places to make the code more readable. Functions also make the code easier to test so that it works correctly.

A good function is a function that has only one clearly defined task. This makes it easy to understand and easy to test. The function should not retrieve information from outside more than what is specified in the parameters.

Define and call a simple function

We start by defining a simple function that just prints a string. This is done with the reserved word def (short for define). We write def function_name(): to define a function that does not receive any parameters (also called arguments). We will later see how we use the space within the parentheses to make the function receive data. Indentation is then used to show which lines belong to the function.

Anywhere in the code after the function is defined, we can call the function like this function_name(). It is important to remember that the function must be defined first, otherwise Python will not recognize the name.

Example

A simple function that writes a line of text. The function is called on the last line.

def simple_function():
    print('hello from the function')
    
simple_function()

Login or create an account to save your progress and your code.

A simple function

Define a function named my_function that prints Hello! on one line. End by calling the function.

-- Output from your program will be here --

Parameter and return value

Most functions receive values, so-called parameters or arguments. These arguments are processed in the function, for example to calculate something. After that, it is common for the function to return some value. That a value is returned means that it is sent back to where the call was made. The reserved word return is for returning values. In the example below, we look at a function that receives a value (a radius) and returns a processed value (an area).

Example

The function below receives a radius of a circle and then calculates the area. Click test to see how the function can be used.

def circle_area(radius):
    area = 3.14 * radius * radius
    return area

The variables radius and area above only exist inside the function, therefore it would not be a problem to use these variable names outside the function without them affecting each other.

@livewire('editor-modify-correct', [ 'editorId' => 'functions_modify_circle', 'code' => $code, 'correctInput' => $correctInput, 'correctOutput' => $correctOutput, 'title' => 'Change the code', 'add_code' => '', 'text' => 'We want a program that takes a circle's circumference from the user and prints the radius of the circle. Right now, the function can only calculate the radius of a circle with circumference = 10 and it doesn't matter what the user enters. Change the program so that it does what it's supposed to.', 'tip_text' => 'You need to change the three places where it says "change here". The function should have one argument: circumference. When the function is called on line 7, the argument then needs to be entered inside the parenthesis.' ])

Multiple parameters

It is perfectly fine to define a function that takes multiple arguments. A function with three arguments is defined as follows:

def function_name(arg_1, arg_2, arg_3):

where arg_1, arg_2 and arg_3 are different parameters. They can be of different data types and in Python an argument can be of different types at different calls, for example float at one time and int at another. Note that the arguments are separated by commas.

Example

The function distance calculates the distance between two points, (x1, y1) and (x2, y2). The arguments to the function are x1, y1, x2 and y2. Click test to see how the function can be used.

def distance(x1, y1, x2, y2):
    distance_squared = (x1 - x2)**2 + (y1 - y2)**2 
    return distance_squared ** 0.5

Login or create an account to save your progress and your code.

Circumference of a rectangle

Write a function named rectangle_circumference that has two arguments, the width and height of a rectangle. Return the circumference of the rectangle. Note! When you click run, the program should not print anything because you should not call the function.

-- Output from your program will be here --

Unlike many other programming languages, it is possible to call a function with the arguments in a different order than in the definition. This can be done if the function is called with the arguments named. See the example below.

Example

Call a function with the arguments in a different order by naming them when calling.

def function(a, b):
  print('a = ' + str(a))
  print('b = ' + str(b))

function('one', 'two')
function(b = 'one', a = 'two')

Finally, even though it is possible to write programs without functions, they are still a fundamental part of programming. A large program without functions becomes difficult to manage. Functions are needed to make it readable and manageable.

Status
You have finished all tasks in this section!
🎉