count = 0
while count < 5: print count count += 1
print print
count = 0 while count < 5: if count == 3: count +=1 continue print count count += 1
print print
count = 0 while True: if count == 8: break print “Count %s” % count count += 1
Python supports while … else structure. In this case the else block will execute when loop condition is evaluated to False - this means the while block never entered or the loop exited normally after the loop condition was evaluated to False. However python will not execute the else block if the loop exit is due to break.
count = 0 while count < 5: count += 1 print count else: print “Done!”
# output: 0,1,2,3 for i in range(4): print i
fridge = [“chicken”, “tomato”, “pasta”]
for item in fridge: print item
menu = { ‘fajita’: 23.5, ‘chicken alfredo’: 45, ‘fish platter’: 34 }
print “Welcome to our restaurant, check our menu:” for key in menu: print key + " " + str(menu[key])
Using for loop to loop through a list you wouldn’t know the index of the element you are accessing at each iteration. Enumarate function will help us with this, as it will supply a corresponding index to each element in the list that you pass it.
choices = [‘pasta’, ‘pizza’, ‘chicken alfredo’]
for item in choices: print “Item %s” % item
for index, item in enumerate(choices): print “Item %s: %s” % (index, item)
Zip function will create pairs of elemnts when passed two lists. It will stop at the end of shorter list.
list1 = [1,2,3,4,5] list2 = [4,6,2]
for el1, el2 in zip(list1, list2): print el1, el2
For loop may end with else. Else clause will be executed only when the for loop ends normally, without break.
list = [3,5,2,1]
for number in list: print number else: print ‘all numbers were printed’
employees = { “John”: “Manager”, “Bob”: “Assistant”, “Kate”: “Secretary” }
print employees.items()
print employees.keys()
print employees.values()
# output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] numbers = range(1,11) print numbers
numbers = [x for x in range(1,11)] print numbers
numbers = [x ** 2 for x in range(1,11)] print numbers
numbers = [x ** 2 for x in range(1, 11) if x % 2 == 0] print numbers
Syntax: [start:end:stride]
start - where the slicing starts (inclusive)
end - where the slicing ends (exclusive)
stride - space between items in the sliced list (i.e. step)
positive stride length - traverses the list from left to right
negative stride length - traverses the list from right to left
numbers = [1,3,4,5,6,7,8,9,10]
print numbers[3:]
print numbers[::2]
print numbers[3:6]
print numbers[3:9:2]
reversed = numbers[::-1] print reversed