> Tutorial
We are now going to look at another type of structure that is just as fundamental as conditions: loops!
A loop allows instructions to be repeated several times. There are several types, bounded and unbounded, that we will see in this part.
while loopThe unbounded while loop has a syntax similar to the if seen previously. It allows an instruction block to be executed as long as a condition is met.
Here is an example:
This code will display in the logs when executed: > Counter is 1 Counter is 2 Counter is 3 Counter is 4 Counter is 5
Python does not have a do while loop. To execute a block at least once then repeat as long as a condition is met, we use while True with break (which exits the loop):
for loopPython's for loop repeats a block for each value of a sequence. With range(n), we get the numbers from 0 to n - 1:
range(1, 6) produces the values 1, 2, 3, 4, 5 (the end bound is excluded).
Our leek has between 10 and 13 TP (thanks to Motivation) and the Pistol only costs 3 TP, so it can be used 4 times at most.
We use a for loop to execute the me.useWeapon() method 4 times in a row:
Here our variable i will have the values 0, 1, 2 and 3 so the loop will do 4 iterations.
What is a loop for?
Executing statements multiple times Condense your code Speed up part of your code Execute instructions in parallel
Which code(s) are correct?
x = 0 while x < 10: x += 2 x = 0 while x < 10 x += 2 x = 0 for i < 10: x += 2 x = 0 for i in range(5): x += 2
Impossible de charger les données du jeu.
Vérifiez votre connexion et réessayez.