A notebook demonstrating some key features of the python programming language.
Draws particularly closely on ideas from the Python Tutorial and the Python Regular Expression Tutorial
You might also want to familiarize yourself with IPython notebooks, through sites like this one or this one.
Don't forget the argument sketch.
Matthew Stone; Feb 10, 2015; CS 195.
Numerical computations, specified interactively.
9 / 2
4
Lists: specified using brackets.
[1, 2, 3]
[1, 2, 3]
Tuples: fixed sequences, specified using parentheses.
("a", "b")
('a', 'b')
Various ways of specifying string literals, using single quotes or double quotes, and using the r
tag to control how special characters are treated.
man1 = "I'd like to have an argument please."
man1
"I'd like to have an argument please."
man2 = 'I\'d like to have an argument please.'
man2
"I'd like to have an argument please."
man3 = r"I'd like to have an argument please."
man3
"I'd like to have an argument please."
man4 = r'I\'d like to have an argument please.'
man4
"I\\'d like to have an argument please."
A variety of operations on strings:
len
(function): Computing the length of a stringsplit
(method): Separating a string into tokens based on a simple pattern delimeter[:]
notationlen(man1)
36
words = man1.split(' ')
words
["I'd", 'like', 'to', 'have', 'an', 'argument', 'please.']
man1[2]
'd'
man1[-2]
'e'
man1[0:15]
"I'd like to hav"
man1[:8]
"I'd like"
man1[-7:]
'please.'
Key concepts and constructs for flow of control in Python
:
if ... else ...
blocks for conditional executionfor ...
blocks for iterationYou can totally [geek out][1] on programming with generators! [1]:http://www.dabeaz.com/generators/
if man1[-1] == '.' :
man1 = man1[:-1]
man1
"I'd like to have an argument please"
for w in words :
print w, "!"
I'd ! like ! to ! have ! an ! argument ! please. !
'-- '.join(words)
"I'd-- like-- to-- have-- an-- argument-- please."
'-- '.join(w.upper() + " really " for w in words if len(w) < 5 )
"I'D really -- LIKE really -- TO really -- HAVE really -- AN really "
Regular expressions, the mainstay of string programming in Python.
Interface:
compile
a regular expression (string) into a patternsearch
or match
a pattern against another string, returning Match
objectsgroup
method gives the matched string (or matched substrings for complex patterns)span
shows where in the original string the match was foundimport re
pat1 = r"argument"
p1 = re.compile(pat1)
m1 = p1.search(man1)
m1
<_sre.SRE_Match at 0x105a6b308>
m1.group()
'argument'
m1.span()
(20, 28)
man1[20:28]
'argument'
Key elements of regular expressions
\\s
for space, .
for anything*
for any number of repetitions including 0()
to group subexpressions (which can then be repeated, reported, etc.)pat2 = r"I'd like to\s(.*)\splease"
p2 = re.compile(pat2)
m2 = p2.search(man1)
m2
<_sre.SRE_Match at 0x105a700a8>
m2.group()
"I'd like to have an argument please"
m2.group(1)
'have an argument'
"You can't " + m2.group(1) + "!"
"You can't have an argument!"