6 August 2014

For loop in Python loops through a sequence of statements and iterates the code with current variable.

Source code viewer
  1. # Loop through letters of string.
  2. for letter in 'String':
  3. print('Current letter:', letter)
  4.  
  5. # Loop through array.
  6. cars = ['mitsubishi', 'toyota', 'jeep']
  7. for car in cars:
  8. print('Current car:', car)
  9.  
  10. # Use else in for loop.
  11. for num in range(1, 20):
  12. for i in range(2, num):
  13. if num % i == 0:
  14. j = num / i
  15. print('%d equals %d * %d' % (num, i, j))
  16. break
  17. else:
  18. print(num, 'is a prime number')
  19.  
  20. # Early stop of loop.
  21. for x in range(3):
  22. if x == 1:
  23. break
Programming Language: Python