Más contenido relacionado


Python for loop

  1. Python programming-for loops
  2. Quick revision  What is a list?  Difference between list and a variable  Can list store data of multiple types?  What is used to iterate over a list?  How to calculate length of list?  Are strings stored as lists in python?
  3. What is for loop???  The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects.  Iterating over a sequence is called traversal.
  4. 2 types of writing for loops 1.Getting each element of the sequence 2.Range (): By generating range of numbers and use these numbers as indexes to access sequences.
  5. Lets dive in type 1 of for loop
  6. Syntax of for loop
  7. Example
  8. Flowchart of for loop
  9. Iterating over string
  10. Example 2:For loop to calculate sum of elements in a list
  11. The break statement  Exit the loop when x is "banana", but this time the break comes before the print:
  12. Continue keyword  With the continue statement we can stop the current iteration of the loop, and continue with the next:
  13. Type 2 of for loop
  14. The range() function  We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).  We can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1 if not provided.  To force this function to output all the items, we can use the function list().
  15. Example
  16. Example to use range() in for loop
  17.  Syntax : range(start index, end index, step size)
  18. Sample problems  Print elements of a 1 dimensional list.  Print elements of 2 dimensional list.  Print even elements in a list.
  19. This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. It makes use of the works of Mateus Machado Luna.