Lab 5, Part 1: For loop practice
In your lab05
folder, create a new empty lab05.py
file where you will write
the functions below. Each of the functions contains a single for loop. There
are no nested loops on this page.
Task 1. box
Write a function called box
that takes a size and a character and
prints a box of the given size using the character. box
is a None function. Your box
function should have one loop (no need for a nested loop).
>>> box(2, '$') # Two rows, each with two dollar signs
$$
$$
>>> box(4, 'X') # Four rows, each with four Xs
XXXX
XXXX
XXXX
XXXX
>>> box(7, '@') # Seven rows, each with 7 @ symbols
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
@@@@@@@
Task 2. rect
Write a function called rect
that takes a width, height and character and
prints a rectangle of the given dimensions using the character. rect
is a None function that contains one loop.
>>> rect(2, 5, 'P') # Five rows, each with two Ps
PP
PP
PP
PP
PP
>>> rect(6, 1, '&') # One row with six &s
&&&&&&
>>> rect(7,3,'#') # Three rows, each with 7 #s
#######
#######
#######
Task 3. triangle
Write a function called triangle
that takes a height and character and
prints a triangle of the given height using the character. triangle
is a None function.
Hint: Try describing the content of a triangle to your partner in English,
this may shed light on how to code it in Python.
>>> triangle(5, 'V')
V
VV
VVV
VVVV
VVVVV
>>> triangle(1,'X')
X
>>> triangle(10, 'O')
O
OO
OOO
OOOO
OOOOO
OOOOOO
OOOOOOO
OOOOOOOO
OOOOOOOOO
OOOOOOOOOO
Task 4. findMultiplesOf
findMultiplesOf
is a None function that prints all the multiples of a
given factor between the given start and stop numbers, inclusive.
>>> findMultiplesOf(1,10,15)
There are 0 multiples of 15 between 1 and 10.
>>> findMultiplesOf(1,100,17)
17
34
51
68
85
There are 5 multiples of 17 between 1 and 100.
>>> findMultiplesOf(1000,2000,177)
1062
1239
1416
1593
1770
1947
There are 6 multiples of 177 between 1000 and 2000.
Task 5. addOdds
addOdds
is a fruitful function that returns the sum of all the odd numbers
up to the given number, inclusive.
>>> addOdds(1)
1
>>> addOdds(10)
25 # 1 + 3 + 5 + 7 + 9 = 25
>>> addOdds(37)
361
>>> addOdds(275)
19044
[Challenge problem] Task 6. makeN
Write a function called makeN
that draws a capital N made up of the given character
and of the given height. makeN
is a None function. Hint: makeN
builds from the triangle
function above.
>>> makeN(3, 'Y')
YY Y
Y Y Y
Y YY
>>> makeN(5,'E')
EE E
E E E
E E E
E E E
E EE
>>> makeN(7, 'L')
LL L
L L L
L L L
L L L
L L L
L L L
L LL