#!/usr/bin/env python # coding: utf-8 # All the IPython Notebooks in this lecture series are available at https://github.com/rajathkumarmp/Python-Lectures # #Control Flow Statements # ##If # if some_condition: # # algorithm # In[1]: x = 12 if x >10: print "Hello" # ##If-else # if some_condition: # # algorithm # # else: # # algorithm # In[2]: x = 12 if x > 10: print "hello" else: print "world" # ##if-elif # if some_condition: # # algorithm # # elif some_condition: # # algorithm # # else: # # algorithm # In[3]: x = 10 y = 12 if x > y: print "x>y" elif x < y: print "x y: print "x>y" elif x < y: print "x=7: break # ##Continue # This continues the rest of the loop. Sometimes when a condition is satisfied there are chances of the loop getting terminated. This can be avoided using continue statement. # In[10]: for i in range(10): if i>4: print "The end." continue elif i<7: print i # ##List Comprehensions # Python makes it simple to generate a required list with a single line of code using list comprehensions. For example If i need to generate multiples of say 27 I write the code using for loop as, # In[11]: res = [] for i in range(1,11): x = 27*i res.append(x) print res # Since you are generating another list altogether and that is what is required, List comprehensions is a more efficient way to solve this problem. # In[12]: [27*x for x in range(1,11)] # That's it!. Only remember to enclose it in square brackets # Understanding the code, The first bit of the code is always the algorithm and then leave a space and then write the necessary loop. But you might be wondering can nested loops be extended to list comprehensions? Yes you can. # In[13]: [27*x for x in range(1,20) if x<=10] # Let me add one more loop to make you understand better, # In[14]: [27*z for i in range(50) if i==27 for z in range(1,11)]