Forum Archive

Loops

reefboy

How can I loop my commands over and over again

cook

@reefboy hello!

Using for or while
read more

If you mean something really different than that, please let us know!

reefboy

@cook yes but may I have an example please? I'm new to programming.

dgelessus

for loops are used to go over items stored in a list and repeat a piece of code for each item. For example, this code:

mylist = ["hello", "there", "how", "are", "you"]

for message in mylist:
    print message

creates a list named mylist that contains a few strings, then it goes over the list and prints out every item.

while loops are a little different. They work like an if block that repeats over and over until the condition is false. For example, this code:

import random

response = ""
while response != "exit":
    print "Your random number is:", random.randint(0, 10)
    response = raw_input()

prints out a new random number every time you press Enter, until you type exit.

(By the way, I'm assuming that you're using Python 2. If you're using Python 3, the code won't work like this.)