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.
# ___ i in range(_,_):
# print(i)
for i in range(1, 10):
print('value', i + 1)
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9
value 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?)
# ___ = __
# while num _= __:
# print(num)
# num += __
i = 2
while i <= 20:
print('value', i)
i += 2
value 2
value 4
value 6
value 8
value 10
value 12
value 14
value 16
value 18
value 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.
# 1. Right triangle (Don't uncomment this, they are instructions)
# ___ i in ___(1, 6):
# print("*" * ___)
for i in range(1,6):
print("*" * i)
# 2. Square (5x5) (Don't uncomment this, they are instructions)
#___ i in ___(5):
# print("*" * ___)
for i 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
# fruits = ["___", "___", "___"]
#for ___ in ___s:
# print(___)
fruits = ["pineapple", "grape", "strawberry"]
for fruit in fruits:
print(fruit)
pineapple
grape
strawberry
fruits = ["apple", "banana", "cherry"]
# ___ = 0
# while i < ___(fruits): # Hint: Loop continues as long as i is less than the length of the fruits list (The length is 3)
# print(fruits[___]) #` Print the fruit at index i
# ___ += 1
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
apple
banana
cherry