CodeStart / Python Course / Lesson 10
Lesson 10: For Loop Exercises
Now let's practice for loops with some practical exercises.
1st Exercise:
Print each character of an inputted word or text individually:
Reveal Answer
text = input("Write a word: ")
for i in range(len(text)):
print(text[i])Output
Write a word: I like food
I
l
i
k
e
f
o
o
d2nd Exercise:
The user inputs a single number. Draw a rectangle that has a width equal to half the input number of asterisks, and a height exactly equal to the input number of asterisks.
Example for n = 6: width = 3, height = 6. In case of an odd input, round the half width down to the nearest whole number.
Reveal Answer
height = int(input("What is the height? "))
width = height // 2
for i in range(height):
print("*" * width)Output
What is the height? 4
**
**
**
**3rd Exercise:
Write a program that reads a character string and then sequentially prints each letter from this string onto a new line, repeating the letter as many times as its position in the string (for example, for the string "Python").
Reveal Answer
text = "Python"
a = 1
for i in range(len(text)):
print(text[i] * a)
a+=1Output
P
yy
ttt
hhhh
ooooo
nnnnnnWant XP, levels and progress tracking? Play this lesson in the CodeStart game.
Play Lesson 10