Hardware Reference
In-Depth Information
Call the printInsult function with the names and ages of some of your friends and
family!
Creating Loops
Loops are great when there's repetition in a task. To try this out, you're going to create a
program that loops around a few times, each one producing another insult. You'll look at two
variations of loops: a for loop and while loop. Both have a test that determines if the code
in the loop body should be run again, or if the program should skip the loop body and con-
tinue. A for loop is typically used as a counting loop, where code needs to be run for a par-
ticular number of times - for example, for six times. A while loop tends to be used while a
condition is true - for example, while a user wants to continue running the program.
for Loop
Type the following code to loop for each item in the adjectives list and print it out:
adjectives = [“wet”, “big”]
for item in adjectives:
print (item)
he indented code, print (item) , is the body of the loop that is repeated on each iteration
(loop). for item in adjectives : sets up the loop and tells Python to loop for each item
in the adjectives variable. On each iteration, the next value from the list is placed in the
item variable.
So, to print “hello world” three times you write this:
for count in [1, 2, 3]:
print (“loop number “,count)
print (“hello world”)
You can use commas to separate multiple items for printing.
You can use range instead of typing every number in a list. Type
list(range (10))
 
Search WWH ::




Custom Search