Python Control Flow and Functions

Python Control Flow

Chapter 1

As with most imperative languages, there are three main categories of program control flow:

  • loops
  • branches
  • function calls

Generators and list comprehensions are advanced forms of program control flow, but they are not covered here.

Overview

Control flow in Python at a glance:

x = -6                              # Branching
if x > 0:                           # If
  print "Positive"
elif x == 0:                        # Else if AKA elseif
  print "Zero"
else:                               # Else
  print "Negative"
list1 = [100, 200, 300]
for i in list1: print i             # A for loop
for i in range(0, 5): print i       # A for loop from 0 to 4
for i in range(5, 0, -1): print i   # A for loop from 5 to 1
for i in range(0, 5, 2): print i    # A for loop from 0 to 4, step 2
list2 = [(1, 1), (2, 4), (3, 9)]
for x, xsq in list2: print x, xsq   # A for loop with a two-tuple as its iterator
l1 = [1, 2]; l2 = ['a', 'b']
for i1, i2 in zip(l1, l2): print i1, i2 # A for loop iterating two lists at once.
i = 5
while i > 0:                        # A while loop
  i -= 1
list1 = ["cat", "dog", "mouse"]
i = -1 # -1 if not found
for item in list1:
  i += 1
  if item=="dog":
    break                           # Break; also usable with while loop
print "Index of dog:",i             
for i in range(1,6):
  if i <= 4:
    continue                        # Continue; also usable with while loop
  print "Greater than 4:", i

Loops

In Python, there are two kinds of loops, ‘for’ loops and ‘while’ loops.

For loops

A for loop iterates over elements of a sequence (tuple or list). A variable is created to represent the object in the sequence. For example,

x = [100,200,300]
for i in x:
      print i

This will output

100
200
300

The for loop loops over each of the elements of a list or iterator, assigning the current element to the variable name given. In the example above, each of the elements in x is assigned to i.

A built-in function called range exists to make creating sequential lists such as the one above easier. The loop above is equivalent to:

l = range(100, 301,100)
for i in l:
    print i

The next example uses a negative step (the third argument for the built-in range function):

for i in range(5, 0, -1):
    print i

This will output

5
4
3
2
1

PPT Rundown of Python Programming CSC Functions and Control Flow - Chapter 1
CSC 201 200 220 207 204 221 205
CSC 201 200 220 207 204 221 205

Slide2 Slide3 Slide4 Slide5 Slide6 Slide7 Slide8 Slide9 Slide10 Slide11 Slide12 Slide13 Slide14 Slide15 Slide16 Slide17 Slide18 Slide19 Slide20 Slide21 Slide22 Slide23

Leave a Reply

Your email address will not be published.