Log in to save your progress.
<< Previous
Home
Next >>
OBS! Fönstret är för smalt för att använda pythonlabbet.se. Använd en enhet med tangentbord!

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

The while statement

In this section you will learn about

Simple loops with while

Another extremely important part of programming is being able to run the same code over and over again. A loop is code that is repeated until the condition for the loop to continue is no longer met. Most programming languages have the so-called while statement. In Python, we write while condition:, which repeats a piece of code while (English: while) the condition is true.

Example

A while statement is used to print the numbers one to ten.

x = 1
while x <= 10:
    print(x)
    x = x + 1

In the example above, x starts with the value one. On line 2, the program reaches the while loop and checks if x <= 10, which is true. Then we go down into the code block under while, print 1 and then x + 1 is assigned to x. We simply add one to x (increment x by 1) and x is now equal to two. Since we are in a while loop, we return to line 2 and check if x still less than or equal to 10. This is true (x = 2), so we run the code inside the while statement again. The program continues in this way until 10 is printed and the value 11 is stored in x. Then, when the program returns to line 2, it is no longer true that x <= 10, so we are done with the while statement.

It is understandable if you find x = x + 1 strange. In mathematics, it means something completely different. Therefore, it is important to remember here that = means assignment in Python (and most programming languages).

It is very important that you understand the example and the text above, so please read it again until you understand it. Also, don't be afraid to experiment with the code. Consider: what happens if we forget to increment x by one in each loop?

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?

2
1
2
1
0
2
0

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

Change the code

Change the while loop so that only odd numbers between 1 and 10 are printed (the number 1 should be included).

-- Output from your program will be here --

Did you figure out what happens if we forget to increment x by one for each loop or for each iteration as it is also called? Then the loop will never end and we will get an infinite loop. All programmers sooner or later encounter an infinite loop, it is a fairly common bug.

Example

An infinite loop. If you run the code below, it might eventually crash your browser. That's why there's a stop button! It's good to have when the program has accidentally entered an infinite loop. Can you change the code so that the program stops?

x = 0
while x < 5:
    print(x)

Example - ett enkelt "spel"

In this simple game, you have to guess what the result of a calculation is. If you guess smartly, you can find the answer quite quickly! Reminder: the % operator means remainder in division.

x = -1
facit = 124861357 % 107
while x != facit:
    x = int( input('What do you think 124861357 % 107 is?') )
    if x < facit:
        print('You guessed too low.')
    elif x > facit:
        print('You guessed too high.')
print('You guessed ' + str(x) + ' and that\'s correct!')

Here's how the program works in broad terms: The loop runs while the guess is not equal to the correct answer. Once inside the loop, x gets the value of the new guess. We test if x is greater than or less than the correct answer and print something appropriate. When the while loop finally sees that x != correct answer is false (we have a correct answer), the loop is terminated, and we print that the user guessed correctly.

break and continue

To break a loop during execution, break is used. To continue with the next iteration without running more code in the current iteration, continue is used. As we see in the example below, break can, for example, be used if you always want to run the code in the loop at least once.

Example

The code in the while loop always runs at least once. The condition to break the while statement is at the end instead. With while True: the loop runs until it is broken.

while True:
    answer = input('What year did Gustav Vasa become king?')
    if answer == '1523':
        break

Example

A program that prints the square root (which is the same as raising to the power of one half) of the input. If the user provides a negative number, continue is used to avoid calculating the square root of a negative number. Zero is used to exit.

while True:
    number = float( input('What do you want to take the square root of? (Exit with 0)') )
    if number < 0:
        continue
    elif number == 0:
        break
    print(number**0.5)

Example - is the number prime?

Now we will do a simple test of an integer to see if it is a prime number. A prime number is only divisible by itself and one. We simply test if there is any number that contradicts it. We do not need to test dividing numbers larger than the square root of the number. Why?

If you try some large random numbers, you will see that it is quite difficult to find a large prime number.

number = int( input('Which number do you want to test?') )
x = 2
is_prime = True
while x <= number ** 0.5:
    if number % x == 0:
        is_prime = False
        break
    x = x + 1
    
if is_prime:
    print(str(number) + ' is a prime number.')
else:
    print(str(number) + ' is NOT a prime number.')

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?

64,6
99,6
128,6
64,7
99,7
128,7

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

Multiplication Table

Your program should take an integer n as input from the user. Then the program should print the first n numbers in the multiplication table for 7.

Example input

5

Example output

7
14
21
28
35

-- Output from your program will be here --

Do you want to practice more with while? See the activity Loan with interest.

Status
You have finished all tasks in this section!
🎉