3.8 Iterations Homework in Python
Complete the 4 hacks down below as homework:
- Uncomment the base code so that you can work on adding what you need to produce the correct outputs
- Make sure you connect too the python kernal to display an output
- Some questions require you to fill in the blanks. Beware of the ‘_’ that you need to delete and replace with numbers or words
- Make sure everything is re-indented properly before you run the code in the notebook
- Have fun!
Hack #1: Write a for loop that prints the numbers 1 through 10.
# Hack 1: Print numbers 1 through 10
for i in range(1, 11):
print(i)
1
2
3
4
5
6
7
8
9
10
Hack #2: Write a while loop that prints the even numbers between 2 and 20.
Hint 1 for Hack #2: You need to remember your work with math equations. (What goes before the equal sign?)
Hint 2 for Hack #2: You need to remember variables. (What is the initial condition?)
# Hack 2: Print even numbers between 2 and 20 using while loop
num = 2
while num <= 20:
print(num)
num += 2
2
4
6
8
10
12
14
16
18
20
Hack #3: Shapes! Make the following shapes using iteration loops with the symbol *
This might be a little challenging but think about how you need your outputs to look.
# Hack 3: Shapes using iteration
# 1. Right triangle (1 to 5 stars)
for i in range(1, 6):
print("*" * i)
print() # spacer
# 2. Square (5x5)
for _ in range(5):
print("*" * 5)
*
**
***
****
*****
*****
*****
*****
*****
*****
Hack #4: Fruits! Choose your favorate fruits and list them using iterations
Pick you 3 favorte fruits and list them in the blanks
# Hack 4 (part A): list fruits and print using a for-loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
# Hack 4 (part B): print fruits using a while-loop
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
apple
banana
cherry