2. python
• Simple
– Python is a simple and minimalistic language in nature
– Reading a good python program should be like reading English
– Its Pseudo-code nature allows one to concentrate on the problem
rather than the language
• Easy to Learn
• Free & Open source
– Freely distributed and Open source
– Maintained by the Python community
• High Level Language –memory management
• Portable – *runs on anything c code will
07/07/2018 2
CS 331
3. python
• Interpreted
– You run the program straight from the source code.
– Python program Bytecode a platforms native language
– You can just copy over your code to another system and it will auto-
magically work! *with python platform
• Object-Oriented
– Simple and additionally supports procedural programming
• Extensible – easily import other code
• Embeddable –easily place your code in non-python programs
• Extensive libraries
– (i.e. reg. expressions, doc generation, CGI, ftp, web browsers, ZIP, WAV,
cryptography, etc...) (wxPython, Twisted, Python Imaging library)
07/07/2018 3
CS 331
4. Why Python?
• Natural Language ToolKit
• Ease of use; interpreter
• AI Processing: Symbolic
– Python’s built-in datatypes for strings, lists, and more.
– Java or C++ require the use of special classes for this.
• AI Processing: Statistical
– Python has strong numeric processing capabilities:
matrix operations, etc.
– Suitable for probability and machine learning code.
5. 5
• Some influential ones:
– FORTRAN
• science / engineering
– COBOL
• business data
– LISP
• logic and AI
Languages
6. python Timeline/History
• Python was conceived in the late 1980s.
– Guido van Rossum, Benevolent Dictator For Life
– Rossum is Dutch, born in Netherlands, Christmas break
bored, big fan of Monty python’s Flying Circus
– Descendant of ABC, he wrote glob() func in UNIX
– M.D. @ U of Amsterdam, worked for CWI, NIST, CNRI, Google
– Also, helped develop the ABC programming language
• In 1991 python 0.9.0 was published and reached the masses
through alt.sources
• In January of 1994 python 1.0 was released
– Functional programming tools like lambda, map, filter, and reduce
– comp.lang.python formed, greatly increasing python’s userbase
07/07/2018 6
CS 331
7. python Timeline/History
• In 1995, python 1.2 was released.
• By version 1.4 python had several new features
– Keyword arguments (similar to those of common lisp)
– Built-in support for complex numbers
– Basic form of data-hiding through name mangling (easily
bypassed however)
• Computer Programming for Everybody (CP4E) initiative
– Make programming accessible to more people, with basic “literacy”
similar to those required for English and math skills for some jobs.
– Project was funded by DARPA
– CP4E was inactive as of 2007, not so much a concern to get employees
programming “literate”
07/07/2018 7
CS 331
8. python Timeline/History
• In 2000, Python 2.0 was released.
– Introduced list comprehensions similar to Haskells
– Introduced garbage collection
• In 2001, Python 2.2 was released.
– Included unification of types and classes into one
hierarchy, making pythons object model purely Object-
oriented
– Generators were added(function-like iterator behavior)
• Standards
– http://www.python.org/dev/peps/pep-0008/
07/07/2018 8
CS 331
9. 9
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
Python is instead directly interpreted into machine instructions.
compile execute
output
source code
Hello.java
byte code
Hello.class
interpret
output
source code
Hello.py
10. Python types
• Int – 42- may be transparently expanded to
long through 438324932L
• Float – 2.171892
• Complex – 4 + 3j
• Bool – True of False
07/07/2018 10
CS 331
11. Python semantics
• Each statement has its own semantics, the def
statement doesn’t get executed immediately like
other statements
• Python uses duck typing, or latent typing
– Allows for polymorphism without inheritance
– This means you can just declare
“somevariable = 69” don’t actually have to declare a type
– print “somevariable = “ + tostring(somevariable)”
strong typing , can’t do operations on objects not defined
without explicitly asking the operation to be done
07/07/2018 11
CS 331
12. Python Syntax
• Python uses indentation and/or whitespace to delimit
statement blocks rather than keywords or braces
• if __name__ == "__main__":
print “Salve Mundo"
# if no comma (,) at end ‘n’ is auto-included
CONDITIONALS
• if (i == 1): do_something1()
elif (i == 2): do_something2()
elif (i == 3): do_something3()
else: do_something4()
07/07/2018 12
CS 331
13. Conditionals Cont.
• if (value is not None) and (value == 1):
print "value equals 1”,
print “ more can come in this block”
• if (list1 <= list2) and (not age < 80):
print “1 = 1, 2 = 2, but 3 <= 7 so its True”
• if (job == "millionaire") or (state != "dead"):
print "a suitable husband found"
else:
print "not suitable“
• if ok: print "ok"
07/07/2018 13
CS 331
14. Loops/Iterations
• sentence = ['Marry','had','a','little','lamb']
for word in sentence:
print word, len(word)
• for i in range(10):
print I
for i in xrange(1000):# does not allocate all initially
print I
• while True:
pass
• for i in xrange(10):
if i == 3: continue
if i == 5: break
print i,
07/07/2018 14
CS 331
16. Exception handling
• try:
f = open("file.txt")
except IOError:
print "Could not open“
else:
f.close()
• a = [1,2,3]
try:
a[7] = 0
except (IndexError,TypeError):
print "IndexError
caught”
except Exception, e:
print "Exception: ", e
except: # catch everything
print "Unexpected:"
print sys.exc_info()[0]
raise # re-throw caught exception
try:
a[7] = 0
finally:
print "Will run regardless"
• Easily make your own exceptions:
class myException(except)
def __init__(self,msg):
self.msg = msg
def __str__(self):
return
repr(self.msg)
07/07/2018 16
CS 331
17. Classes
class MyVector: """A simple vector class."""
num_created = 0
def __init__(self,x=0,y=0):
self.__x = x
self.__y = y
MyVector.num_created += 1
def get_size(self):
return self.__x+self.__y
@staticmethod
def get_num_created
return MyVector.num_created
#USAGE OF CLASS MyVector
print MyVector.num_created
v = MyVector()
w = MyVector(0.23,0.98)
print w.get_size()
bool = isinstance(v, MyVector)
Output:
0
1.21
07/07/2018 17
CS 331
18. 18
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication,
division
% modulus, a.k.a. remainder
** exponentiation
precedence: Order in which operations are computed.
* / % ** have a higher precedence than + -
1 + 3 * 4 is 13
Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16
19. 19
Integer division
When we divide integers with / , the quotient is also an integer.
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
More examples:
35 / 5 is 7
84 / 10 is 8
156 / 100 is 1
The % operator computes the remainder from a division of integers.
3 43
4 ) 14 5 ) 218
12 20
2 18
15
3
20. 20
Real numbers
Python can also manipulate real numbers.
Examples: 6.022 -15.9997 42.0 2.143e17
The operators + - * / % ** ( ) all work for real numbers.
The / produces an exact answer: 15.0 / 2.0 is 7.5
The same rules of precedence also apply to real numbers:
Evaluate ( ) before * / % before + -
When integers and reals are mixed, the result is a real number.
Example: 1 / 2.0 is 0.5
The conversion occurs on a per-operator basis.
7 / 3 * 1.2 + 3 / 2
2 * 1.2 + 3 / 2
2.4 + 3 / 2
2.4 + 1
3.4
21. 21
Math commands
Python has useful commands for performing calculations.
Command name Description
abs(value) absolute value
ceil(value) rounds up
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
Constant Description
e 2.7182818...
pi 3.1415926...
22. 22
Variables
variable: A named piece of memory that can store a value.
Usage:
Compute an expression's result,
store that result into a variable,
and use that variable later in the program.
assignment statement: Stores a value into a variable.
Syntax:
name = value
Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
A variable that has been given a value can be used in expressions.
x + 4 is 9
Exercise: Evaluate the quadratic equation for a given a, b, and c.
23. 23
print : Produces text output on the console.
Syntax:
print "Message"
print Expression
Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
print Item1, Item2, ..., ItemN
Prints several messages and/or expressions on the same line.
Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
You have 20 years until retirement
print
24. 24
input : Reads a number from user input.
You can assign (store) the result of input into a variable.
Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years until retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
Exercise: Write a Python program that prompts the user for
his/her amount of money, then reports how many Nintendo Wiis
the person can afford, and how much more money he/she will
need to afford an additional Wii.
input
26. 26
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
for variableName in groupOfValues:
statements
We indent the statements to be repeated with tabs or spaces.
variableName gives a name to each value, so you can refer to it in the statements.
groupOfValues can be a range of integers, specified with the range function.
Example:
for x in range(1, 6):
print x, "squared is", x * x
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
27. 27
range
The range function specifies a range of integers:
range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
It can also accept a third value specifying the change between values.
range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff!
Exercise: How would we print the "99 Bottles of Beer" song?
28. 28
Cumulative loops
Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum
Output:
sum of first 10 squares is 385
Exercise: Write a Python program that computes the factorial of
an integer.
29. 29
if
if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
Syntax:
if condition:
statements
Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."
30. 30
if/else
if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
Syntax:
if condition:
statements
else:
statements
Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."
Multiple conditions can be chained with elif ("else if"):
if condition:
statements
elif condition:
statements
else:
statements
31. 31
while
while loop: Executes a group of statements as long as a condition is True.
good for indefinite loops (repeat an unknown number of times)
Syntax:
while condition:
statements
Example:
number = 1
while number < 200:
print number,
number = number * 2
Output:
1 2 4 8 16 32 64 128
32. 32
Logic
Many logical expressions use relational operators:
Logical expressions can be combined with logical operators:
Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
34. 34
string: A sequence of text characters in a program.
Strings start and end with quotation mark " or apostrophe ' characters.
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
A string can represent characters by preceding them with a backslash.
t tab character
n new line character
" quotation mark character
backslash character
Example: "HellottherenHow are you?"
Strings
35. 35
Indexes
Characters in a string are numbered with indexes starting at 0:
Example:
name = "P. Diddy"
Accessing an individual character of a string:
variableName [ index ]
Example:
print name, "starts with", name[0]
Output:
P. Diddy starts with P
index 0 1 2 3 4 5 6 7
character P . D i d d y
36. 36
String properties
len(string) - number of characters in a string
(including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length, "characters"
Output:
MARTIN DOUGLAS STEPP has 20 characters
37. 37
raw_input : Reads a string of text from user input.
Example:
name = raw_input("Howdy, pardner. What's yer name? ")
print name, "... what a silly name!"
Output:
Howdy, pardner. What's yer name? Paris Hilton
Paris Hilton ... what a silly name!
raw_input
38. 38
Text processing
text processing: Examining, editing, formatting text.
often uses loops that examine the characters of a string one by one
A for loop can examine each character in a string in sequence.
Example:
for c in "booyah":
print c
Output:
b
o
o
y
a
h
39. 39
Strings and numbers
ord(text) - converts a string into a number.
Example: ord("a") is 97, ord("b") is 98, ...
Characters map to numbers using standardized mappings such as
ASCII and Unicode.
chr(number) - converts a number into a string.
Example: chr(99) is "c"
Exercise: Write a program that performs a rotation cypher.
e.g. "Attack" when rotated by 1 becomes "buubdl"
40. 40
File processing
Many programs handle data, which often comes from files.
Reading the entire contents of a file:
variableName = open("filename").read()
Example:
file_text = open("bankaccount.txt").read()
41. 41
Line-by-line processing
Reading a file line-by-line:
for line in open("filename").readlines():
statements
Example:
count = 0
for line in open("bankaccount.txt").readlines():
count = count + 1
print "The file contains", count, "lines."
Exercise: Write a program to process a file of DNA text, such as:
ATGCAATTGCTCGATTAG
Count the percent of C+G present in the DNA.