Monday, March 26, 2012

Looping Statement: For Loop with Dictionary and While

Hello everyone in this post, we will discuss how to loop through a Dictionary.

I guess we are clear about what dictionary is, if not please look at the blog archive and go through the Dictionary Post.

Lets make a Quick dictionary

>>> things = {'Socks':50, 'Shirt':550, 'Trouser':995, 'Shoes':780 }
>>> things
{'Trouser': 995, 'Shirt': 550, 'Socks': 50, 'Shoes': 780}

Now lets say we want the Dictionary to display the keys with its respective key_values

This is where the For Loop comes handy

The For Loop loops a variable with every elements in a list or dictionary.

>>> for purchase in things:
             print "Price of "+purchase+" is Rs.",things[purchase]


Price of Trouser is Rs. 995
Price of Shirt is Rs. 550
Price of Socks is Rs. 50
Price of Shoes is Rs. 780
>>>

Here purchase is a variable that is looped with the dictionary. On executing, the variable purchase is assigned the key Socks, and things[purchase] which at the first loop is, things[Trouser] returns the key_value 995. and on the second loop, things[purchase] means, things[Shirt] and it returns its key value 550, and it goes on, until all the keys in the dictionary has been looped.


Now, here is another Loop with While, which will be very helpful in future, lets first check the code, then will explain:

>>> password = "welcome"
>>> while True:
              pass1 = raw_input("Enter the Password: ")
              if pass1 == password:
                    print "Password Accepted"
                    break

Enter the Password: garry
Enter the Password: tom
Enter the Password: letmein
Enter the Password: welcome
Password Accepted
>>>

Explanation: while True:(Alternate while 1:) means asking the python to keep looping the statements under the while, until the loop is broken by some event.

So we assigned the password "welcome" to variable password, then we asked the python to keep looping the statement under while. Next, allows user to type a password and the user input is assigned to variable pass1, then the value of pass1 is matched with the value of password, and according to the condition, if values of both the variable match, then print "Password Accepted", and break is the keyword, which breaks the whole Loop and exits out of the loop.

Okay, So I Hope this has been informative, Practice them, as it will be used many times with the future posts.

Thank You and Don't forget to check my next post.

0 comments:

Post a Comment