Repetition - Exercises (Pretty patterns!)
Here are more exercises to get you loopy about loops! Especially when they are nested loops.
Use loops to print out the patterns given below. You can have print()
output only ONE character each time. So print(2)
is allowed, but print("3 3 3 3 3")
and print("1 2 3")
is not.
You can use either for
loops or while
loops (or both!) This will get you thinking whether one is more suitable than the other.
Hint #1: print("whatever")
automatically adds a new line by default after printing. Add end=" "
as the last argument to replace the new line with a space instead.
So the following will print "1 1 1"
.
print(1, end=" ")
print(1, end=" ")
print(1, end=" ")
Hint #2: print()
without any arguments will give you a new line.
Hint #3: These exercises are incremental. You will only need to make small changes to your code for the previous pattern.
Many thanks to the following people for contributing to these exercises: Josiah Wang (based on materials by Ya-Ping Wong)
Pattern 1
1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
Pattern 2
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
Pattern 3
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
Pattern 4
1 *
1 2 *
1 2 3 *
1 2 3 4 *
1 2 3 4 5 *
1 2 3 4 5 6 *
1 2 3 4 5 6 7 *
1 2 3 4 5 6 7 8 *
1 2 3 4 5 6 7 8 9 *
Pattern 5
*
1 *
1 2 *
1 2 3 *
1 2 3 4 *
1 2 3 4 5 *
1 2 3 4 5 6 *
1 2 3 4 5 6 7 *
1 2 3 4 5 6 7 8 *
Pattern 6
*
. *
. . *
. . . *
. . . . *
. . . . . *
. . . . . . *
. . . . . . . *
. . . . . . . . *
Pattern 7
. . . . . . . . *
. . . . . . . *
. . . . . . *
. . . . . *
. . . . *
. . . *
. . *
. *
*
Pattern 8
. . . . *
. . . *
. . *
. *
*
. *
. . *
. . . *
. . . . *
Pattern 9
[Josiah: This one is a toughie! If you are stuck, get away from your code and think carefully!]
. . . . *
. . . * * *
. . * * * * *
. * * * * * * *
* * * * * * * * *
. * * * * * * *
. . * * * * *
. . . * * *
. . . . *
[If you are really stuck: In each row, what is the sum of the number of dots, the number of asterisks, and the number of blanks?]
Pattern 10
[Josiah: And this is probably one of the easiest once you solve the previous one!]
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Pattern 11
*
* . *
* . * . *
* . * . * . *
* . * . * . * . *
* . * . * . *
* . * . *
* . *
*
[Josiah’s hint #1: Flip flop flip flop]
[Josiah’s hint #2: You are allowed to use building blocks other than loops]
Hope you did not get too addicted. If that did not satisfy you enough, find more patterns to try online in your spare time. This page has 30 of them!
But for now – please move on to complete your lessons!!