Introduction to Python Workshop
From MtlPy Wiki
[edit] Interactive Introduction to Python Workshop
This workshop was given on January 25th, 2012 as part of a series of workshops for Winter 2012.
Author: Mathieu Perreault (mathieu.perreault[at]gmail.com) based on material by Alexandre Bourget and from the Python Essential Reference book.
[edit] Preparation
- Make sure everyone has a python interpreter.
- Windows: Install Python and use shortcut in Start menu or Start -> Run... -> cmd -> python
- Mac: Utilities -> Terminal -> python
- Linux: Terminal -> python
- Make sure everyone knows how to create a file and run it.
- Create file workshop.py and run it from the command line.
[edit] Interactivity
For every code snippet:
- People must write the code in the Python interpreter and run it.
- Instructor may pause briefly to make sure everyone has typed it.
- Instructor may ask: Who got an error, what is the error?
- Instructor may ask if someone can describe what is going on (makes them think about the code).
- Instructor should explain what is going on.
[edit] First steps with Python
print “Hello world” 6000 + 4523.50 + 134.12
Different types of values: String, Integer, Floating Point (double, float)
[edit] Small Program
year = 2000 while year < 2005: print year # Don’t forget the spaces for the indented block. year += 1
[edit] Things of note
- Variable assignment
- Indentation
- Conditional statement
- Printing a variable
- Incrementing the variable
[edit] Different Operators Mean Different Things
print “Hello Mr. %s” % (“Lazhar”) print 7 % 2
Different operators mean different things in different contexts (3 % signs here, only one is the modulo operator). String substitution similar to C and other languages.
[edit] Conditionals
a = 1 b = 2 if a < b: print “a is smaller than b” else: print “b is smaller than a”
[edit] Containment
monty = ‘Egg and spam’ has_spam = “spam” in monty print has_spam
if ‘spam’ in monty: # replace with has_spam print “I’ve got spam!” else: print “Where’s my spam!”
- No Difference between single quote and double quote (and triple quotes!) but be consistent.
- Introducing the “in” operator.
- Introducing the boolean. See that it comes from the “in” operator.
[edit] Reading files the Python way
f = open(“hello.py”) for line in f: print line
That can be brought back to
for line in open(‘hello.py’): print line,
Opening a file, reading every line. Pythonic way!
[edit] User input and Array slicing
>>> a = raw_input(“What’s your name: “) What’s your name: _______
What’s in a now?
a = “Hello World” # You can put your name here :) a[7] = “o” a[0:5] = “Hello” a[6:] = “World” a[3:8] = “lo Wo”
a is a sequence of characters, that we can access easily characters in specific positions.
[edit] Lists
names = [“Dave”, “Mark”, “Ann”, “Phil”] f.readlines() # Get the lines of a file. a = names[2] # Access different elements. names[0] = “Jeff” # Change some elements in the list. names.insert(2, “Thomas”) # Insert something in a list.
lastnames = [] # Create a new list. names.append(“Smith”) # Append a string to the end of the list.
[edit] Having fun with lists
[name.upper() for name in names] # List comprehension alist = [[1,2,3], [4,5,”Mark”], [7,8,9]] # Go and get the number 8 (a[2][1]) allnames = names + lastnames # concatenating lists
[edit] Tuples
stock = (‘GOOG’, 100, 600.00) # Defining a tuple company, shares, price = stock # Variable unpacking
- Although the tuple supports the same methods as a list, the contents are immutable.
- Tuple is more memory efficient if you know that you are not going to modify your sequence.
[edit] Sets
languages = set([“Python”, “Java”, “Ruby”]) stones = set([“Ruby”, “Amethyst”]) snakes = set([“Python”, “Cobra”])
>>> languages.union(stones) # languages | stones >>> languages.intersection(snakes) # languages & snakes >>> languages.difference(snakes) # languages - snakes
Different methods avaiable for set s: s.add(), s.remove(), s.clear()
[edit] Dictionaries
stock = {“name”: “GOOG”, “shares”: 100, “price” : 490.10}
company = stock[‘name’] value = stock[‘shares’] * shares[‘price’]
stock[‘price’] = 600.0
>>> stock_keys = list(stock) # List of keys [‘name’, ‘shares’, ‘price’]
[edit] Iteration and Looping
for n in [1,2,3,4,5,6]: # Can be replaced by range(1,7) print “2 to the %d power is %d” % (n, 2**n)
ws = “Python workshop” wslist = [‘Python’, ‘Workshop’]
for c in ws: # Iterate over a string will give you the characters
for el in wslist: # Iterate over the elements in the list (strings).
[edit] Functions
def reverse(s): return "".join([s[-i-1] for i in range(len(s))])
Talk about functions, and how you can define a function.