Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Explore the while Loop in Python | Loops in Python
Introduction to Python(ihor)
course content

Kursusindhold

Introduction to Python(ihor)

Introduction to Python(ihor)

1. First Acquaintance with Python
2. Variables and Types in Python
3. Conditional Statements in Python
4. Other Data Types in Python
5. Loops in Python
6. Functions in Python

book
Explore the while Loop in Python

Sometimes, you need your code to execute repeatedly as long as a specific condition is true. You can accomplish this using a while loop, which follows this structure:

python

To use a while loop effectively, start by initializing a counter variable and update it within the loop to avoid an infinite loop.

1234567
# Assign starting number (counter) i = 1 # While loop will print all the numbers to 10 while i < 10: print(i, end=' ') i = i + 1 # Increasing variable
copy

The print() function outputs each result on a new line by default. To separate outputs with a space, you can use end=' ' in the function.

The loop's logic includes the statement i = i + 1 to ensure the condition i < 10 eventually becomes False. Without it, the loop would run indefinitely.

question mark

What will happen if the line i = i + 1 is omitted from the while loop?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 5. Kapitel 1
Vi beklager, at noget gik galt. Hvad skete der?
some-alt