Log in to save your progress.
<< Previous
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

for-statement

In this section you will learn

Iterate through list with for

To iterate through a list means that the list is gone through element by element. Actually, iterate means to repeat and the expression comes from the fact that we repeat the same thing for each element in the list.

The syntax is for variable in list: where variable is an optional variable name and list is a list. Indented below is the code to be executed for each element.

Example

A simple iteration of a list where each element is printed.

colors = ['Green', 'Red', 'Blue']
for color in colors:
    print(color)

Example

Here we show how we can test each element and, as in the example, count the number of elements greater than 10.

number_list = [44, -2, 19, 5, 30, 10]
count = 0
for number in number_list:
    if number > 10:
        count = count + 1

print(count)
    

In previous sections, we used while to iterate through a list. It works just as well, but in the case above where we need to go through the entire list, the syntax is smoother with for. We will soon see how for is easy to use when we want to repeat something a certain number of times.

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

Change the code

The code contains a number of errors that need to be corrected. Change the code so that it prints the names that come before E alphabetically.

-- Output from your program will be here --

Iterate through a string

In the same way that it is possible to iterate through a list, it is possible to iterate through a string, character by character, with for.

Example

Iterate through all characters in a string.

text = 'Iterate more'
for character in text:
    print(character)
  

With the help of enumerate() we can also get a variable that keeps track of which iteration we are on. This variable thus functions as a counter and it starts at 0 and counts up by one for each iteration. The example below shows for strings, but it works well on all types of objects that can be iterated over.

Example

Iteration with for and enumerate.

text = 'Iterate more'
for i, character in enumerate(text):
    print('Index ' + str(i) + ': ' + str(character))
  
@livewire('editor-modify-correct', [ 'editorId' => 'for-make-vocals', 'code' => $code, 'rows' => 10, 'showReset' => true, 'correctAnswer' => array("N/A"), 'correctInput' => $correctInput, 'correctOutput' => $correctOutput, 'title' => 'Create', 'text' => 'Write a program that takes a string from the user and then calculates how many vowels the string contains. Print that number.', 'tip_text' => 'Receive a string from the user with input. Then go through the string's characters with a for-loop and count up a variable for each character that is a vowel.' ])

Repetitions with range()

Sometimes we want to repeat the same code a fixed number of times and then the function range() is suitable. The simplest syntax is for variable in range(n): where variable is the counter's variable name and n is the number of repetitions.

Example

Repetition of the same code three times.

for i in range(3):
    print('Python!')
  

Example

In this example, we see how the counter changes for each iteration. Note that it starts at 0.

for i in range(3):
    print(i)
  

We can choose what range() should start at by using two arguments. The first argument is what the interval starts at and the second argument is how far the counter should go (not inclusive). For example, range(1, 10) means values from 1 to 9. Keep in mind that the value in the second argument is therefore not included in the interval.

Example

Counter with variable name i that starts at 1 and ends at 9.

for i in range(1, 10):
    print(i)
  

It is actually possible to use three arguments as well. The third argument stands for the step length. For example, range(1,10,2) means that we start at 1 and then take two steps for each iteration, in the second iteration the value is 3 and in the last the value is 9. It is also possible to use negative step lengths for the counter to go backwards.

Example

Example of using range() with three arguments.

for i in range(10, 51, 10):
    print(i)

for i in range(5, 0, -1):
    print(i)
  

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

What does the code do?

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?

1
2
1
2
1
4

Nested for-statements

It is common to use a for-statement inside another for-statement, so-called nested loops. It also works well with while.

Example

Two nested for-loops that print all combinations of two lists.

colors = ['blue', 'yellow', 'pink']
things = ['bag', 'car', 'house']

for color in colors:
    for thing in things:
        print(color + ' ' + thing)

Example

Two nested for-loops that print all 36 combinations of two dice rolls.

for t1 in range(1,7):
    for t2 in range(1,7):
        print(str(t1) + ', ' + str(t2))

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

Change the code

Change the code so that only the dice rolls that have a sum of 10 are printed.

-- Output from your program will be here --
Status
You have finished all tasks in this section!
🎉