Hardware Reference
In-Depth Information
print (username + “, you are a “ +
ageAdjective + choice(adjectives) +
“ “ + choice(nouns))
Now, whenever you need a personalised insult you can just call
printInsult
, with your
victim's name and their age, and it will produce one on demand! So, to insult 10-year-old
Fred, you would write the following code line:
printInsult(“Fred”,10)
And Python would print something like this:
Fred, you are a young wet turnip
Call the
printInsult
function with the names and ages of some of your friends and family!
YOUR TURN!
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 loop: 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)
The 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: