PYTHON PROGRAMMING
10
PART 4 – LOOPS
PROGRAMS
PROGRAM 1 – OUTPUT NUMBERS 1 TO 10
for x in range(1, 10):
print(x) # start at 1 # end BEFORE 10 |
PROGRAM 2A – ODD NUMBERS BETWEEN 1
& 10
for x in range(1, 10, 2): print(x) # start at 1 # end BEFORE 10 # increase by 2 |
PROGRAM 2B – EVEN NUMBERS BETWEEN 1
& 10
for x in range(2, 101, 2): print(x) # start at 2 (first even number) # end BEFORE 11 # increase by 2 |
TASK 1
a)
Use
a for loop to output all whole numbers between 17 and 25 inclusively.
b) Use a for loop to output all odd
numbers from 32 to 45 inclusively.
c)
Use
for loop to output all numbers from 10 down to 5 (backwards).
|
PROGRAM 3A – MULTIPLE MESSAGES
for coco in range(1, 5): print("I love school!") |
PROGRAM 3B – MULTIPLE LOOPS
for a in range(1, 4): print("Hey") for b in range(1, 4): print("Ho") for c in range(1, 4): print("Ha") |
TASK 2
Write a
program that asks the user for a message and then for a number of times to
display that message. It then prints
that message to screen the number of times specified.
SAMPLE IO
Enter a
message. Campeau is cool!
How many
times should I display this? 3
Campeau is
cool!
Campeau is
cool!
Campeau is
cool!
|
PROGRAM 4 – LARGER BLOCK
for x in range(1, 6): print("The number:", x) print("Its double:", x * 2) print("Its half:", x / 2) print("Its square:", x * x) print("=====") |
PROGRAM 5 – SENTENCE BUILDING GAME
turn = 1 sentence = "" for x in range (0,8): #8 passes print("==============") print("Sentence:", sentence) if turn == 1: print("Player 1, add a word") turn = 2 else: print("Player 2, add a word") turn = 1 word = input("Word to add:") sentence = sentence + " " + word print("***************") print(sentence)
|
PROGRAM 6 – INTRODUCING WHILE
num = 1 while num <= 10: print(num) num = num + 1 #try removing this line print("done") |
TASK 3
Use a while
loop to output all numbers from 10 to 20 on the screen.
|
PROGRAM 7 – LOOPING BASED ON USER
DECISIONS
keepGoing = True total = 0 while keepGoing == True: value = int(input("Enter a number (-1 escapes)")) if value == -1: keepGoing = False else: total = total + value print("The total is", total) |
TASK 4
Associate
each program description with a program below.
1)
This
program will output every fifth number from 0 to 100.
2)
This
program will output all odd numbers from 1 to 9 on the screen.
3)
This
program will output the numbers 1 to 4 on the screen.
4)
This
program will output numbers 1 to 5 on the screen.
5)
This
program will actually output nothing to screen because of a logical error.
6)
This
program will output the word coco on the screen four times.
|
a)
for coco in range(1, 5): print(coco)
|
b)
for x in range(1,10,2): print(x)
|
c)
for coco in range(1, 5): print("coco")
|
d)
a = 0 while a >= 100: print(a) a = a + 5
|
e)
z = 1 while z <= 5: print(z) z = z + 1
|
f)
a = 0 while a <= 100: print(a) a = a + 5
|
|