[Python]: Loops

While Loops

count = 0

# output: 0,1,2,3,4
while count < 5:
    print count
    count += 1

# couple of empty lines
print
print 

count = 0
while count < 5:
    if count == 3:
        count +=1
        continue
    print count
    count += 1

# output: 0,1,2,4 - will skip the number 3

print
print

count = 0
while True:
    if count == 8:
        break
    print "Count %s" % count
    count += 1

Python supports whileelse 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!"

screen-shot-2016-11-12-at-11-38-19-am

For Loops

# output: 0,1,2,3
for i in range(4):
    print i

Looping through the list

fridge = ["chicken", "tomato", "pasta"]

# output: chicken, tomato, pasta
for item in fridge:
    print item

Looping through the dictionary

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])

screen-shot-2016-11-12-at-11-52-50-am

Enumerate function

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']

# basic for loop
for item in choices:
    print "Item %s" % item

# looping using enumerate function
for index, item in enumerate(choices):
    print "Item %s: %s" % (index, item)

screen-shot-2016-11-25-at-4-34-11-pm

Multiple lists

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]

# output: 1,4
# output: 2,6
# output: 3,2
for el1, el2 in zip(list1, list2):
    print el1, el2

For / else

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'

Dictionary functions: items(), keys(), values()

employees = {
    "John": "Manager",
    "Bob": "Assistant",
    "Kate": "Secretary"
}

# output: the list of key, value pairs
# output: [('Bob', 'Assistant'), ('John', 'Manager'), ('Kate', 'Secretary')]
print employees.items()

# output: ['Bob', 'John', 'Kate']
print employees.keys()

# output: ['Assistant', 'Manager', 'Secretary']
print employees.values()

Building Lists

# output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers = range(1,11)
print numbers

# output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers = [x for x in range(1,11)]
print numbers


# output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
numbers = [x ** 2 for x in range(1,11)]
print numbers

# output:[4, 16, 36, 64, 100]
numbers = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print numbers

Slicing Lists

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]

# output: [5, 6, 7, 8, 9, 10]
print numbers[3:]

# output: every second element
# output: [1, 4, 6, 8, 10]
print numbers[::2]

# output: [5, 6, 7]
print numbers[3:6]

# output: [5, 7, 9]
print numbers[3:9:2]

# output: [10, 9, 8, 7, 6, 5, 4, 3, 1]
reversed = numbers[::-1]
print reversed

 

Majd Arbash

...

Leave a Reply