Let’s check out some exercises that will help you understand Python’s For Loops better.

Exercise 8-a

Write a for loop so that every item in the list is printed.


You can start a for loop and write a print statement inside it.

for i in …:
    ….

for i in lst:
print(i)

Exercise 8-b

Write a for loop which print "Hello!, " plus each name in the list. i.e.: "Hello!, Sam"


You can add strings together with “+” sign.: “Hello!, ” + “Sam” = “Hello!, Sam”

for i in lst:
print("Hello!, " + i)

Exercise 8-c

Write a for loop that iterates through a string and prints every letter.


When you iterate through a string it will go through the letters as strings have indexing too.

for i in str:
print(i)

Exercise 8-d

Type a code inside the for loop so that counter variable named c is increased by one each time loop iterates. Can you guess how many times it will add 1?.


c = c+1

c = 0
for i in str:
c = c+1 print(c)

 

Exercise 8-e

Using a for loop and .append() method append each item with a Dr. prefix to the lst.


“Dr. ” + i will create a string with “Dr. ” prefix and name.

.append() method can be used inside the for loop to append each element during the iteration.

for i in lst1:
lst2.append("Dr. " + i)

 

Exercise 8-f

Write a for loop which appends the square of each number to the new list.


i**2 will give square of i if it’s a number.

.append() method can be used inside the for loop to append each element during the iteration.

for i in lst1:
lst2.append(i**2)

 

Exercise 8-g

Write a for loop using an if statement, that appends each number to the new list if it's positive.


You can write an if statement inside the for loop.

if i >0 will do the trick.

for i in lst1:
if i > 0:
lst2.append(i)

 

Exercise 8-h

Using for loop and if statement, append the value minus 1000 for each key to the new list if the value is above 1000. i.e.: if the value is 1500, 500 should be added to the new list.


You can write an if statement inside the for loop.

If you iterate through a dictionary it will iterate through its keys. If i is a key in dict, dict[i] will give the value of key i.

for i in dict:
if dict[i] > 1000:
lst.append(dict[i]-1000)

 

Exercise 8-i

Write a for loop which appends the type of each element in the first list to the second list.


You can write an if statement inside the for loop.

If you iterate through a dictionary it will iterate through its keys. If i is a key in dict, dict[i] will give the value of key i.

for i in lst1:
lst2.append(type(i))