A3 - Nested Loops
These algorithms contain loops inside of loops. For each iteration of the outer loop, the inner loop completes all of it's iterations.
for i in range(4):
for j in range(5):
print("*", end="") # Prints * without a new line
print() # Prints a new line
This next example is almost identical to the one above, except for a small change in the second line:
for i in range(4):
for j in range(i):
print("*", end="") # Prints * without a new line
print() # Prints a new line
This algorithm counts the number of times the letter e appears in a list of words:
words = ['cup', 'pencil', 'tree', 'phone']
e_count = 0
for word in words:
for letter in word:
if letter == "e":
e_count += 1
print(f"The letter e appears {e_count} times")
Your Task
-
In a file called
a3a.py, modify the first example above (the grid pattern) so that:- The grid is larger
- Not everything is an asterisk. For example, you could choose a different character to print in all even rows, and if it's an even row and a column divisible by three, you choose yet a different character.
-
In a file called
a3b.py, modify the second example above (the triangle) to somehow modify the pattern. For example, by adding anif/elsestatement inside the inner loop, you could produce something like this:* ** *.* *..* *...* *....* *.....* *......* *.......* *........* *.........* *..........* *...........* **************You could also do something simpler. For instance, you could start by changing the second character in each row to something different.
If you're up for a real challenge, print an ASCII Christmas tree that is as high as the user asks it to be. Something like this:
-
In a file called
a3c.py, modify the third example above so that it analyzes something different about list of strings. For example, you could use theisupper()string method to determine the total number of capital letters.