How can I loop my commands over and over again
Forum Archive
Loops
reefboy
Jun 22, 2016 - 23:49
cook
Jun 22, 2016 - 23:53
@reefboy hello!
Using for or while
If you mean something really different than that, please let us know!
reefboy
Jun 22, 2016 - 23:59
@cook yes but may I have an example please? I'm new to programming.
dgelessus
Jun 23, 2016 - 00:20
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.)