版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、An Introduction to the Python Programming Language,Presented by Michael DiRamio ,My Background,At Brock for teachers college Currently on a practical teaching block at Westlane Secondary (DSBN) Undergrad at UW in math and computers with a focus on programming languages Favorite programming language
2、is Scheme (my apologies if I refer to it too often!),Your Background,Which of these languages do you know? C or C+ Java Perl Scheme,Presentation Overview,Running Python and Output Data Types Input and File I/O Control Flow Functions Classes,Hello World, hello world! hello world!,Open a terminal wind
3、ow and type “python” If on Windows open a Python IDE like IDLE At the prompt type hello world!,Python Overview,From Learning Python, 2nd Edition: Programs are composed of modules Modules contain statements Statements contain expressions Expressions create and process objects,The Python Interpreter,P
4、ython is an interpreted language The interpreter provides an interactive environment to play with the language Results of expressions are printed on the screen, 3 + 7 10 3 print me print me print print me print me ,Output: The print Statement, print hello hello print hello, there hello there,Element
5、s separated by commas print with a space between them A comma at the end of the statement (print hello,) will not print a newline character,Documentation, this will print this will print #this will not ,The # starts a line comment,Variables,Are not declared, just assigned The variable is created the
6、 first time you assign it a value Are references to objects Type information is with the object, not the reference Everything in Python is an object,Everything is an object?,Everything means everything, including functions and classes (more on this later!), x = 7 x 7 x = hello x hello ,Type info is
7、with the object,Numbers: Integers,Integer the equivalent of a C long Long Integer an unbounded integer value. Newer versions of Python will automatically convert to a long integer if you overflow a normal one, 132224 132224 132323 * 2 ,Numbers: Floating Point,int(x) converts x to an int
8、eger float(x) converts x to a floating point The interpreter shows a lot of digits, including the variance in floating point To avoid this use “print”, 1.23232 1.2323200000000001 print 1.23232 1.23232 1.3E7 13000000.0 int(2.0) 2 float(2) 2.0,Numbers: Complex,Built into Python Same operations are sup
9、ported as integer and float, x = 3 + 2j y = -1j x + y (3+1j) x * y (2-3j),Numbers: A Wrap Up,Numbers are immutable Many math functions in the math module, import math dir(math) _doc_, _file_, _name_, acos, asin, atan, atan2, ceil, cos, cosh, degrees, e, exp, fabs, floor, fmod, frexp, hypot, ldexp, l
10、og, log10, modf, pi, pow, radians, sin, sinh, sqrt, tan, tanh ,String Literals,Strings are immutable There is no char type like in C+ or Java + is overloaded to do concatenation, x = hello x = x + there x hello there,String Literals: Many Kinds,Can use single or double quotes, and three double quote
11、s for a multi-line string, I am a string I am a string So am I! So am I! And me too! . though I am much longer . than the others :) And me too!nthough I am much longernthan the others :),Substrings and Methods, s = 012345 s3 3 s1:4 123 s2: 2345 s:4 0123 s-2 4,len(String) returns the number of charac
12、ters in the String str(Object) returns a String representation of the Object, len(x) 6 str(10.3) 10.3,String Formatting,Similar to Cs printf % Can usually just use %s for everything, it will convert the object to its String representation., One, %d, three % 2 One, 2, three %d, two, %s % (1,3) 1, two
13、, 3 %s two %s % (1, three) 1 two three ,Lists,Ordered collection of data Data can be different types Lists are mutable Issues with shared references and mutability Same subset operations as Strings, x = 1,hello, (3 + 2j) x 1, hello, (3+2j) x2 (3+2j) x0:2 1, hello,Lists: Modifying Content,xi = a reas
14、signs the ith element to the value a Since x and y point to the same list object, both are changed Append also modifies the list, x = 1,2,3 y = x x1 = 15 x 1, 15, 3 y 1, 15, 3 x.append(12) y 1, 15, 3, 12,Lists: not all are in-place changes,Append modifies the list and returns None (the python versio
15、n of null) List addition returns a new list, x = 1,2,3 y = x z = x.append(12) z = None True y 1, 2, 3, 12 x = x + 9,10 x 1, 2, 3, 12, 9, 10 y 1, 2, 3, 12 ,Tuples,Tuples are immutable versions of lists One strange point is the format to make a tuple with one element (the , is needed to differentiate
16、from the mathematical expression (2), x = (1,2,3) x1: (2, 3) y = (2,) y (2,) ,Dictionaries,A set of key-value pairs Dictionaries are mutable, d = 1 : hello, two : 42, blah : 1,2,3 d 1: hello, two: 42, blah: 1, 2, 3 dblah 1, 2, 3,Dictionaries: Add/Modify,Entries can be changed by assigning to that en
17、try Assigning to a key that does not exist adds an entry, d 1: hello, two: 42, blah: 1, 2, 3 dtwo = 99 d 1: hello, two: 99, blah: 1, 2, 3 d7 = new entry d 1: hello, 7: new entry, two: 99, blah: 1, 2, 3,Dictionaries: Deleting Elements,The del method deletes an element from a dictionary, d 1: hello, 2
18、: there, 10: world del(d2) d 1: hello, 10: world,Copying Dictionaries and Lists,The built-in list function will copy a list The dictionary has a method called copy, l1 = 1 l2 = list(l1) l10 = 22 l1 22 l2 1, d = 1 : 10 d2 = d.copy() d1 = 22 d 1: 22 d2 1: 10,Data Type Wrap Up,Lists, Tuples, and Dictio
19、naries can store any type (including other lists, tuples, and dictionaries!) Only lists and dictionaries are mutable All variables are references,Data Type Wrap Up,Integers: 2323, 3234L Floating Point: 32.3, 3.1E2 Complex: 3 + 2j, 1j Lists: l = 1,2,3 Tuples: t = (1,2,3) Dictionaries: d = hello : the
20、re, 2 : 15,Input,The raw_input(string) method returns a line of user input as a string The parameter is used as a prompt The string can be converted by using the conversion methods int(string), float(string), etc.,Input: Example,print Whats your name? name = raw_input() print What year were you born
21、? birthyear = int(raw_input() print Hi %s! You are %d years old! % (name, 2005 - birthyear),: python input.py Whats your name? Michael What year were you born? 1980 Hi Michael! You are 25 years old!,Files: Input,Files: Output,Booleans,0 and None are false Everything else is true True and False are a
22、liases for 1 and 0 respectively (added in more recent versions of Python),Boolean Expressions,Compound boolean expressions short circuit and and or return one of the elements in the expression Note that when None is returned the interpreter does not print anything, True and False False False or True
23、 True 7 and 14 14 None and 2 None or 2 2,Moving to Files,The interpreter is a good place to try out some code, but what you type is not reusable Files can be read into the interpreter using the import statement,If Statements,x = 22 if x 15 : print first clause elif x 25 : print second clause else :
24、print the else,In file ifstatement.py, import ifstatement second clause ,In interpreter,No Braces?,Python uses indentation instead of braces to determine the scope of expressions All lines must be indented the same amount to be part of the scope (or indented more if part of an inner scope) This forc
25、es the programmer to use proper indentation since the indenting is part of the program!,While Loops,x = 1 while x 10 : print x x = x + 1, import whileloop 1 2 3 4 5 6 7 8 9 ,In whileloop.py,In interpreter,Loop Control Statements,The Loop Else Clause,The optional else clause runs only if the loop exi
26、ts normally (not by break),x = 1 while x 3 : print x x = x + 1 else: print hello,: python whileelse.py 1 2 hello,Run from the command line,In whileelse.py,The Loop Else Clause,x = 1 while x 5 : print x x = x + 1 break else : print i got here,: python whileelse2.py 1,whileelse2.py,For Loops,Similar t
27、o perl forloops, iterating through a list of values Forloops also have the optional else clause,: python forloop.py 1 7 13 2,for x in 1,7,13,2 : print x,forloop.py,Function Basics,def max(x,y) : if x y : return x else : return y, import functionbasics max(3,5) 5 max(hello, there) there max(3, hello)
28、 hello,Function Not-So-Basics,Functions are first class objects Can be assigned to a variable Can be passed as a parameter Can be returned from a function Functions are treated like any other variable in python, the def statement simply assigns a function to a variable,Functions as Variables,Functio
29、ns are objects The same reference rules hold for them as for other objects, x = 10 x 10 def x () : . print hello x x() hello x = blah x blah,Functions: As Parameters,def foo(f, a) : return f(a) def bar(x) : retun x * x, from funcasparam import * foo(bar, 3) 9,The function foo takes two parameters an
30、d applies the first as a function with the second as its parameter,Functions: In Functions,Since they are like any other object, you can have functions inside functions,def foo (x,y) : def bar (z) : return z * 2 return bar(x) + y, from funcinfunc import * foo(2,3) 7,Functions Returning Functions,def
31、 foo (x) : def bar(y) : return x + y return bar # main f = foo(3) print f print f(2),: python funcreturnfunc.py 5,Parameters: Defaults,Can assign default values to parameters They are overridden if a parameter is given for them The type of the default doesnt limit the type of a parameter, def foo(x
32、= 3) : . print x . foo() 3 foo(10) 10 foo(hello) hello,Parameters: Named,Can specify the name of the parameter to set Any positional arguments must come before named ones in a call, def foo (a,b,c) : . print a, b, c . foo(c = 10, a = 2, b = 14) 2 14 10 foo(3, c = 2, b = 19) 3 19 2,Anonymous Function
33、s,The lambda returns a function The body can only be a simple expression, not complex statements, f = lambda x,y : x + y f(2,3) 5 l = one, lambda x : x * x, 3 l1(4) 16,Classes,A collection of data and methods that act on that data But in python functions are basically just data!,Class Syntax,Every m
34、ethod in a class takes a self-pointer as the first parameter (self as convention) like this in java or C+ _init_ is a builtin function that you override as the constructor, from classbasic import * x = myclass(3) x.printit() 3,class myclass : def _init_(self, val) : self.x = val def printit(self) :
35、print self.x,Class Method Calls,Self is automatically added as the first parameter when a method is called on an instance of a class Internally self must be explicitly passed,Class Inheritance,Super classes are listed in brackets after the name of the class Python allows multiple inheritance Name re
36、solution is bottom to top, left to right,Class Inheritance: Example, from classinherit import * x = c3() obj = c3() obj.z 2 obj.x 10 obj.y 15,class c1 : x = 10 class c2 : x = 20 y = 15 class c3(c1,c2) : z = 2,Explicit Call to a Super-class Method,class c2 (c1) : def _init_(self, x, y) : c1._init_(se
37、lf, x) self.y = y def foo(self) : c1.foo(self) print self.y,class c1 : def _init_(self, x) : self.x = x def foo(self) : print self.x, obj = c2(4,5) obj.foo() 4 5,Instance Variables,Created as they are assigned Referenced as self.,Classes as Objects,Classes exist as objects and contain all of there own variab
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 金融機(jī)構(gòu)貸款合同模板
- 舞臺桁架搭建協(xié)議
- 專業(yè)合同種植技術(shù)服務(wù)樣本
- 招標(biāo)文件標(biāo)準(zhǔn)范例
- 個(gè)人創(chuàng)業(yè)非固定員工保證書
- 保證書格式典范
- 廣告服務(wù)合同的履行標(biāo)準(zhǔn)
- 嫖娼問題自我反省書
- 買賣合同取消協(xié)議書
- 防雷工程合作協(xié)議范本
- 2024年華潤燃?xì)饧瘓F(tuán)招聘筆試參考題庫含答案解析
- 岸基維修協(xié)議
- (完整版)翻譯技巧翻譯方法
- 中醫(yī)護(hù)理技術(shù)操作平衡火罐技術(shù)操作流程與考核評分標(biāo)準(zhǔn)
- 2023年10月上海社會科學(xué)院工作人員招考聘用筆試歷年難易錯(cuò)點(diǎn)考題薈萃附帶答案詳解
- 《法理學(xué)》(第三版教材)形成性考核作業(yè)1234答案
- 植物的抗熱性
- 《人際關(guān)系與溝通技巧》(第3版)-教學(xué)大綱
- 2023年中醫(yī)養(yǎng)生之藥膳食療考試試題
- 某土石方施工工程主要施工機(jī)械設(shè)備表
- 硅PU(塑料面層)檢驗(yàn)批質(zhì)量驗(yàn)收記錄表
評論
0/150
提交評論