Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

For loop vs. While loop

If you’re new, try these programming tricks below.

For loop: Try to use a for loop instead of a While loop, it’s much easier and you can use it even if you don’t have programmaticion IV.

Examples:
Instead of…

while True:
    enemies = hero.findEnemies()
    Index = 0
    while Index < len(enemies):
        enemy = enemies[Index]
        while enemy.health > 0:
            hero.attack(enemy)
        Index += 1

You can use…

while True:
    enemies = hero.findEnemies()
    for enemy in enemies:
        while enemy.health > 0:
            hero.attack(enemy)

Way easier, right?

Example #2 (more complex)
Instead of…

while True:
    Admin = hero.findByType("Admin")
    Moderator = hero.findByType("Moderator")
    Victims = Moderator.findVictims()
    MuteIndex = 0
    while MuteIndex < len(Victims):
        Victim = Victims[MuteIndex]
        while Victim.status != "Muted":
            Moderator.mute(Victim)
            if Victim.type == "Admin":
                Moderator.say("oops")
                Admin.ban(Moderator)
                break
        MuteIndex += 1
    pass

You can use…

while True:
    Admin = hero.findByType("Admin")
    Moderator = hero.findByType("Moderator")
    Victims = Moderator.findVictims()
    for Victim in Victims:
        while Victim.status != "Muted":
            Moderator.mute(Victim)
            if Victim.type == "Admin":
                Moderator.say("oops")
                Admin.ban(Moderator)
                break
    pass