Login

Back

Examples of loops using 'for'

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. Document any 5 lines in the program using the hash symbol to the right of each line.
Q3. Add a comment block at the beginning of the program.
Q4. Write a new program to print out the numbers from 3 to 12 inclusive. Each number should be on a new line.
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.
Q6. Print out the odd numbers between 30 and 40.
Q7. Write a list of 5 animals and print out the whole list with one instruction in Python.
Q8. Print out the list of animals in the question above so they are all on the same line and separated by a space.
Q9. Seperate answers out using the print('\n') instruction.
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.

Back