Monday, September 24, 2012


All right i am back again with a little bit of a dose of python . Let us start looking  into loops and conditions from today. Since this is a vital and integral part of any programming language , this chapter will be split-ted in smaller sub chapters to provide the unassuming  user a better understanding of how loops , conditions and decisions work in python .


Some great guy correctly said what i mentioned above . Decisions are very important in life and they have at least the same importance in the programming world,  if not more .

The If  condition :

Let's see the syntax first :
In python , one can comment using : hash operator(#).

kNumeric = int(raw_input("Please enter an integer: ")) # kNumeric is the variable chosen here . It's upto you. 
if kNumeric < 0:
     kNumeric = 0
     print 'Negative changed to zero'
elif kNumeric == 0:
     print 'Zero'
elif kNumeric == 1:
     print 'Single'
    print 'More'

O/P : If i input here 42 , i get the output as More .

Here the key word elif stands for else if and is very widely used to get rid of repetitive indentation . However, the else part is optional here . This conditional flow is a kind of a substitute for switch and case statements found in other languages .

The  for loop :

The for statement in Python is different from what we may be used to in other languages. Rather than always giving the user the ability to define both the iteration step and halting condition, Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

For example in Java :

In Python :

# Let us find out length of individual items of a list
kList = ['item1', 'item2', 'item3']
for k in kList:
     print k,"-->", len(k)

O/P : 
item1 --> 5
item2 --> 5
item3 --> 5

Question : One question that is being repeatedly asked in interviews is : how can you modify a list on the fly and insert an element of the list in another location of the list depending on a condition given ?

Answer : The answer is slice copy . Let's see how to do it .

kList = ['item11', 'item2', 'item3333333']
for k in kList:
     print k,"-->", len(k)
for k in kList [:]: # in this way we can make a slice copy of the entire list on
                         # the fly
    if len(k) > 9: kList.insert(0, k)
print "Now the first element is ::",kList[0]

O/P :

item11 --> 6
item2 --> 5
item3333333 --> 11
Now the first element is :: item3333333

That's it for today friends . Next time we will have a look in the next sub chapter which will contain many other loops and conditions and constructs . Have a good day .

No comments:

Post a Comment