Python - loops


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

There are 2 types of loop available in Python.
1) for loop
2) while loop.


Let's see these loops 1-by-1 in the following examples.



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

 #for loop - examples

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)

 #while loop - examples

i = 1 #Initialization of loop counter while i<=10: #Conditonal test print 5*i #Printing factors of 5 i+=1 #Incrementing loop counter by 1 city = "Raipur" #Initializing variable named city while True: #Condition is always True city = raw_input("Enter city name (Enter => Bangalore to exit) : ") #Take i/p from keyboard if city=="Bangalore": #If we entered => Bangalore break #come out from the for loop else: #Otherwise print "You entered ",city #Print whatever we entered