Back

Examples of loops using 'for' - Answers

Q1. Get the following code working in Python:

for x in [1, 2, 3, 4, 5]:
    print (x)

print('\n')
for x in [1, 2, 3, 4, 5]:
    print (x,end=' ')

print('\n')
for i in range(10):
    print (i, i*2, i*5)

print('\n')
for i in range(5,15):
    print (i, i**4)

print('\n')
for i in range(2,11,2):
    print (i)

print('\n')
monsters = ['evil pixie','mummy','orc','ghost','wizard']
print('The monsters are:\n') for monster in monsters:
    print(monster)

print('\n')
mixedList = ['life', 42, 'toad', True, 'fish', 3.14, False]
for item in mixedList:
    print("The current item is:",item)

Q2 - Q3. Document the program e.g.

'''
Use triple quotes
to add
a block of comments
'''

for x in [1, 2, 3, 4, 5]: #assign x to each number in the range
    print (x) #print x

print('\n') #move the curesor onto the next line
for x in [1, 2, 3, 4, 5]:
    print (x,end=' ') #force the cursor to stay on the same line

print('\n')
for i in range(10):
    print (i, i*2, i*5)

print('\n')
for i in range(5,15):
    print (i, i**4)

print('\n')
for i in range(2,11,2):
    print (i)

print('\n')
monsters = ['evil pixie','mummy','orc','ghost','wizard']
print('The monsters are:\n')
for monster in monsters:
    print(monster,end='\t') #stay on the same line and tab along.

print('\n')
mixedList = ['life', 42, 'toad', True, 'fish', 3.14, False]
for item in mixedList:
    print("The current item is:",item)

Q4. Write a new program to print out the numbers from 3 to 12 inclusive. Each number should be on a new line.

print('\n')
for i in range(12):
    print (i+1)

Q5. Write a new program to print out the numbers from 3 to 12 inclusive. Each number should be on the same line and separated by a space.

print('\n')
for i in range(3,13):
print (i,end=' ')

Q6. Print out the odd numbers between 30 and 40.

print('\n')
for i in range(31,40,2):
print (i,end=' ')

Q7. Write a list of 5 animals and print out the whole list with one instruction in Python.

animals=['lion', 'tiger','rhino','elephant','spider']
print(animals)

Q8. Print out the list of animals in the question above so they are all on the same line and separated by a space.

animals=['lion', 'tiger','rhino','elephant','spider']
for animal in animals:
print(animal,end=' ')

Q9. To seperate answers out using the print('\n') instruction.

print('\n')

Q10. Write a list of 5 fruits and print them out. They should each be on their own line and seperated by three line spaces.

fruits=['apple', 'grape','pear','banana','coconut']
for item in fruits:
print(item,end='\n\n\n\n')

Back