Python - loops


Loops are useful for executing a statement or a group of statements again & again based the truth value(True/False) of the conditional expression.



  """
      created_at       : 04 Feb 2017.
      updated_at       : 08 Feb 2017.
      aim of script    : To understand the concept of for loops in python.
      coded by         : Rishikesh Agrawani.
      Python version   : 2.7.12
  """

  for i in range(1,11):       #Printing natural numbers from 1 to 10
      print i                 #Newline will be automatically appended 


  for j in range(5,21):       #Printing numbers from 5 to 20
      print j


  for k in range(2,21,2):     #Printing even numbers between 1 and 21, here 2 denotes the 
      print k                 #increment in each iteration


  for i in range(1,11):       #Printing tables for numbers in range [1,10]
      for j in range(1,11):   #Nested loop 
          print i*j,"\t",
      print "\n"              #For newline


  for c in "Rishikesh":       #Printing all characters of string 'Rishikesh' in 1 line, each separated by tab
      print c,"\t",           
  print ""                    #For newline


  for num in [1,3,7,9,11]:    #Printing all the numbers of list one by one in new lines
      print num


  cities  = ["Bangalore",'Raipur',"Dhamtari",'London']         #Defining list of cities 
  for city in cities:                                          #Printing all the cities 1 by 1
      print city

  #Defining a dictionary containing the details, an example to span a line into multiple lines
  details = {   "name"      : "Grimmy Heldon", \
                "age"       : 45, \
                'languages' : ['C','C++','Python','Golang','PHP','Core Java'],\
                'profession': "Backend Developer", \
                'is_active' : True,\
                'fav_num'   : 67+92j
            }
  print details    #Printing the dictionary

  for key,value in details.iteritems():     #Printing key & value individually using for loop
      print key,' => ',value

  digits = [0,1,2,3,4,5,6,7,8,9]            #List of single digit numbers
  digits_spell = ['Zero', 'One' ,'Two', "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] #List of spelling for single digit numbers
  for digit,digit_spell in zip(digits,digits_spell):        #Iterating 2 lists simultaneously
      print digit," : ",digit_spell         #0 : Zero, 1 : One, 2 : Two (and so on, in new line)

index2.html