> Tutorial
We are now going to look at another type of structure that is just as fundamental as conditions: loops!
A loop lets you repeat instructions several times. There are several types, bounded and unbounded, which we will cover in this part.
while loopThe unbounded while loop has a syntax similar to the if we saw earlier. It runs a block of instructions as long as a condition is met.
Here is an example:
# We declare a counter and initialize it to 0
counter = 0
while counter < 5: # As long as the counter is less than 5
counter += 1 # Increase the counter by 1
print("Counter is " + str(counter))
When it runs, this code displays the following in the logs: > Counter is 1 Counter is 2 Counter is 3 Counter is 4 Counter is 5
Python doesn't have a do while loop. To run a block at least once and then repeat it as long as a condition is met, we use while True with break (which exits the loop):
import random
while True:
x = random.random() # x is a random number between 0 and 1
if x >= 0.8: # we stop as soon as x reaches 0.8
break
print("x: " + str(x)) # displays a number between 0.8 and 1
for loopPython's for loop repeats a block for each value in a sequence. With range(n), you get the numbers from 0 to n - 1:
# We loop from i = 1 to i = 5
for i in range(1, 6):
print("The counter i is: " + str(i))
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 we can use it 4 times at most.
We use a for loop to run the me.useWeapon() method 4 times in a row:
for i in range(4):
me.useWeapon(enemy)
Here our variable i takes the values 0, 1, 2 and 3, so the loop does 4 iterations.
What is a loop for?
Running instructions several times Making your code more compact Speeding up part of your code Running 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
me = Fight.me
# We take the pistol if it isn't equipped
if me.weapon is None:
me.setWeapon(Weapon.pistol)
# We get the nearest enemy
enemy = Fight.getNearestEnemy()
# We greet our opponent
if Fight.turn == 1:
me.say("Hi " + enemy.name + "!")
# We move toward the enemy
me.moveToward(enemy)
# Boosts, shield and heal
me.useChip(Chip.motivation)
me.useChip(Chip.protein)
me.useChip(Chip.helmet)
# We heal ourselves if our life is below 75% of our max life.
if me.life < me.maxLife * 0.75:
me.useChip(Chip.bandage)
# We try to shoot at it 4 times!
for i in range(4):
me.useWeapon(enemy)
Impossible de charger les données du jeu.
Vérifiez votre connexion et réessayez.