Python Syntax
"""Sipping from your cup 'til it runneth over,
Holy Grail.
"""
Strings & Console Output
Escaping characters
'There\'s a snake in my boot!'
String methods
len()
lower()
upper()
str()
"Ryan".lower()
"Ryan".upper()
str(3.14)
len("roar")
print "The %s who %s %s!" % ("Knights", "say", "Ni")
Date and Time
Getting the Current Date and Time
from datetime import datetime
now = datetime.now()
print now
from datetime import datetime
now = datetime.now()
current_year = now.year
current_month = now.month
current_day = now.day
Pretty Time
from datetime import datetime
now = datetime.now()
print '%s:%s:%s' % (now.hour, now.minute, now.second)
Conditionals & Control Flow
And
- 1 < 2
and
2 < 3 is True
- 1 < 2
and
2 > 3 is False
This and That (or This, But Not That!)
Boolean operators aren’t just evaluated from left to right. Just like with arithmetic operators, there’s an order of operations for boolean operators:
not
is evaluated first
and
is evaluated next
or
is evaluated last
The Big If
if this_might_be_true():
print "This really is true."
elif that_might_be_true():
print "That is true."
else:
print "None of the above."
PygLatin
name = raw_input("What's your name?")
print name
Check Yourself… Some More
x = "J123"
x.isalpha()
Functions
Generic Imports
import math
print math.sqrt(25)
Function Imports
from module import function
print sqrt(25)
Universal Imports
from module import *
Here Be Dragons
import math
everything = dir(math)
print everything
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
None
On Beyond Strings
def biggest_number(*args):
print max(args)
return max(args)
biggest_number(-10, -5, 5, 10)
Built-in Functions
maximum = max(1, 1.1, -3.2)
print maximum
minimum = min(-100, 0, 44, 100.3)
print minimum
absolute = abs(-42)
print absolute
print type(4)
print type(4.2)
print type('hello')
Python Lists and Dictionaries
Introduction to Lists
Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name.
Late Arrivals & List Length
letters = ['a', 'b', 'c']
letters.append('d')
print len(letters)
print letters
List Slicing
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2]
middle = suitcase[2:4]
last = suitcase[4:6]
Slicing Lists and Strings
animals = "catdogfrog"
cat = animals[:3]
dog = animals[3:6]
frog = animals[6:]
Maintaining Order
animals = ["ant", "bat", "cat"]
print animals.index("bat")
animals.insert(1, "dog")
print animals
For One and All
my_list = [1,9,3,8,5,7]
for number in my_list:
print 2 * number
More with ‘for’
animals = ["cat", "ant", "bat"]
animals.sort()
for animal in animals:
print animal
This Next Part is Key
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print residents['Puffin']
print residents['Sloth']
print residents['Burmese Python']
New Entries
dict_name[new_key] = new_value
Changing Your Mind
del dict_name[key_name]
dict_name[key] = new_value
Remove a Few Things
beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")
print beatles
>> ["john","paul","george","ringo"]
It’s Dangerous to Go Alone! Take This
my_dict = {
"fish": ["c", "a", "r", "p"],
"cash": -4483,
"luck": "good"
}
print my_dict["fish"][0]
A Day at the Supermarket
This is KEY!
d = {"foo" : "bar"}
for key in d:
print d[key]
Student Becomes the Teacher
Lesson Number One
animal_sounds = {
"cat": ["meow", "purr"],
"dog": ["woof", "bark"],
"fox": [],
}
print animal_sounds["cat"]
Lists and Functions
Appending to a list
n = [1, 3, 5]
n.append(4)
Removing elements from lists
This exercise will expand on ways to remove items from a list. You actually have a few options. For a list called n
:
n.pop(index)
will remove the item at index
from the list and return it to you:n = [1, 3, 5]
n.pop(1)
print n
n.remove(item)
will remove the actual item
if it finds it:n.remove(1)
print n
del(n[1])
is like .pop
in that it will remove the item at the given index, but it won’t return it:del(n[1])
print n
Passing a range into a function
range(6)
range(1,6)
range(1,6,3)
- range(stop)
- range(start, stop)
- range(start, stop, step)
Iterating over a list in a function
Now that we’ve learned about range
, we have two ways of iterating through a list.
Method 1 : for item in list
for item in list:
print item
Method 2 : iterate through indexes
for i in range(len(list)):
print list[i]
Method 1 is useful to loop through the list, but it’s not possible to modify the list this way. Method 2 uses indexes to loop through the list, making it possible to also modify the list if needed. Since we aren’t modifying the list, feel free to use either one on this lesson!
Using two lists as two arguments in a function
a = [1, 2, 3]
b = [4, 5, 6]
print a + b
Battleship!
Make a List
print ["O"] * 5
Printing Pretty
letters = ['a', 'b', 'c', 'd']
print " ".join(letters)
print "---".join(letters)
Hide…
from random import randint
coin = randint(0, 1)
dice = randint(1, 6)
Loops
While / else
while condition:
pass
else:
pass
For your strings
word = "eggs!"
for c in word:
print c
Looping over a dictionary
d = {'x': 9, 'y': 10, 'z': 20}
for key in d:
if d[key] == 10
print "This dictionary has the value 10!"
Counting as you go
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index + 1, item
Multiple lists
It’s also common to need to iterate over two lists at once. This is where the built-in zip
function comes in handy.
zip
will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
zip
can handle three or more lists as well!
For / else
names = ['Hyde', 'Jack', 'Dorothy', 'Jane']
for name in names:
print name
else:
print "No more name"
Advanced Topics in Python
keys() and values()
my_dict = {
"Name" : "Junggu Lee",
"Company" : "LGE",
"Age" : 41
}
print my_dict.keys()
print my_dict.values()
print my_dict.items()
The ‘in’ Operator
for number in range(5):
print number,
d = { "name": "Eric", "age": 26 }
for key in d:
print key, d[key],
for letter in "Eric":
print letter,
List Comprehension Syntax
new_list = [x for x in range(1,6)]
doubles = [x*2 for x in range(1,6)]
doubles_by_3 = [x*2 for x in range(1,6) if (x*2)%3 == 0]
List Slicing Syntax
[start:end:stride]
Reversing a List
letters = ['A', 'B', 'C', 'D', 'E']
print letters[::-1]
Anonymous Functions
See the lambda
bit? Typing
lambda x: x % 3 == 0
Is the same as
def by_three(x):
return x % 3 == 0
Lambda Syntax
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
Try it!
cubes = [x**3 for x in range(1, 11)]
filter(lambda x: x % 3 == 0, cubes)
Binary Representaion
Lesson 10:The Base 2 Number System
print 0b1,
print 0b10,
The bin() Function
bin()
function
oct()
function
hex()
function
print bin(1)
print bin(2)
int()’s Second Parameter
int("42")
int("110", 2)
Introduction to Classes
Class Syntax
class NewClass(object):
pass
Let’s Not Get Too Selfish
class Animal(object):
def __init__(self, name):
self.name = name
Inheritance Syntax
class DerivedClass(BaseClass):
Override!
class Employee(object):
def __init__(self, name):
self.name = name
def greet(self, other):
print "Hello, %s" % other.name
class CEO(Employee):
def greet(self, other):
print "Get back to work, %s!" % other.name
ceo = CEO("Emily")
emp = Employee("Steve")
emp.greet(ceo)
ceo.greet(emp)
``` This Looks Like a Job For …
class Derived(Base):
def m(self):
return super(Derived, self).m()
See It to Believe It
my_list = [i**2 for i in range(1,11)]
f = open("output.txt", "w")
for item in my_list:
f.write(str(item) + "\n")
f.close()
Reading
my_file = open("output.txt", "r")
print my_file.read()
my_file.close()
Reading Between the Lines
my_file = open("text.txt", "r")
print my_file.readline()
print my_file.readline()
print my_file.readline()
my_file.close()
The ‘with’ and ‘as’ Keywords
Programming is all about getting the computer to do the work. Is there a way to get Python to automatically close our files for us?
Of course there is. This is Python.
You may not know this, but file objects contain a special pair of built-in methods: __enter__()
and __exit__()
. The details aren’t important, but what is important is that when a file object’s __exit__()
method is invoked, it automatically closes the file. How do we invoke this method? With with and as.
The syntax looks like this:
with open("file", "mode") as variable:
with open("text.txt", "w") as textfile:
textfile.write("Success!")
Case Closed?
f = open("bg.txt")
f.closed
f.close()
f.closed