Teachnique
      CourseRoadmaps
      Login

      OverviewCommentsUser InputNumbersBooleansHistoryHello World ProgramEnvironment SetupSyntaxVariablesData TypesType CastingUnicode SystemLiteralsOperators

      Control FlowBreak StatementContinue StatementPass StatementNested LoopsDecision MakingIf StatementIf-else StatementNested IF StatementMatch-Case StatementLoopsFor LoopsFor-else LoopsWhile Loops

      FunctionsBuilt-in FunctionsDefault ArgumentsKeyword ArgumentsKeyword-Only ArgumentsPositional ArgumentsPositional-Only ArgumentsArbitrary ArgumentsVariable ScopeFunction AnnotationsModules

      StringSlicing StringsModify StringsString ConcatenationString FormattingEscape CharactersString MethodsString Exercises

      ListsList ExercisesAccess List ItemsChange List ItemsAdd List ItemsRemove List ItemsLoop ListsList ComprehensionSort ListsCopy ListsJoin ListsList Methods

      TuplesAccess Tuple ItemsUpdate TuplesUnpack Tuple ItemsLoop TuplesJoin TuplesTuple MethodsTuple Exercises

      SetsAccess Set ItemsAdd Set ItemsRemove Set ItemsLoop SetsJoin SetsCopy SetsSet OperatorsSet MethodsSet Exercises

      DictionariesDictionary ExercisesAccess Dictionary ItemsChange Dictionary ItemsAdd Dictionary ItemsRemove Dictionary ItemsDictionary View ObjectsLoop DictionariesCopy DictionariesNested DictionariesDictionary Methods

      ArraysAccess Array ItemsAdd Array ItemsRemove Array ItemsLoop ArraysCopy ArraysReverse ArraysSort ArraysJoin ArraysArray MethodsArray Exercises

      File HandlingWrite to FileRead FilesRenaming and Deleting FilesDirectoriesFile Methods

      OOP ConceptsDynamic BindingDynamic TypingAbstractionObject and ClassesEncapsulationInterfacesPackagesInner ClassesAnonymous Class and ObjectsSingleton ClassWrapper ClassesEnumsReflectionClass AttributesClass MethodsStatic MethodsConstructorsAccess ModifiersInheritancePolymorphismMethod OverridingMethod Overloading

      Feedback

      Submit request if you have any questions.

      Course
      For Loops

      Python Tutorial

      This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.

      For Loops

      The for loop in Python has the ability to iterate over the items of any sequence, such as a list, tuple or a string.

      Syntax

      for iterating_var in sequence:
      statements(s)
      If a sequence contains an expression list, it is evaluated first. Then, the first item (at 0th index) in the sequence is assigned to the iterating variable iterating_var.
      Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
      The following flow diagram illustrates the working of for loop
      
      Since the loop is executed for each member element in a sequence, there is no need for explicit verification of Boolean expression controlling the loop (as in while loop).
      The sequence objects such as list, tuple or string are called iterables, as the for loop iterates through the collection. Any iterator object can be iterated by the for loop.
      The view objects returned by items(), keys() and values() methods of dictionary are also iterables, hence we can run a for loop with these methods.
      Python's built-in range() function returns an iterator object that streams a sequence of numbers. We can run a for loop with range as well.

      Using "for" with a String

      A string is a sequence of Unicode letters, each having a positional index. The following example compares each character and displays if it is not a vowel ('a', 'e', 'I', 'o' or 'u')

      Example

      zen = '''
      Beautiful is better than ugly.
      Explicit is better than implicit.
      Simple is better than complex.
      Complex is better than complicated.
      '''
      for char in zen:
      if char not in 'aeiou':
      print (char, end='')

      Output

      On executing, this code will produce the following output
      Btfl s bttr thn gly.
      Explct s bttr thn mplct.
      Smpl s bttr thn cmplx.
      Cmplx s bttr thn cmplctd.

      Using "for" with a Tuple

      Python's tuple object is also an indexed sequence, and hence we can traverse its items with a for loop.

      Example

      In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers.
      numbers = (34,54,67,21,78,97,45,44,80,19)
      total = 0
      for num in numbers:
      total+=num
      print ("Total =", total)

      Output

      On executing, this code will produce the following output
      Total = 539

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.
      

      Using "for" with a List

      Python's list object is also an indexed sequence, and hence we can traverse its items with a for loop.

      Example

      In the following example, the for loop traverses a list containing integers and prints only those which are divisible by 2.
      numbers = [34,54,67,21,78,97,45,44,80,19]
      total = 0
      for num in numbers:
      if num%2 == 0:
      print (num)

      Output

      On executing, this code will produce the following output
      34
      54
      78
      44
      80

      Using "for" with a Range Object

      Python's buil-in range() function returns a range object. Python's range object is an iterator which generates an integer with each iteration. The object contains integrrs from start to stop, separated by step parameter.

      Syntax

      The range() function has the following syntax
      range(start, stop, step)

      Parameters

      • Start − Starting value of the range. Optional. Default is 0
      • Stop − The range goes upto stop-1
      • Step − Integers in the range increment by the step value. Option, default is 1.

      Return Value

      The range() function returns a range object. It can be parsed to a list sequence.

      Example

      numbers = range(5)
      '''
      start is 0 by default,
      step is 1 by default,
      range generated from 0 to 4
      '''
      print (list(numbers))
      # step is 1 by default, range generated from 10 to 19
      numbers = range(10,20)
      print (list(numbers))
      # range generated from 1 to 10 increment by step of 2
      numbers = range(1, 10, 2)
      print (list(numbers))

      Output

      On executing, this code will produce the following output
      [0, 1, 2, 3, 4]
      [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
      [1, 3, 5, 7, 9]

      Example

      Once we obtain the range, we can use the for loop with it.
      for num in range(5):
      print (num, end=' ')
      print()
      for num in range(10,20):
      print (num, end=' ')
      print()
      for num in range(1, 10, 2):
      print (num, end=' ')

      Output

      On executing, this code will produce the following output
      0 1 2 3 4
      10 11 12 13 14 15 16 17 18 19
      1 3 5 7 9

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.
      

      Factorial of a Number

      Factorial is a product of all numbers from 1 to that number say n. It can also be defined as product of 1, 2, up to n.
      Factorial of a number n! = 1 * 2 * . . . . . * n
      We use the range() function to get the sequence of numbers from 1 to n-1 and perform cumumulative multplication to get the factorial value.
      fact=1
      N = 5
      for x in range(1, N+1):
      fact=fact*x
      print ("factorial of {} is {}".format(N, fact))

      Output

      On executing, this code will produce the following output
      factorial of 5 is 120

      

      In the above program, change the value of N to obtain factorial value of different numbers.

      Using "for" Loop with Sequence Index

      To iterate over a sequence, we can obtain the list of indices using the range() function
      Indices = range(len(sequence))
      We can then form a for loop as follows:
      numbers = [34,54,67,21,78]
      indices = range(len(numbers))
      for index in indices:
      print ("index:",index, "number:",numbers[index])
      On executing, this code will produce the following output
      index: 0 number: 34
      index: 1 number: 54
      index: 2 number: 67
      index: 3 number: 21
      index: 4 number: 78

      Using "for" with Dictionaries

      Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with different techniques.
      Running a simple for loop over the dictionary object traverses the keys used in it.
      numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
      for x in numbers:
      print (x)
      On executing, this code will produce the following output
      10
      20
      30
      40
      Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with the get() method. Take a look at the following example
      numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
      for x in numbers:
      print (x,":",numbers[x])
      It will produce the following output
      10 : Ten
      20 : Twenty
      30 : Thirty
      40 : Forty
      The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them.
      The dict_items object is a list of key-value tuples over which a for loop can be run as follows
      numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
      for x in numbers.items():
      print (x)
      It will produce the following output
      (10, 'Ten')
      (20, 'Twenty')
      (30, 'Thirty')
      (40, 'Forty')
      Here, "x" is the tuple element from the dict_items iterator. We can further unpack this tuple in two different variables. Check the following code
      numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
      for x,y in numbers.items():
      print (x,":", y)
      It will produce the following output
      10 : Ten
      20 : Twenty
      30 : Thirty
      40 : Forty
      Similarly, the collection of keys in dict_keys object can be iterated over. Take a look at the following example
      numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
      for x in numbers.keys():
      print (x, ":", numbers[x])
      It will produce the same output
      10 : Ten
      20 : Twenty
      30 : Thirty
      40 : Forty

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.