Python 101
McBryde 101
Feb 22, 2013
Overview for Today
1. Setting up Python
2. Background on Python
3. Basics of Python
4. Data Structures in Python
5. Control Structures in Python
6. Functions in Python
Things you should do
Ask questions!
   If you are confused, there is a 80% chance that
someone else is even more confused.
Participate!
   We're all friends here. Tell us if we're going too slowly.
Tell us if we're boring. Tell us if have an idea for
something.
Follow along!
   Open up Python and try stuff!
Setting up Python
Download & Install Python
http://www.python.org/download/

Run python
Windows: python.exe
Mac/Linux: python
Background on Python
What is Python?
● A language

● An interpreter

● A reference to a British sketch comedy:
  "Monty Python's Flying Circus"
   (The documentation is full of jokes referencing the
show)
Why Python?
● Traditional languages (C++, C, Java)
  evolved for large-scale programming

● Scripting language (Perl, Python) evolved
  for simplicity and flexibility
The Python Language
● Free!
● Elegant and Powerful!
● Cross-Platform!
● Tons of useful modules!
● Chock full of technical buzzwords!
  ○ Object-oriented, dynamic-typing
The "Zen" of Python
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
...
Readability Counts
... (It's actually a lot longer)
The Basics
Printing in Python
>>> print "Hello World."
Hello World.


Meanwhile, in Java land:
public class MyFirstProgram {
   public static void main(String[] args) {
     System.out.println("Hello World");
   }
}
Input in Python
>>> input("Tell me something: ")
Tell me something:


Type something in and press enter
Comments in Python
>>> # This is a comment
...


The following will NOT work:
/*
Multiline comment in Java
*/
// Single line comment in Java
Scripts in Python
1. In your IDE/Text Editor, write
   # My first program!
   print "Hello", "World"
2. Save the file as helloworld.py
3. From the terminal,
   > python helloworld.py
   Hello World.
Congratulations!
You are now all Python programmers.
Basic Data
Values in Python
-5           #   Integer type
23.1         #   Float type
"Some words" #   String type
True         #   Boolean type

Variables in Python
age                =   23
miles_from_home    =   301.36
name               =   "Cory Bart"
has_dog            =   False
Operators
Numerics    Strings
1 + 4       "Hello " + "World"
2 - 3       "Repeat" * 5
4 * 1
10.0 / 2    Comparisons
10.5 // 2   10 >= 5
2 ** 4      3 < 80
22 % 12     5 == 10
            3 != 3
Operators continued...
Boolean logic
True and False
True or True
not True
Exercise
given a string myString and a
numbernumRepetitions, return myString
multiplied numRepetitions times.

multiplyString('a', 4) → 'aaaa'
multiplyString('Hello', 2) → 'HelloHello'
multiplyString('Python', 3) →
'PythonPythonPython'
Control and Data Structures
If statements
if has_dogs:
   print "Has dogs"
elif age >= 25:
   print "Can rent a car"
elif name == "Ellie" or name == "Becky"
   print "Is awesome!"
else:
   print "Not a great fellow"

*Note the white-space!*
Defining functions
def add(first, second):
  return first + second

value = add(10, 5)
Exercise
Write a function that can compute tips for a
meal, given the price and how generous the
user is.

# price: float
# generous: string, either "stingy"
#           or "generous"
# returns a float indicating tip
def calculate_tip(price, generosity):
   ...
Multiple returns!
def flip_coordinates(pos):
  x, y = pos
  return -x, -y

x, y = flip_coordinates((5, -5))
Sequences
Lists are Mutable and Ordered
a_list       = [1, 3, 2]
Tuples are Immutable and Ordered
a_tuple = (1, 2, 3)
Sets are Mutable, Unordered, and Unique
a_set        = set([1, 2, 3])
Dictionaries are Key-Value pairs
a_dictionary         = {'A': 1, 'B': 2, 'C': 3}
Strings are immutable sequences of one-character Strings!
a_string = "Also a sequence!"
Working with a list
colors = ['red', 'blue', 'yellow', 'purple']
Add to a list
colors.append('green') or colors.insert
(index)
Remove from a list
colors.pop() or colors.remove(index)
Sets are a little different
>>> set([1, 1, 2,    -2, 3, 3, 4])
set([1, 2, -2, 3,    4])
>>> set([1, 2, -2,   3, 4]).add(4)
set([1, 2, -2, 3,    4])
>>> set([1, 2, -2,   3, 4]).add(5)
set([1, 2, -2, 3,    4, 5])
Tuples are a little different
>>> my_tuple = (1, 2, 3, 4)
>>> my_tuple.add(5)
NOPE!

Tuples will be more awesome when we get to
functions.
Dictionaries are wonderful
>>> scores = {"Cory": 32,
              "Ellie": 100,
              "Becky": 78}

>>> print scores["Cory"]
32
Working with sequences
Get an element of a sequence:
"Puzzle"[2]
Get the length of a sequence
len(set([1, 2, 3, 4, 5, 6]))
Is something in a sequence?
5 in (1, 2, 3, 4, 5)
Get a sublist from a list
['red', 'blue', 'yellow', 'green'][1:2]
There are many built-in functions for sequences
sum((1, 2, 3, 4))
min((5, 10, 15))
Strings have a ton of methods!
"1, 2, 3, 4".split(",")

",".join([1,2,3,4])

"   whitespace   ".strip()

"I am 22".replace("am", "was")

"HeLlO wOrLd".swapcase()
Converting between types
str(5)                ->   "5"
int("10")             ->   10
float("10.0")         ->   10.0
bool(None)            ->   False
list((1, 2, 3, 4))    ->   [1,2,3,4]
tuple([1, 2, 4, 8])   ->   (1,2,4,8)
Truthiness in Python
        True                  False
True                  False
5                     0
-5                    []
[1, 2, 3]             ""
"Hello world"         None

         items_left = [1, 2, 3]
         while items_left:
           print items_left.pop()
Looping
The for-each loop is best!
                                      List
for item in [1, 2, 3]:                Set
  print item                         Tuple
                                    String
                                 File handler
You can also use a while loop.

while True:
  # do something
xrange
for value in xrange(5):
   print value

0
1
2
3
4
Iterating with indices
for index, item in enumerate("ABCDE"):
   print index, item

0   A
1   B
2   C
3   D
4   E
Iterating over Dictionary
a_dictionary = {'a':1,'b':2}
for key, value in a_dictionary.items():
   print key, value
Exercise
Write a program that will "translate" a sentence
into Pyglatin:

"We only speak Pyglatin in Pyrome"
->
"Eway onlyay peaksay Yglatinpay inay yromeay"
List comprehensions
You can make a list by sticking a for loop inside!

[value*2 for value in range(10)]

[int(number) for number in "123456789"]
File I/O
file = open('word_lists.txt', 'r')
for line in file:
  print line

file = open('numbers.txt', 'w')
for number in range(100):
  file.write(number)
Importing
import random
random.choice(("Heads", "Tails"))

import sys
print sys.args

import math
print math.sqrt(36)
Command line arguments
>python file.py this is a test

Inside of file.py
import sys
print sys.args

Outputs
['this', 'is', 'a', 'test']
What should I do next?
The Python Challenge
  http://www.pythonchallenge.com/

Online Books:
  http://tinyurl.com/interactivepython
Feedback
● Facebook - http://tinyurl.com/letscode


● Would you be interested in this formulating
  into a meetup group?
● How often?
● What would you like to learn next?
● Does the location matter?
● Any other feedback?
● How large/small class size would you
  prefer?

Python 101 1

  • 1.
  • 2.
    Overview for Today 1.Setting up Python 2. Background on Python 3. Basics of Python 4. Data Structures in Python 5. Control Structures in Python 6. Functions in Python
  • 3.
    Things you shoulddo Ask questions! If you are confused, there is a 80% chance that someone else is even more confused. Participate! We're all friends here. Tell us if we're going too slowly. Tell us if we're boring. Tell us if have an idea for something. Follow along! Open up Python and try stuff!
  • 4.
  • 5.
    Download & InstallPython http://www.python.org/download/ Run python Windows: python.exe Mac/Linux: python
  • 6.
  • 7.
    What is Python? ●A language ● An interpreter ● A reference to a British sketch comedy: "Monty Python's Flying Circus" (The documentation is full of jokes referencing the show)
  • 8.
    Why Python? ● Traditionallanguages (C++, C, Java) evolved for large-scale programming ● Scripting language (Perl, Python) evolved for simplicity and flexibility
  • 9.
    The Python Language ●Free! ● Elegant and Powerful! ● Cross-Platform! ● Tons of useful modules! ● Chock full of technical buzzwords! ○ Object-oriented, dynamic-typing
  • 10.
    The "Zen" ofPython Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. ... Readability Counts ... (It's actually a lot longer)
  • 11.
  • 12.
    Printing in Python >>>print "Hello World." Hello World. Meanwhile, in Java land: public class MyFirstProgram { public static void main(String[] args) { System.out.println("Hello World"); } }
  • 13.
    Input in Python >>>input("Tell me something: ") Tell me something: Type something in and press enter
  • 14.
    Comments in Python >>># This is a comment ... The following will NOT work: /* Multiline comment in Java */ // Single line comment in Java
  • 15.
    Scripts in Python 1.In your IDE/Text Editor, write # My first program! print "Hello", "World" 2. Save the file as helloworld.py 3. From the terminal, > python helloworld.py Hello World.
  • 16.
    Congratulations! You are nowall Python programmers.
  • 17.
  • 18.
    Values in Python -5 # Integer type 23.1 # Float type "Some words" # String type True # Boolean type Variables in Python age = 23 miles_from_home = 301.36 name = "Cory Bart" has_dog = False
  • 19.
    Operators Numerics Strings 1 + 4 "Hello " + "World" 2 - 3 "Repeat" * 5 4 * 1 10.0 / 2 Comparisons 10.5 // 2 10 >= 5 2 ** 4 3 < 80 22 % 12 5 == 10 3 != 3
  • 20.
    Operators continued... Boolean logic Trueand False True or True not True
  • 21.
    Exercise given a stringmyString and a numbernumRepetitions, return myString multiplied numRepetitions times. multiplyString('a', 4) → 'aaaa' multiplyString('Hello', 2) → 'HelloHello' multiplyString('Python', 3) → 'PythonPythonPython'
  • 22.
    Control and DataStructures
  • 23.
    If statements if has_dogs: print "Has dogs" elif age >= 25: print "Can rent a car" elif name == "Ellie" or name == "Becky" print "Is awesome!" else: print "Not a great fellow" *Note the white-space!*
  • 24.
    Defining functions def add(first,second): return first + second value = add(10, 5)
  • 25.
    Exercise Write a functionthat can compute tips for a meal, given the price and how generous the user is. # price: float # generous: string, either "stingy" # or "generous" # returns a float indicating tip def calculate_tip(price, generosity): ...
  • 26.
    Multiple returns! def flip_coordinates(pos): x, y = pos return -x, -y x, y = flip_coordinates((5, -5))
  • 27.
    Sequences Lists are Mutableand Ordered a_list = [1, 3, 2] Tuples are Immutable and Ordered a_tuple = (1, 2, 3) Sets are Mutable, Unordered, and Unique a_set = set([1, 2, 3]) Dictionaries are Key-Value pairs a_dictionary = {'A': 1, 'B': 2, 'C': 3} Strings are immutable sequences of one-character Strings! a_string = "Also a sequence!"
  • 28.
    Working with alist colors = ['red', 'blue', 'yellow', 'purple'] Add to a list colors.append('green') or colors.insert (index) Remove from a list colors.pop() or colors.remove(index)
  • 29.
    Sets are alittle different >>> set([1, 1, 2, -2, 3, 3, 4]) set([1, 2, -2, 3, 4]) >>> set([1, 2, -2, 3, 4]).add(4) set([1, 2, -2, 3, 4]) >>> set([1, 2, -2, 3, 4]).add(5) set([1, 2, -2, 3, 4, 5])
  • 30.
    Tuples are alittle different >>> my_tuple = (1, 2, 3, 4) >>> my_tuple.add(5) NOPE! Tuples will be more awesome when we get to functions.
  • 31.
    Dictionaries are wonderful >>>scores = {"Cory": 32, "Ellie": 100, "Becky": 78} >>> print scores["Cory"] 32
  • 32.
    Working with sequences Getan element of a sequence: "Puzzle"[2] Get the length of a sequence len(set([1, 2, 3, 4, 5, 6])) Is something in a sequence? 5 in (1, 2, 3, 4, 5) Get a sublist from a list ['red', 'blue', 'yellow', 'green'][1:2] There are many built-in functions for sequences sum((1, 2, 3, 4)) min((5, 10, 15))
  • 33.
    Strings have aton of methods! "1, 2, 3, 4".split(",") ",".join([1,2,3,4]) " whitespace ".strip() "I am 22".replace("am", "was") "HeLlO wOrLd".swapcase()
  • 34.
    Converting between types str(5) -> "5" int("10") -> 10 float("10.0") -> 10.0 bool(None) -> False list((1, 2, 3, 4)) -> [1,2,3,4] tuple([1, 2, 4, 8]) -> (1,2,4,8)
  • 35.
    Truthiness in Python True False True False 5 0 -5 [] [1, 2, 3] "" "Hello world" None items_left = [1, 2, 3] while items_left: print items_left.pop()
  • 36.
    Looping The for-each loopis best! List for item in [1, 2, 3]: Set print item Tuple String File handler You can also use a while loop. while True: # do something
  • 37.
    xrange for value inxrange(5): print value 0 1 2 3 4
  • 38.
    Iterating with indices forindex, item in enumerate("ABCDE"): print index, item 0 A 1 B 2 C 3 D 4 E
  • 39.
    Iterating over Dictionary a_dictionary= {'a':1,'b':2} for key, value in a_dictionary.items(): print key, value
  • 40.
    Exercise Write a programthat will "translate" a sentence into Pyglatin: "We only speak Pyglatin in Pyrome" -> "Eway onlyay peaksay Yglatinpay inay yromeay"
  • 41.
    List comprehensions You canmake a list by sticking a for loop inside! [value*2 for value in range(10)] [int(number) for number in "123456789"]
  • 42.
    File I/O file =open('word_lists.txt', 'r') for line in file: print line file = open('numbers.txt', 'w') for number in range(100): file.write(number)
  • 43.
    Importing import random random.choice(("Heads", "Tails")) importsys print sys.args import math print math.sqrt(36)
  • 44.
    Command line arguments >pythonfile.py this is a test Inside of file.py import sys print sys.args Outputs ['this', 'is', 'a', 'test']
  • 45.
    What should Ido next? The Python Challenge http://www.pythonchallenge.com/ Online Books: http://tinyurl.com/interactivepython
  • 46.
    Feedback ● Facebook -http://tinyurl.com/letscode ● Would you be interested in this formulating into a meetup group? ● How often? ● What would you like to learn next? ● Does the location matter? ● Any other feedback? ● How large/small class size would you prefer?