In [1]:
## Python I: Beginner Tutorial
## University of Toronto Operations Research Group (UTORG) - Coding Month
## Teacher: Kyle E. C. Booth, Ph.D. Student - Industrial Engineering
## February 4, 2016

## Topics: Basic syntax, data types, control flows, functions and some test exercises. 

## 1) Standard Data Types
## Select variable names carefully (str, int, float, list, dict, etc. are bad choices)
## Cannot start a name with a number! "_" or letter only. Also, do not use a Python Keyword (if, else, elif etc.)

string = "Hello world!"
number = 10
list1 = ["this", "is", "a", "list", 1, 2, 3]
tuple1 = (1,2,3, "cat", "dog")
dictionary = {1:"this", 2:"is", 3:"a", 4:"dictionary"}
boolean = True

print string, "\n", number, "\n", list1, "\n", tuple1, "\n", dictionary, "\n", boolean
Hello world! 
10 
['this', 'is', 'a', 'list', 1, 2, 3] 
(1, 2, 3, 'cat', 'dog') 
{1: 'this', 2: 'is', 3: 'a', 4: 'dictionary'} 
True

In [2]:
## 2) Dynamically Typed
## Python doesn't need you to specify variable types, it guesses based on the value assignment.

variable = "Hello World!"
print type(variable)
variable = 2
print type(variable)
variable = {"dog":1,"cat":2}
print type(variable)
variable = [1,2]
print type(variable)
variable = 5.673439
print type(variable)

## The variable doesn't store the object itself, it stores a reference to the object
## Note: type() is a Python class with a method that returns the type of the variable argument

print variable
<type 'str'>
<type 'int'>
<type 'dict'>
<type 'list'>
<type 'float'>
5.673439

In [3]:
## 2.1) Getting Tricky
## What is the output of the following? Error?

x, y = 1, 2
x, y = y, x

print x, y
2 1

In [4]:
## 3) Strongly Typed

string = "1"
number = 2

## Which print statements produce an error? (if any)

#print string + number (the '#' character is used for commenting in Python)
#print "1" + 2
#print "1" + str(2)
print int(string) + number

## Note: str() is a class with a method that can convert data types to string. int() is a similar class.
3

In []:
## 4) Getting Help
## Want to learn more about a class? Try help()

help(int)
#help(str)
#help(dict) 

## and so on...
In [5]:
## 5) Boolean in Python
## These are all evaluated as false when used in a logical expression

boolean = False
integer = 0
emptyList = []
emptyTuple = ()
emptyDict = {}
In [6]:
## 6) Control Statements
## The if... else... command

if integer:
    print True
elif emptyList:
    print True
elif emptyTuple:
    print True
elif emptyDict:
    print True
else:
    print False
False

In [7]:
## 6.2) Control Statements Cont'd: if... else...
## Even and odd numbers

i = 10
even = "even"
odd = "odd"

if i % 2 == 0:
   print("%d is an %s number." % (i, even)) ## Note we can print variable inside string like so.
else:
   print("%d is an %s number." % (i, odd))
10 is an even number.

In [8]:
## 6.3) Control Statements Cont'd: Loops!
## For loops!

## for i in iterable_object: do something

list1 = ["dog", "cat", "fish", "potato"]

## Which of the following will print out all the list elements?

for item in list1:
    print item,             ## Note: The comma avoids a "\n" character being printed each time
print "\n"
    
for i in range(len(list1)): ## Note: len() is a class with a method that returns the length of an object
    print i,
print "\n"

for i in range(1,len(list1)):
    print list1[i],
print "\n"
    
for i in range(len(list1)):
    print list1[i],
dog cat fish potato 

0 1 2 3 

cat fish potato 

dog cat fish potato

In [9]:
## 6.4) Control Statements Cont'd: Loops
## While Loops

## while condition: do something
## What will the following program do?

counter = 0
while counter < 10:
    if counter % 2 == 0:
        pass            ## Note: pass is used when you don't want to do anything.
    else:
        print counter,
    counter += 1        ## Note: if you don't include this, you'll break Notebooks. So be careful!
1 3 5 7 9

In [10]:
## 6.5) Control Statements Cont'd: Loops
## While Loops

## How about the following program?

list1 = ["dog", "cat", "fish", "potato"]

counter = 0
while counter < len(list1):
    print list1[counter],
    counter += 1
dog cat fish potato

In []:
## 7) CODING ACTIVITY: DEVELOP A FIZZBUZZ PROGRAM
## (this problem is used to filter out 99% of programming job applicants)

## Time: 10 Minutes

## Write a program that prints the numbers from 1 to 100. 
## But for multiples of three print “Fizz” instead 
## of the number and for the multiples of five 
## print “Buzz”. For numbers which are multiples 
## of both three and five print “FizzBuzz"

## Be Pythonic: How short (lines) can you make your program? 
In [11]:
## FizzBuzz Program (14 lines) 
## Is this a good solution? What can we improve?

i = 1
while (i <= 100):
    if (i % 5) == 0 and (i % 3) == 0:
        print "FizzBuzz",
        i = i +1
    elif (i % 3) == 0:
        print "Fizz",
        i = i + 1
    elif (i % 5) == 0:
        print "Buzz", # Note: a comma after output will ensure all output on the same line.
        i = i +1
    else:
        print i,
        i = i + 1
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz

In [12]:
## FizzBuzz Program (7 lines) 
## That's better! Can we improve it more?

for i in range(1,101):
    words = ''
    if i % 3 == 0:
        words += 'Fizz'
    if i % 5 == 0:
        words += 'Buzz' ## Remember, we can concatenate data of the same type
    print words or i,    ## The print statement will always default to print the 'non-empty' first item
    
## Congratulations, you've got a hold on the basics!
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz

In [13]:
## 8) Functions
## A Brief introduction to functions in Python

## Functions in Python are easy. Let's define one that adds two numbers.

def addition(x, y):
    return x + y

print addition(2,3)
5

In []:
## 8) CODING ACTIVITY: FIZZBUZZ PROGRAM EXTENSION
## (this one would filter out 99.5% of applicants! {maybe})

## Time: 15 Minutes

## Using a function, write a program that runs FizzBuzz on 'n' ranging from 1 to 100. 
## How many times does Fizz, Buzz, and FizzBuzz occur?
In [14]:
## Solution (~15 lines of code) Could be improved with things we will learn in following slides!

def fizzBuzz(n):
    fizzCount = buzzCount = fizzBuzzCount = 0
    for i in range(1,n+1):
        if i % 5 == 0 and i % 3 == 0:
            fizzBuzzCount += 1
        elif i % 3 == 0:
            fizzCount += 1
        elif i % 5 == 0:
            buzzCount += 1 
    return fizzCount, buzzCount, fizzBuzzCount

a = b = c = 0
for i in range(1,101):
    result = fizzBuzz(i)
    a += result[0]
    b += result[1]
    c += result[2]
    
print ("Fizz: %d, Buzz: %d, FizzBuzz: %d" % (a, b, c))
Fizz: 1359, Buzz: 679, FizzBuzz: 291

In [15]:
## 9) Data Structure: Lists
## Lists are awesome.

growing = []

## Let's grow this list.
growing.append("1")
growing.append("2")
growing.append(["dog","cat"])

dictionary = {"ID":500} 
growing.append(dict(dictionary)) # Key to remember that only copies are made
dictionary["ID"] = 600

print growing
print growing[3], growing.pop() # There are a lot of neat list operators
print dictionary
['1', '2', ['dog', 'cat'], {'ID': 500}]
{'ID': 500} {'ID': 500}
{'ID': 600}

In [16]:
## 9) Data Structure: Lists Continued
## Commonly used list operators

## What is the expected output of the following? What do we need to change?

if "dog" in growing[2]:
    print True
else:
    print False
    
## And there are other operators such as max, min, sum, len etc.
True

In [17]:
## 9) Data Structure: Lists Continued
## Commonly used list operators

## Will these produce different outputs? Why or why not?

print growing

for item in growing:
    print item,
['1', '2', ['dog', 'cat']]
1 2 ['dog', 'cat']

In [19]:
## 9) Data Structure: Lists Continued
## List Slices & Comprehension

## The Slice - What will the output here be?
print growing[:1]
print growing[1:]
print growing[:1]+growing[1:]

## List Comprehension (for concisely creating lists) - What will the output be?

comprende = [ x for x in range(10) if x % 2 == 0 ]
comprende.remove(0)
comprende.append(10)
comprende.reverse()

print comprende
['1']
['2', ['dog', 'cat']]
['1', '2', ['dog', 'cat']]
[10, 8, 6, 4, 2]

In []:
## Check out the Python II: Intermediate Tutorial also given by me as part of Coding Month!