Introduction to Python Python Official website http python
Introduction to Python
Python Official website http: //python. org/ documentation, tutorials, beginners guide, core distribution, . . . Versions Version 2. 7 came out in mid-2010 Version 3. 1. 2 came out in early 2010
Python Interactive Shell Two variations: IDLE (GUI), python (command line) % python Python 2. 6. 1 (r 261: 67515, Feb 11 2010, 00: 51: 29) [GCC 4. 2. 1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> You can type things directly into a running Python session >>> 2+3*4 14 >>> name = "Andrew" >>> name 'Andrew' >>> print "Hello", name Hello Andrew >>> # this is a comment >>>
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 Output: 13 Parentheses can be used to force a certain order of evaluation. (1 + 3) * 4 Output: 16
Integer Division When we divide integers with / , the quotient is also an integer. Examples: 35 / 5 is 7 84 / 10 is 8 156 / 100 is 1 The % operator computes the remainder from a division of integers. 5
Variables variable: A named piece of memory that can store a value. 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 A variable that has been given a value can be used in expressions. x + 4 output: 9 6
Variables No need to declare Need to assign (initialize) use Not of uninitialized variable raises exception typed greeting = "hello world" greeting = 12**2 print greeting
Reference Semantics Assignment manipulates references x = y does not make a copy of y x = y makes x reference the object y references Very useful; but beware! Example: >>> a = [1, 2, 3] >>> b = a >>> a. append(4) >>> print b [1, 2, 3, 4]
Grouping Indentation for i in range(20): if i%3 == 0: print i if i%5 == 0: print "Bingo!" print "---"
print Produces text output on the console. Syntax: print "Message" print Expression print Item 1, Item 2, . . . , Item. N 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
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
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. " 12
if/else statement: Syntax: if condition: statements else: statements Multiple conditions: Syntax if condition: statements else: statements 13
while Syntax: while condition: statements Example: number = 1 while number < 200: print number, number = number * 2 Output: 1 2 4 8 16 32 64 128
Logic 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 Operator Example Result and 9 != 6 and 2 < 3 True or 2 == 3 or -1 < 5 True not 7 > 0 False 15
Control Flow Things that are False The boolean value False The numbers 0 (integer), 0. 0 (float) and 0 j (complex). The empty string "". The empty list [], empty dictionary {} and empty set(). Things that are True The boolean value True All non-zero numbers. Any string containing at least one character. A non-empty data structure.
Boolean logic Python expressions can have “and”s and “or”s: if (ben <= 5 and chen >= 10 or chen == 500 and ben != 5): print “Ben and Chen” Range Test if (3 <= Time <= 5): print “Office Hour"
The for loop Repeats a set of statements over a group of values. Syntax: for variable. Name in group. Of. Values: statements We indent the statements to be repeated with tabs or spaces.
The for loop Example: for x in range(1, 6): print x, "squared is", x * x Output: 1 squared 2 squared 3 squared 4 squared 5 squared is is is 1 4 9 16 25
Range() Creates a list of numbers in a specified range Syntax: range(start, stop, step) When step is given, it specifies the increment (or decrement). >>> range(5) [0, 1, 2, 3, 4] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 2) [0, 2, 4, 6, 8] How to get every second element in a list? for i in range(0, len(data), 2): print data[i]
Range() example for x in range(5, 0, -1): print x print "Blastoff!" Output: 5 4 3 2 1 Blastoff! 21
Cumulative Loops Some loops incrementally compute a value that is initialized outside the loop. This is sometimes called a cumulative 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
For Loop used in List >>> names = [“Ben", “Chen", “Yaqin"] >>> for name in names: . . . Ben Chen Yaqin print smiles
Strings 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: "Hellottheren. How are you? "
String Operations "hello"+"world" "hello"*3 "hello"[0] "hello"[-1] "hello"[1: 4] len("hello") "hello" < "jello" "e" in "hello" "helloworld" # concatenation "hellohello" # repetition "h" # indexing "o" # (from end) "ell" # slicing 5 # size 1 # comparison, true 1 # search, true
String Methods: find, split >>> smiles = "C(=N)(N)N. C(=O)(O)O" >>> smiles. find("(O)") • Use “find” to find the start of a substring. 15 >>> smiles. find(". ") • Start looking at position 10. 9 >>> smiles. find(". ", 10) • Find returns -1 if it couldn’t find a match. -1 >>> smiles. split(". ") • Split the string into parts ['C(=N)(N)N', 'C(=O)(O)O'] with “. ” as the delimiter >>>
String operators: in, not in if "Br" in “Brother”: print "contains brother“ email_address = “clin” if "@" not in email_address: email_address += "@brandeis. edu“
Unexpected things about strings Strings are read only >>> s = "andrew" >>> s[0] = "A" Error >>> s = "A" + s[1: ] >>> s 'Andrew‘
Lists Flexible arrays a = [99, "bottles of beer", ["on", "the", "wall"]] Same operators as for strings a+b, a*3, a[0], a[-1], a[1: ], len(a) Item and slice assignment a[0] = 98 a[1: 2] = ["bottles", "of", "beer"] #-> [98, "bottles", "of", "beer", ["on", "the", "wall"]] del a[-1] # -> [98, "bottles", "of", "beer"]
Use [ ] to index items in the list >>> names = [“Bend”, “Chen”, “Doug”] >>> names[0] ‘Ben' >>> names[1] ‘Chen' >>> names[3] Error >>> names[-1] ‘Doug' >>> names[-2] ‘Chen' >>> names[-3] ‘Ben' [0] is the first item. [1] is the second item. . . Out of range values raise an exception Negative values go backwards from the last element.
Lists are mutable - some useful methods >>> ids = ["9 pti", "2 plv", "1 crn"] >>> ids. append("1 alm") >>> ids ['9 pti', '2 plv', '1 crn', '1 alm'] >>> del ids[0] >>> ids ['2 plv', '1 crn', '1 alm'] >>> ids. sort() >>> ids ['1 alm', '1 crn', '2 plv'] >>> ids. reverse() >>> ids ['2 plv', '1 crn', '1 alm'] >>> ids. insert(0, "9 pti") >>> ids ['9 pti', '2 plv', '1 crn', '1 alm']
Tuples: sort of an immutable list >>> yellow = (255, 0) # r, g, b >>> yellow[1: ] (255, 0) >>> yellow[0] = 0 Error
Dictionaries are lookup tables. They map from a “key” to a “value”. symbol_to_name = { "H": "hydrogen", "He": "helium", "Li": "lithium", "C": "carbon", "O": "oxygen", "N": "nitrogen" } Duplicate keys are not allowed Duplicate values are just fine
Dictionary >>> symbol_to_name["C"] 'carbon' >>> "O" in symbol_to_name, "U" in symbol_to_name (True, False) >>> "oxygen" in symbol_to_name False
Some useful dictionary methods >>> symbol_to_name. keys() ['C', 'H', 'O', 'N', 'Li', 'He'] >>> symbol_to_name. values() ['carbon', 'hydrogen', 'oxygen', 'nitrogen', 'lithium', 'helium'] >>> symbol_to_name. update( {"P": "phosphorous", "S": "sulfur"} ) >>> symbol_to_name. items() [('C', 'carbon'), ('H', 'hydrogen'), ('O', 'oxygen'), ('N', 'nitrogen'), ('P', 'phosphorous'), ('S', 'sulfur'), ('Li', 'lithium'), ('He', 'helium')] >>> del symbol_to_name['C'] >>> symbol_to_name {'H': 'hydrogen', 'O': 'oxygen', 'N': 'nitrogen', 'Li': 'lithium', 'He': 'helium'}
More List Operations >>> a = range(5) # [0, 1, 2, 3, 4] >>> a. append(5) # [0, 1, 2, 3, 4, 5] >>> a. pop() # [0, 1, 2, 3, 4] 5 >>> a. insert(0, 42) # [42, 0, 1, 2, 3, 4] >>> a. pop(0) # [0, 1, 2, 3, 4] 42 >>> a. reverse() # [4, 3, 2, 1, 0] >>> a. sort() # [0, 1, 2, 3, 4]
Functions, Procedures def name(arg 1, arg 2, . . . ): """documentation""" # optional doc string statements return # from procedure return expression # from function
Example Function def gcd(a, b): "greatest common divisor" while a != 0: a, b = b%a, a # parallel assignment return b >>> gcd. __doc__ 'greatest common divisor' >>> gcd(12, 20) 4
Classes class name: "documentation" statements -orclass name(base 1, base 2, . . . ): . . . Most, statements are method definitions: def name(self, arg 1, arg 2, . . . ): . . . May also be class variable assignments
Example Class class Stack: "A well-known data structure…" def __init__(self): # constructor self. items = [] def push(self, x): self. items. append(x) # the sky is the limit def pop(self): x = self. items[-1] # what happens if it’s empty? del self. items[-1] return x def empty(self): return len(self. items) == 0 # Boolean result
Using Classes To create an instance, simply call the class object: x = Stack() # no 'new' operator! To use methods of the instance, call using dot notation: x. empty()# -> 1 x. push(1) # [1] x. empty()# -> 0 x. push("hello") x. pop() # [1, "hello"] # -> "hello" # [1] To inspect instance variables, use dot notation: x. items # -> [1]
File Processing Many programs handle data, which often comes from files. Read the entire contents of a file: variable. Name = open("filename"). read() Example: file_text = open("bankaccount. txt"). read()
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. " 43
File Output input_file = open(“in. txt") output_file = open(“out. txt", "w") for line in input_file: output_file. write(line)
Modules When a Python program starts it only has access to a basic functions and classes. (“int”, “dict”, “len”, “sum”, “range”, . . . ) “Modules” Use contain additional functionality. “import” to tell Python to load a module. >>> import math >>> import nltk
import the math module >>> import math >>> math. pi 3. 1415926535897931 >>> math. cos(0) 1. 0 >>> math. cos(math. pi) -1. 0
“import” and “from. . . import. . . ” >>> import math. cos >>> from math import cos, pi cos >>> from math import *
Math Commands Command name abs(value) Description ceil(value) rounds up cos(value) cosine, in radians floor(value) rounds down log(value) logarithm, base e log 10(value) logarithm, base 10 absolute value max(value 1, value 2) larger of two values min(value 1, value 2) smaller of two values round(value) nearest whole number sin(value) sine, in radians sqrt(value) square root Constant e Description pi 3. 1415926. . . 2. 7182818. . . 48
Classes class Class. Name(object): <statement-1>. . . <statement-N> class My. Class(object): """A simple example class""" i = 12345 def f(self): return self. i class Derived. Class. Name(Base. Class. Name): <statement-1>. . . <statement-N>
- Slides: 49