Python for Humans

A language that you write like language

Ryan Brown: Sysadmin, Python Developer

It's all in STDlib

Introductions

Hi, I'm Ryan. I make things for computers, and I use Vim for making most of those. (Even these slides)

If you have questions, fire away.

What is Python?

  • Whitespace-based programming language
  • With a lot of community support
  • And hundreds of modules for every task you can think of
  • Python does its best to stay out of your way so you can get to programming
  • Learn Python -> Write lots of programs -> Code better -> Make awesome stuff (-> Profit?)

Agenda

Getting Started

Unix-y things: python

Windows: There's an icon or something

Mac: See Unix

What's an Interpreter?

Short answer: Don't worry, just start writing code

Long answer: It's a program that you can type Python into and it executes it. It's nice for prototyping because you don't have to do the edit->save->run->repeat dance that you would otherwise.

Try this:

print "hello world"

More About Interpreters

Python is a fully object-oriented language which means you can have objects with their own attributes, functions, etc. It is also interpreted, which means you must declare all your objects first (or import them) and use them afterwards.

Java Syntax: Compare

Java uses braces and semicolons to divide statements, whitespace is only really necessary for style. So this code:

public int myfunction(x, y) {
  if(x > y) {
    return x - y;
  }
  return x+y;
}
System.out.print(myfunction(4, 2));
System.out.print(myfunction(2, 3));

Produces the same results as this code:

public int myfunction(x,y){if(x>y){return x-y;}return x+y;}
System.out.print(myfunction(4,2)); System.out.print(myfunction(2, 3));

Python Uses Whitespace

With this block of Python:

def myfunction(x, y):
        if x > y:
                return x - y
        return x + y
print myfunction(4, 2)
print myfunction(2, 3)

Instead of semicolons Python requires new lines to recognize separate logical statements, and indentation levels separate blocks of code instead of braces.

Note: You need a colon to start any indented blocks (loops, function definitions, etc)

Typing

Python is loosely typed, which means you just do this:

x = 5
#instead of this:
int x = 5

Python does its best to guess what value you're trying to store (is it an int or a string? Double? List? Tuple? Dict?) and store it as that type. If you aren't sure what type something is, just do this:

x = 8
y = 'hello'
print type(x)
print type(y)

The type keyword tells you what type Python thinks an object is. If you don't like it, you can force Python to try and make it into a different type.

x = 892948
print x, type(x) # x is an int
y = str(x) # Force x to be cast as a string, save it to y
print y, type(y) # Show that y is a string

Basic Math

Math Operations:

9*3

Storing results:

x = 9 * 3
print x

String Manipulation

x = "hello world"

String manipulation:

print ('hello' + ' ' + 'there')
print "in ur %s %sing ur %s" % ('base', 'kill', 'dudes')

Lists

x = ['a', 2, 'seventy-three', 9]

A list is a series of mutable values. These values can be any type (including other lists)

print x[2]

for y in x:
        print y

x.append('lastthing')

print x

Tuples

A tuple is a series of immutable values, which can be any type.

x = ('my', 4, 'items', 98475, [4 , 'this', 8])

If you put a list inside a tuple, the contents of the list is mutable.

print x

print x[3]

x[0] = 'newvalue'
  TypeError: 'tuple' object does not support item assignment

Dictionaries

A dictionary is a collection of keys/values

x = {'language': 'Python', 'delimiter': 'whitespace'}
print x['language'], x['delimiter']
# You can also add values to dictionaries like this:
x['extension'] = '.py'
# To see all the keys, just:
x.keys()
# Or for everything:
x.items()

What if/elif/else?

Often, you'll need to check that a certain condition is fulfilled. The simplest way to do this is with the if statement.

mybool = True
myint = 2
mynothing = None
if mybool:
        print "mybool is true"
if myint == 1:
        print myint
elif myint == 2:
        print myint
else:
        print myint
if not mynothing:
        print "There's nothing in mynothing"

Looping

If you need to repeat a task a bunch of times, you want a loop.

while True:
        #This code will execute again and again, pretty much forever
        print "hello forever"

Lists, Tuples, and Dicts are all "iterable" which means that Python automatically understands how to loop through them.

numbers = [1, 3, 5, 7, 9]
runningtotal = 0
#Let's figure out the sum of all those numbers
for num in numbers:
        runningtotal = runningtotal + num
print runningtotal

Which makes it easy to perform an operation on a group of items without dealing with length/counters/other crap.

Interactive: Let's Write Something

Alright, let's try writing a simple program.

  1. Store a simple list of items along with their price and print the list
  2. Store items, an ID for the items, and their price. Print the list

Sample data:

IDNamePrice
1Widget5.00
3Gizmo1.75
5Gadget2.50
7POS0.99

Sample Code

Here's the simple inventory program

names = ['Widget', 'Gizmo', 'Gadget', 'POS']
prices = [5.00, 1.75, 2.50, 0.99]
counter = 0
while counter < 4:
        print "Item: %s\t\tPrice: %s" % (names[counter], prices[counter])
        counter = counter + 1

And here's the more complex version.

inventory = [{'id': 1, 'name': 'Widget', 'price': 5.00 },
{'id': 3, 'name': 'Gizmo', 'price': 1.75 },
{'id': 5, 'name': 'Gadget', 'price': 2.50 },
{'id': 7, 'name': 'POS', 'price': 0.99 }]
for item in inventory:
        print "ID: %s\tName: %s\tPrice: %s" % (item['id'], item['name'], item['price'])

Loops Continued

What if you need to get out of a loop if a certain condition is met? Easy, the break statement has your back.

What about if you want to skip an iteration for some condition? Look no further than continue.

Let's say you don't want to add any numbers that are divisible by 3 and have a sum no higher than 25.

numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
runningtotal = 0
for num in numbers:
        #if we go over 25, get out of the loop
        if runningtotal > 25: break
        #if the number is divisible by 3, skip it
        if num % 3 == 0: continue
        runningtotal = runningtotal + num

Functions

A function is a block of code that is executed when it is called. Usually functions return something. Most of the time they take arguments

#Function definition
def myfunction():
        #code to execute
        myval = 7
        #return statement
        return myval

#Function definition with arguments
def additionfunction(x, y):
        #execute x + y and return the result
        return x + y
x = myfunction()
y = myfunction() * 2
print additionfunction(x, y)

Classes

A class is an object that you can create with attributes (think variables) that are specific to it, and

class MyClass(object):
        def __init__(cls, firstarg):
                cls.arg = firstarg
                cls.somevalue = 2984

        def do_stuff(cls):
                return cls.firstarg * 9

c = MyClass(6)
print c.do_stuff()
print c.somevalue

Style: Theoretical

"If you’re about to take a hundred lines to write what you could in ten,

stop and ask yourself this: what the fuck?"

- Mark, Criminal Overengineering

Whatever you're writing, keep it short and simple. Python makes it easy to do. Don't be ridiculous.

Also, single-letter variable names: Not ok.

Style: Actual

There are several Python style guides, but the most broadly accepted one is PEP 8:

http://www.python.org/dev/peps/pep-0008/

Here's the basics for PEP8 style:

But wait

Two rules you must remember about PEP8, and are good reasons to break any of the other rules.

  1. When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules.
  2. To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style).

One other one I like to add that isn't PEP8 related, but good to consider: Don't write code you wouldn't want to read.

Files and References

Files

References

The End

Find the slides later:

Find me later: