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
Example
while True:
print('You are nice!')
answer = input('Should I stop saying that? Write yes in that case.')
if answer == 'yes':
break
Explanation
break interrupts code that is repeated. For example when while is used.
continue
continue interrupts a repetition and starts the next
Example
i = 0
while i < 100:
if i % 2 == 0: # continue with the next repetition if i is divisible by 2
continue
print(i,'is an odd number')
Explanation
continue interrupts the execution in the current repetition/iteration and continues with the next repetition. Used in while-statements and for-statements.
elif
elif is a combination of else and if
Example #1
temp = int(input('What is the temperature?'))
if temp > 20:
print('Warm and nice!')
elif temp > 0: #if temp <= 20 and temp > 0
print('Not very cold, but not so warm either.')
Example #2
number = int(input('Enter an integer'))
if number == 0:
print('You entered the number 0.')
elif number > 0:
print('You entered a positive number.')
else:
print('You entered a negative number.')
Explanation
elif is only used after if. It is a combination of else and if, meaning ELSE (if the above is false) and IF (if the new condition is true). The condition for elif is only tested if the condition for if is false.
Syntax
elif condition:
condition
Required. Something that is True or False.
else
else can be used last in an if-statement
Example
age = int(input('How old are you?'))
if age >= 18:
print('You are an adult!')
else:
print('You are not an adult.')
Explanation
else is only used at the end of a block that starts with if, and the code under else is only executed if the condition for if is false.
float()
Converts to type float (decimal number)
Example
float('0.01') #converts the string '0.01' to 0.01
float(10) #converts the integer 10 to 10.0
Explanation
The function float() converts the argument to type float (decimal number). Usually, the argument is a string or an integer.
Syntax
float(number)
Argument
number
A number in the form of a string or an integer.
if
if controls the code to do different things depending on a condition
Example #1
number = 10
if number == 10:
print('The number is equal to 10.') #this will be printed
Example #2
number = int(input('Enter an integer'))
if number == 0:
print('You entered the number 0.')
elif number > 0:
print('You entered a positive number.')
else:
print('You entered a negative number.')
Explanation
if is used to control what the program does depending on a condition. If the condition is true, the code in the if-block is executed. To control
what happens if the condition is not true, elif and else can be used.
Syntax
if condition:
condition
Required. Something that is True or False.
input()
Receives input from the user
Example
answer = input('What is your name?') #The user's answer is saved in the variable answer
Explanation
The function input() allows the user to enter input into the program. It is possible to include text that describes what should be entered.
Syntax
input(prompt)
Argument
prompt
An optional text the user sees.
int()
Converts to type int (integer)
Example
int(42) #converts the string '42' to 42
int(3.94) #converts the decimal number 3.94 to 3
Explanation
The function int() converts the argument to type int (integer). Usually, the argument is a string or a decimal number.
Syntax
int(number)
Argument
number
A number in the form of a string or a decimal number.
print()
Prints text or the content of a variable to the screen
Example #1
print('Hello World') #prints "Hello World"
print(1+1) #prints the number 2
print(x) #prints the content of variable x
Example #2
print('Hello World', end='') #prints "Hello World" without a new line
Example #3
print('Hello','to','you') #Prints "Hello to you"
print('Hello','to','you',sep=' | ',end='!') #prints "Hello | to | you!" without a new line at the end.
Explanation
The function print() prints a string to the screen. Automatically tries to convert what is to be printed to text.
Syntax
print(*object, sep=' ', end='\n')
Argument
*object
Required. One or more objects to be printed. Separate objects with commas.
sep
Character to separate the objects being printed. Default is space.
end
Character that ends the text being printed. Default is "\n" - which means new line.
randint()
Generates a random integer
Example
from random import randint
roll = randint(1,6) #a random number 1-6
Explanation
The function randint() generates a random integer between two integer values a and b such that a <= N <= b. randint is in the random module.
Syntax
randint(a,b)
Argument
a
The smallest random number that can be generated.
b
The largest random number that can be generated.
round()
Rounds a number
Example #1
round(7.89) #rounds to 8
round(1.23) #rounds to 1
Example #2
round(1.23456,2) #rounds 1.23
round(1.23456,4) #rounds to 1.2346
Explanation
The function round() rounds a decimal number. By default to an integer, it is possible to set round() to round to an arbitrary number of decimals.
Syntax
round(number, decimalplaces = 0)
Argument
number
Required. The number to be rounded.
decimalplaces
Number of decimals the number should be rounded to. Default is 0.
str()
Converts to type string
Example #1
str(2.71) #converts the decimal number 2.71 to the string '2.71'
str(10) #converts the integer 10 to '10'
Example #2
age = 15
print('You are ' + str(age) + ' years old.')
Explanation
The function str() converts the argument to a string. Often the argument is an integer or a decimal number. It can also be significantly more complex data types that can be converted to strings.
Syntax
str(object)
Argument
object
An object that can be converted to a string.
while
while is used to repeat code
Example
n = int(input('How many numbers do you want to print?'))
i = 1
while i <= n:
print(i)
i = i + 1
Explanation
while repeats the code in the block as long as the condition is true.
Syntax
while condition:
condition
Required. Something that is True or False. Must become false at some point for the while-block to be exited.
Basics part 2
Syntax
Short description
abs
Absolute value
Example
a = abs(5) # a = 5
b = abs(-5.2) # b = 5.2
Explanation
abs takes the absolute value of a number and thus always returns a positive number.
Syntax
abs(number)
Argument
number
Required. A valid number, integer, float, or complex number.
append
Adds an element to a list
Example #1
my_list = [1,2,3]
my_list.append(4) # now [1,2,3,4]
Example #2
my_list = ["one",2,3.0] # in Python, a list can consist of different types
my_list.append([1,2,3,4]) # now ["one",2,3.0,[1,2,3,4]]
Explanation
append adds an element to the end of a list. The list must already exist. It can be empty.
Syntax
my_list.append(element)
Argument
element
Required. The element to be added to the end of the list.
def defines a new function. A function can have arguments that you can use to pass data to the function.
The function can also return data using return.
for
for is used to repeat code
Example #1
for i in range(10): # i goes from 0 to 9
print(i) # runs ten times
Example #2
for character in 'Pythonlab.dev':
print(character)
Example #3
for element in [1,3,3,7]:
print(element)
Explanation
for repeats the code in the block for all elements in an object. The object is for example a range, list or string.
Syntax
for variable in object:
variable
Required. The variable changes content to the current element for each iteration.
object
Required. The object to iterate over. For example, a list.
Create lists easily with Python's list comprehensions
Use lists inside lists
Sublists or part of a string
In Python, it is easy to create a sublist of a list or a substring of a string. In English, it is called slicing.
The syntax used is variable[start:end] where start is the index where the part begins and end is where the part ends. The index end is not included.
Example
Some examples of how the syntax can be used to create a substring.
today = '2026-04-19'
year = today[0:4] # index 0 to 3
month = today[5:7] # index 5 and 6
day = today[8:10] # index 8 and 9
today = '2026-04-19'
year = today[0:4]
month = today[5:7]
day = today[8:10]
print(year, month, day)
Example
Sublists are created in the same way as substrings. Remember that the first element in the list has index 0.
# the list shows times in the Olympic final in Tokyo for men's 100 meters.
times = ['9.80', '9.84', '9.89', '9.93', '9.95', '9.95', 'DNF', 'DQ']
times_1_3 = times[0:3] # the three best times in a sublist
times_4_6 = times[3:6] # the times in places 4 to 6
# the list indicates times in the Olympic final in Tokyo for 100 meters men.
times = ['9.80', '9.84', '9.89', '9.93', '9.95', '9.95', 'DNF', 'DQ']
times_1_3 = times[0:3] # three best times in a sublist
times_4_6 = times[3:6] # times at place 4 to 6
print(times_1_3)
print(times_4_6)
Read the code below and try to figure out what the program prints. Run the program after you answer and see if you were correct.
-- Output from your program will be here --
Question: What will the program print?
nty
nty P
ty P
ty Py
More ways to slice
In the syntax variable[start:end] it is possible to omit start or end. Yes, it is actually possible to omit both to include everything.
If start is omitted, everything from the beginning up to end is included. If end is omitted, everything from start to the end is included.
Example
Examples of slicing where start index and end index are omitted.
s = 'Monty Python'
# Include characters from the beginning up to index 5
beginning = s[:5]
# Include characters from index 6 to the end
end = s[6:]
s = 'Monty Python'
# Take characters from the beginning up to index 5
beginning = s[:5]
# Take characters from index 6 to the end
end = s[6:]
print(beginning)
print(end)
Do you remember that negative indices can be used in lists and strings? Negative indices mean that we count the position from the end, -1 means the last element.
It is also possible to use negative indices when creating substrings and sublists.
Example
Create a sublist with negative indices.
s = 'Monty Python'
substring = s[1:-1] #do not include the first and last character
s = 'Monty Python'
substring = s[1:-1] #do not include the first and last character
print(substring)
Read the code below and try to figure out what the program prints. Run the program after you answer and see if you were correct.
-- Output from your program will be here --
Question: What will the program print?
Monty Pyth Mo
Monty Pyth M
Monty Pytho Mo
Monty Pytho M
List comprehensions
List comprehensions are used to create lists by writing only one line of code.
The English name for list comprehensions is list comprehension and is probably what you will encounter most.
List comprehensions combine the syntax for creating a list [] with the syntax for a for-loop.
Later we will see that it is possible to use an if-statement as well, but we start with simpler examples.
Example
Creates a list with five identical elements.
my_list = [0 for i in range(5)]
my_list = [0 for i in range(5)]
print(my_list)
In the example above, the counter i was never used. We see what happens if we use i instead of zero.
Example
More examples of list comprehensions.
list_1 = [i for i in range(5)] # [0,1,2,3,4]
list_2 = [i*5 for i in range(5)] # [0,5,10,15,20]
list_1 = [i for i in range(5)] # [0,1,2,3,4]
list_2 = [i*5 for i in range(5)] # [0,5,10,15,20]
print(list_1)
print(list_2)
Now we will see how we can use an if-statement inside a list comprehension. This can, for example, be used to filter out elements in a list.
Example
List comprehension with if-statement.
names = ['Maria', 'Anna', 'Margareta', 'Elisabeth', 'Eva', 'Kristina']
#create a new list with names ending in a
ends_with_a = [n for n in names if n[-1] == 'a']
#list with names that are at most five characters long
short_names = [n for n in names if len(n) <= 5]
names = ['Maria', 'Anna', 'Margareta', 'Elisabeth', 'Eva', 'Kristina']
#create a new list with names ending in a
ends_with_a = [n for n in names if n[-1] == 'a']
#list with names that are at most five characters long
short_names = [n for n in names if len(n) <= 5]
print(ends_with_a)
print(short_names)
List comprehensions can be a bit tricky to understand, especially if you know another programming language that doesn't have them.
If you have a list comprehension [x for x in list if x < 10] then you can think of it like this:
Insert element x into the list for all elements x in list where x is less than 10.
So we create a new list from list with all elements less than 10.
List comprehensions are not necessary to know because it is always possible to do the same thing with a regular for-loop or while-loop.
But for experienced Python programmers who often work with lists, it is a nice feature.
Change the code so that the list comprehension filters out all negative numbers.
-- Output from your program will be here --
A list of lists
Imagine a regular list and then imagine that each element in that list is a new list. It is a list of lists or 2D list.
A 2D list is especially suitable for models of something in two dimensions. A common image is a good example.
To iterate through all the elements in a 2D list, a nested for-loop is usually used.
Example
Create a 2D list with two rows and three columns. The two elements in the list represent rows. These elements are in turn also lists.
list_2d = [ [1, 2, 3], [4, 5, 6] ]
list_2d = [ [1, 2, 3], [4, 5, 6] ]
print(list_2d)
#or to see the 2d structure better:
print('Another way to print:')
print(list_2d[0], list_2d[1], sep='\n')
Example
The variable image is a 2D list that represents a simple image.
Each pixel is either # or a space. The image has seven pixels in width and six pixels in height.
The 2D list thus has six rows and each row contains seven columns.
We print the image with a nested for-loop.
A real image works in the same way. However, the elements are usually a number that describes the color of that pixel.
image = [
[' ', '#', '#', ' ', '#', '#', ' '],
['#', ' ', ' ', '#', ' ', ' ', '#'],
['#', ' ', ' ', ' ', ' ', ' ', '#'],
[' ', '#', ' ', ' ', ' ', '#', ' '],
[' ', ' ', '#', ' ', '#', ' ', ' '],
[' ', ' ', ' ', '#', ' ', ' ', ' ']
]
for row in image: #
for column in row:
print(column, end='')
print() #new line in the output for each printed line in the image
image = [
[' ', '#', '#', ' ', '#', '#', ' '],
['#', ' ', ' ', '#', ' ', ' ', '#'],
['#', ' ', ' ', ' ', ' ', ' ', '#'],
[' ', '#', ' ', ' ', ' ', '#', ' '],
[' ', ' ', '#', ' ', '#', ' ', ' '],
[' ', ' ', ' ', '#', ' ', ' ', ' ']
]
for row in image: #
for column in row:
print(column, end='')
print() #new line in the output for each printed line in the image