数据结构与算法 - Python基础

Similar documents
新・明解Python入門

Python a p p l e b e a r c Fruit Animal a p p l e b e a r c 2-2

C/C++ - 字符输入输出和字符确认

3.1 num = 3 ch = 'C' 2

WWW PHP

C/C++ - 字符串与字符串函数

Learn_Perl 3-02.pdf

C/C++ - 函数

C/C++语言 - C/C++数据

Spyder Anaconda Spyder Python Spyder Python Spyder Spyder Spyder 開始 \ 所有程式 \ Anaconda3 (64-bit) \ Spyder Spyder IPython Python IPython Sp

C/C++ - 文件IO

C/C++程序设计 - 字符串与格式化输入/输出

WWW PHP Comments Literals Identifiers Keywords Variables Constants Data Types Operators & Expressions 2

C/C++ 语言 - 循环

untitled

CHAPTER VC#

四川省普通高等学校

新・解きながら学ぶJava

Microsoft Word 軟體設計第二部份範例試題_C++_ _1_.doc

C/C++语言 - 运算符、表达式和语句

Microsoft Word - 第3章.doc

FY.DOC

CC213

電腦做什麼事~第七章

Java java.lang.math Java Java.util.Random : ArithmeticException int zero = 0; try { int i= 72 / zero ; }catch (ArithmeticException e ) { // } 0,

Microsoft PowerPoint - OPVB1基本VB.ppt

( CIP) /. :, ( ) ISBN TP CIP ( 2005) : : : : * : : 174 ( A ) : : ( 023) : ( 023)

CC213

02

第5章修改稿

(京)新登字063号

1 Framework.NET Framework Microsoft Windows.NET Framework.NET Framework NOTE.NET NET Framework.NET Framework 2.0 ( 3 ).NET Framework 2.0.NET F

Guide to Install SATA Hard Disks

PowerPoint プレゼンテーション

untitled

2013 C 1 #include <stdio.h> 2 int main(void) 3 { 4 int cases, i; 5 long long a, b; 6 scanf("%d", &cases); 7 for (i = 0; i < cases; i++) 8 { 9 scanf("%

C

蔡 氏 族 譜 序 2

Fun Time (1) What happens in memory? 1 i n t i ; 2 s h o r t j ; 3 double k ; 4 char c = a ; 5 i = 3; j = 2; 6 k = i j ; H.-T. Lin (NTU CSIE) Referenc

C/C++语言 - 分支结构

科学计算的语言-FORTRAN95

5. 閱 讀 下 文, 推 斷 內 最 適 合 填 入 的 詞 語 依 序 為 何? 人 也 真 是 一 個 絕 字, 一 邊 向 左, 一 邊 向 右, 一 副 的 樣 子, 偏 又 相 連 著, 各 說 各 話 各 走 各 路, 卻 又 人, 這 麼 一 個 簡 單 的 字, 竟 包 含 如 此

Tel: Fax: TTP-344M/246M /

電腦做什麼事~第六章

C

Microsoft Word - 09.數學 docx

, 7, Windows,,,, : ,,,, ;,, ( CIP) /,,. : ;, ( 21 ) ISBN : -. TP CIP ( 2005) 1

C C

Perl

Computer Architecture

(Microsoft Word - \251I\250D\245D\246W

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

《80后职场新鲜人生存手册》

Microsoft Word - 苹果脚本跟我学.doc

untitled

C/C++ - 数组与指针

ebook14-4

1 Project New Project 1 2 Windows 1 3 N C test Windows uv2 KEIL uvision2 1 2 New Project Ateml AT89C AT89C51 3 KEIL Demo C C File

(Guangzhou) AIT Co, Ltd V 110V [ ]! 2

(Microsoft Word - Motion Program \270\305\264\272\276\363 \307\245\301\366 \271\327 \270\361\302\367.doc)

Microsoft Word - PHP7Ch01.docx

untitled

Microsoft Word - 11.doc

Java

CHAPTER 1

CC213

Chapter 9: Objects and Classes

C 1

C H A P T E R 7 Windows Vista Windows Vista Windows Vista FAT16 FAT32 NTFS NTFS New Technology File System NTFS

EC51/52 GSM /GPRS MODEN

Serial ATA ( Silicon Image SiI3114)...2 (1) SATA... 2 (2) B I O S S A T A... 3 (3) RAID BIOS RAID... 5 (4) S A T A... 8 (5) S A T A... 10

epub 94-3

Bourne Shell及shell编程

AL-M200 Series

Microsoft Word - 把时间当作朋友(2011第3版)3.0.b.06.doc

JavaIO.PDF

(Load Project) (Save Project) (OffLine Mode) (Help) Intel Hex Motor

Untitiled

概述

前言 C# C# C# C C# C# C# C# C# microservices C# More Effective C# More Effective C# C# C# C# Effective C# 50 C# C# 7 Effective vii

Progperl.PDF

INTRODUCTION TO COM.DOC

通 用 申 请 填 写 流 程 简 图 首 次 登 陆 已 注 册 用 户 登 录 ( 最 终 提 交 前 可 无 限 次 登 录 修 改 ) 注 册 账 户 College Search 中 添 加 New York University Common App 填 写 ( 包 含 两 篇 写 作

z x / +/- < >< >< >< >< > 3 b10x b10x 0~9,a~f,A~F, 0~9,a~f,A~F, x,x,z,z,?,_ x,x,z,z,?,_ h H 0~9,_ 0~9,_ d D 0~7,x,X,z,Z

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

Simulator By SunLingxi 2003

Microsoft PowerPoint - STU_EC_Ch02.ppt

新版 明解C++入門編

2017ÅàÑø·½°¸

untitled

untitled

TX-NR3030_BAS_Cs_ indd

IO

0020 湖 北 美 术 学 院 戚 雪 雯 书 籍 遇 戴 萌 田 智 文 郭 岚 0021 湖 北 美 术 学 院 胡 星 书 籍 少 年 迈 尔 斯 的 海 戴 萌 田 智 文 郭 岚 0022 湖 北 美 术 学 院 曹 梦 萦 书 籍 古 琴 弹 奏 经 典 三 十 首 戴 萌 田 智 文

华南理工大学广州学院

audiogram3 Owners Manual

untitled

<4D F736F F D D342DA57CA7DEA447B14D2DA475B57BBB50BADEB27AC3FEB14DA447B8D5C344>

Important Notice SUNPLUS TECHNOLOGY CO. reserves the right to change this documentation without prior notice. Information provided by SUNPLUS TECHNOLO

安 全 指 南 : 必 须 遵 守 所 有 的 警 告 事 项, 以 确 保 自 己 和 他 人 的 安 全 以 及 保 护 产 品 和 连 接 装 置 这 些 警 告 事 项 都 按 警 示 程 度 明 示 出 等 级 有 资 格 的 人 员 : YO-YO 只 能 进 行 与 手 册 有 关 的

Transcription:

Python

教材及课件 课件及作业见网址 xpzhang.me 1

1. Python 2. 3. (list) (tuple) 4. (dict) (set) 5. 6. 7. 2

Python

Python

3

Python 4

Python 1, 100, -8080, 0,... 0x 0-9, a-f 0 xff00, 0 xa432bf 5

1.24, 3.14, -9.80,... 1.23 e9, 1.2e -6,... 6

" abc, " xyz ",... "" abc a, b, c 3 "" "I m OK" I,, m,, O, K 6 7

" \ I\ m \"OK\"! I m "OK "! 8

\ \n \t \\ \ print ("I\ ok.") print ("I\ m learning \ npython.") print ( \\\ n\\ ) 9

\ \n \t \\ \ print ("I\ ok.") print ("I\ m learning \ npython.") print ( \\\ n\\ ) I ok. I m learning Python. \ \ 9

\ Python r print ( \\\ n\\ ) print (r \\\ n\\ ) 10

\ Python r print ( \\\ n\\ ) print (r \\\ n\\ ) \ \ \\\ n \\\ 10

\n Python... print ( line1 line2 line3 ) print (r hello,\n world ) 11

\n Python... print ( line1 line2 line3 ) print (r hello,\n world ) line1 line2 line3 hello,\n world 11

Python True False print ( True ) print ( False ) print (3 > 2) print (3 > 5) True False True False 12

and, or, not print ( True and True ) print ( True and False ) print ( False and False ) print (5 > 3 and 1 > 3) True False False False print ( True or True ) print ( True or False ) print ( False or False ) print (5 > 3 or 1 > 3) True True False True print ( not True ) print ( not False ) print ( not 1 > 2) False True True 13

age = int ( input ( Enter your age : )) if age >= 18: print ( adult ) else : print ( teenager ) 14

age = int ( input ( Enter your age : )) if age >= 18: print ( adult ) else : print ( teenager ) Enter your age : 14 teenager Enter your age : 24 adult 14

Python None None 0 0 None 15

Python

n = 1 n a = 1.0 a str = Hello world! str answer = True answer 16

Python = a = 123 print (a, type (a)) a = 3. 14 print (a, type (a)) a = ABC print (a, type (a)) a = 5 > 3 or 2 < 1 print (a, type (a)) 123 <class int > 3.14 <class float > ABC <class str > True <class bool > 17

C int a = 123; // a is an integer type variable a = " ABC "; // error : cannot assign string to a. 18

a = ABC Python ABC a ABC 19

a b b a a = ABC b = a a = XYZ print (b) 20

a b b a a = ABC b = a a = XYZ print (b) ABC 20

a = ABC ABC a a ABC. b = a b b a ABC. a = XYZ XYZ a ABC b. 21

Python

Python PI = 3. 1415926 PI Python PI PI 22

Python

Python /: print ( 10/ 3) 3. 3333333333333335 / print (9/3) 3.0 23

// print (9//3) print (10//3) 3 3 // // 24

Python : print (10 % 3) 1 25

8 bit byte byte 2 8 1 = 255 2 16 1 = 65535 4 2 32 1 = 4294967295 26

127 ( ) ASCII A 65 z 122 27

127 ( ) ASCII A 65 z 122 ASCII GB2312 27

127 ( ) ASCII A 65 z 122 ASCII GB2312 Shift_JIS Euc-kr 27

127 ( ) ASCII A 65 z 122 ASCII GB2312 Shift_JIS Euc-kr Unicode 27

Unicode Unicode ASCII Unicode ASCII 1 Unicode 2 A ASCII 65 01000001 0 ASCII 48 00110000 0 0 ASCII Unicode 20013 01001110 00101101 ASCII A Unicode 0 A Unicode 00000000 01000001 28

Unicode Unicode ASCII 29

Unicode Unicode ASCII Unicode UTF-8 UTF-8 UTF-8 Unicode 1-6 1 3 4-6 29

UTF-8 ASCII Unicode UTF-8 A 01000001 00000000 01000001 01000001 01001110 00101101 11100100 10111000 10101101 UTF-8 ASCII UTF-8 ASCII UTF-8 30

ASCII Unicode UTF-8 Unicode UTF-8 UTF-8 Unicode Unicode UTF-8 31

Python

Python Python 3 Unicode Python print ( string ) string 32

Python Python ord() chr() print ( ord ( A )) print ( ord ( )) print ( chr (66) ) print ( chr (25991) ) 65 20013 B 33

Python Python ord() chr() print ( ord ( A )) print ( ord ( )) print ( chr (66) ) print ( chr (25991) ) 65 20013 B print ( \ u4e2d \ u6587 ) 33

Python Python r b f 34

b Python Unicode str bytes Python bytes b x = b ABC ABC b ABC str bytes print ( type ( ABC )) print ( type (b ABC )) <class str > <class bytes > 35

b Unicode str encode() bytes >>> ABC. encode ( utf -8 ) b ABC >>> ABC. encode ( ascii ) b ABC >>>. encode ( utf -8 ) b \ xe4 \ xb8 \ xad \ xe6 \ x96 \ x87 >>>. encode ( ascii ) Traceback ( most recent call last ): File " <stdin >", line 1, in <module > UnicodeEncodeError : ascii codec can t encode characters in position 0-1: ordinal not in range (128) str bytes UTF-8 ASCII str UTF-8 bytes ASCII ASCII Python 36

b bytes bytes str decode() >>> b ABC. decode ( ascii ) ABC >>> b \ xe4 \ xb8 \ xad \ xe6 \ x96 \ x87. decode ( utf -8 ) 37

b bytes decode() >>> b \ xe4 \ xb8 \ xad \ xff. decode ( utf -8 ) Traceback ( most recent call last ):... UnicodeDecodeError : utf -8 codec can t decode byte 0 xff in position 3: invalid start byte bytes errors= ignore >>> b \ xe4 \ xb8 \ xad \ xff. decode ( utf -8, errors = ignore ) 38

b str len() >>> len ( ABC ) 3 >>> len ( ) 2 bytes len() >>> len (b ABC ) 3 >>> len (. encode ( utf -8 )) 6 1 UTF-8 3 1 1 39

b str bytes UTF-8 str bytes Python UTF-8 Python UTF-8 #!/ usr / bin / env python3 # -*- coding : utf -8 -*- Linux/OS X Python Windows Python UTF-8 40

%-formatting Python OG(original generation) python C print ( Hello, %s! % world ) name = Ming age = 23 print ( Hello, %s. You are %s. % (name, age )) 41

%-formatting Python OG(original generation) python C print ( Hello, %s! % world ) name = Ming age = 23 print ( Hello, %s. You are %s. % (name, age )) Hello, world! Hello, Ming. You are 23. 41

%-formatting 1: %d %f %s %x 42

%-formatting print ( %3d -%03 d % (22, 11) ) print ( %.3 f %8.3 e % (3.1415926, 4000.21) ) 43

%-formatting %-formatting first = Ming last = Li age = 23 profession = student affiliation = WHU print ( Hello, %s %s. You are %s. You are a %s. You are a member of % s. % ( first, last, age, profession, affiliation )) 44

%-formatting %-formatting first = Ming last = Li age = 23 profession = student affiliation = WHU print ( Hello, %s %s. You are %s. You are a %s. You are a member of % s. % ( first, last, age, profession, affiliation )) Hello, Ming Li. You are 23. You are a student. You are a member of WHU. % 44

str.format() Python 2.6 str.format() %-formatting format () str.format() name = Ming age = 23 print ( Hello, {}. You are {}.. format (name, age ) ) Hello, Ming. You are 23. 45

str.format() name = Ming age = 23 print ( Hello, {1}. You are {0}.. format (age, name )) Hello, Ming. You are 23. 46

str.format() person = { name : Ming, age : 23} print ( Hello, { name }. You are { age }.. format ( name = person [ name ], age = person [ age ])) Hello, Ming. You are 23. 47

str.format() ** person = { name : Ming, age : 23} print ( Hello, { name }. You are { age }.. format (** person )) Hello, Ming. You are 23. str.format() %-formatting str.format() 48

f f Python 3.6 name = Ming age = 23 print (f Hello, { name }. You are { age }. ) print (F Hello, { name }. You are { age }. ) Hello, Ming. You are 23. Hello, Ming. You are 23. f Python 49

f print (f {2 * 37} ) 74 name = Ming print (f { name. lower ()} is funny. ) ming is funny. 50

f f class Student : def init (self, first, last, age ): self. first = first self. last = last self. age = age def str ( self ): return f { self. first } { self. last } is { self. age }. def repr ( self ): return f { self. first } { self. last } is { self. age }. Surprise! std = Student ( Ming, Li, 23) print (f { std } ) print (f { std!r} ) Ming Li is 23. Ming Li is 23. Surprise! 51

f f name, profession, affiliation = Ming, student, WHU msg1 = (f"hi { name }. " f" You are a { profession }. " f" You were in { affiliation }.") msg2 = (f"hi { name }. " " You are a { profession }. " " You were in { affiliation }.") msg3 = f """ Hi { name }. You are a { profession }. You were in { affiliation }. """ print ( msg1 ) print ( msg2 ) print ( msg3 ) 52

f Hi Ming. You are a student. You were in WHU. Hi Ming. You are a { profession }. You were in { affiliation }. Hi Ming. You are a student. You were in WHU. 53

(list) (tuple)

(list) (tuple)

Python courses = [ math, phys, chem ] print ( courses )

Python courses = [ math, phys, chem ] print ( courses ) [ math, phys, chem ] 54

len() print ( len ( courses )) 3 0 print ( courses [0]) print ( courses [1]) print ( courses [2]) print ( courses [3]) 55

len() print ( len ( courses )) 3 0 print ( courses [0]) print ( courses [1]) print ( courses [2]) print ( courses [3]) math phys chem Traceback ( most recent call last ): File " list. py", line 5, in <module > print ( courses [3]) IndexError : list index out of range Python IndexError len(classmates)-1 55

1 2 2 print ( courses [ -1]) print ( courses [ -2]) print ( courses [ -3]) # print ( courses [ -4]) 56

1 2 2 print ( courses [ -1]) print ( courses [ -2]) print ( courses [ -3]) # print ( courses [ -4]) chem phys math Traceback ( most recent call last ): File " list.py", line 5, in <module > print ( courses [ -4]) IndexError : list index out of range 56

append() courses. append ( biology ) print ( courses ) [ math, phys, chem, biology ] insert() courses. insert (1, history ) print ( courses ) [ math, history, phys, chem, biology ] 57

pop() courses. pop () print ( courses ) [ math, history, phys, chem ] pop(i) i courses. pop (1) print ( courses ) [ math, phys, chem ] 58

courses [1] = chinese print ( courses ) [ math, chinese, chem ] 59

1. list1 = [ Apple, 123, 3.14, True ] 2. list2 = [ python, java, [ c, c++, c# ], matlab ] 3. list3 = [] # or list3 = list () 60

(list) (tuple) (tuple)

(tuple) Python tuple list tuple courses = ( math, phys, chem ) courses tuple append(), insert() list courses[0], courses[-1] 61

(tuple) tuple tuple tuple list tuple tuple tuple1 = (1, 2) tuple2 = 1, 2 tuple3 = () tuple4 = (1, ) 62

(tuple) tuple t = (1) tuple 1 () tuple Python 1 tuple,: tuple4 = (1, ) 63

(tuple) tuple t = ( a, b, [ A, B ]) print (t) t [2][0] = X t [2][1] = Y print (t) ( a, b, [ A, B ]) ( a, b, [ X, Y ]) t a, b 64

(tuple) tuple tuple list tuple list list tuple tuple a b list list 65

(dict) (set)

(dict) (set)

Python (dict) map - (key-value pair) list list: courses = [ math, phys, chem ] scores = [95, 90, 85] courses scores list 66

dict - info = { math : 95, phys : 90, chem : 85} print ( info [ math ]) 95 67

1. dict key info [ chinese ] = 88 print ( info [ chinese ]) 88 2. key value key value info [ chinese ] = 94 print ( info [ chinese ]) 94 68

3 key dict # print ( info [ history ]) Traceback ( most recent call last ): File " dict1.py", line 10, in <module > print (d[ history ]) KeyError : history 69

4 key : in key print ( history in info ) False dict get() key None value: print ( info. get ( history )) print ( info. get ( history, -1)) None -1 70

5 key pop(key) value dict info. pop ( chem ) print ( info ) { math : 95, phys : 90, chinese : 94} 5 dict key dict 71

list dict key list 72

dict Python dict dict key dict key value key dict key Hash 73

hash key Python key list key d = {} print (d) key = [1, 2, 3] d[ key ] = a list {} Traceback ( most recent call last ): File " dict2.py", line 5, in <module > d[ key ] = a list TypeError : unhashable type : list 74

(dict) (set) (set)

(set) set dict key value key set key 1. set s1 = {1, 2, 3} print ( type (s1)) print (s1) <class set > {1, 2, 3} list s2 = set ([1, 2, 3]) print ( type (s2)) print (s2) <class set > {1, 2, 3} 75

(set) 2 set s3 = {1, 1, 2, 2, 3, 3} print (s3) {1, 2, 3} 3 add(key) set s3.add (4) print (s3) s3.add (4) print (s3) {1, 2, 3, 4} {1, 2, 3, 4} 76

(set) 4 remove(key) s3. remove (4) print (s3) {1, 2, 3} 5 set set s1 = {1, 2, 3} s2 = set ([2, 3, 4]) print (s1 & s2) print (s1 s2) {2, 3} {1, 2, 3, 4} 77

(set) set dict value set dict set 78

(dict) (set)

str list list a = [ c, b, a ] print (a) a. sort () print (a) [ c, b, a ] [ a, b, c ] 79

str list list a = [ c, b, a ] print (a) a. sort () print (a) [ c, b, a ] [ a, b, c ] str a = abc print (a. replace ( a, A )) print (a) Abc abc 79

a abc a abc a abc 80

a abc a abc a abc a.replace( a, A ) replace abc replace abc replace Abc b a abc b Abc 80

if

if if condition : statements : age = 20 if age >= 18: print (f your age is { age } ) print ( adult ) your age is 20 adult 81

if Python if True print 82

if... else...

if... else... if condition : statements1 else : statements2 83

if... else... : age = 12 if age >= 18: print (f your age is { age } ) print ( adult ) else : print (f your age is { age } ) print ( teenager ) your age is 12 teenager 84

if... elif... else...

if... elif... else... if condition1 : statements1 elif condition2 : statements2 elif condition3 : statements3 else : statements4 85

if... elif... else... : age = 12 if age >= 18: print ( adult ) elif age >= 6: print ( teenager ) else : print ( kid ) teenager 86

if... elif... else... if True elif else. age = 20 if age >= 6: print ( teenager ) elif age >= 18: print ( adult ) else : print ( kid )

if... elif... else... if True elif else. age = 20 if age >= 6: print ( teenager ) elif age >= 18: print ( adult ) else : print ( kid ) if if x: print ( True ) 87

input

input age = input ( Enter your age : ) if age >= 18: print ( adult ) elif age >= 6: print ( teenager ) else : print ( kid ) 20 Enter your age : 20 Traceback ( most recent call last ): File " input. py", line 2, in <module > if age >= 18: TypeError : >= not supported between instances of str and int input() str str int str int 88

input age = int ( input ( Enter your age : )) if age >= 18: print ( adult ) elif age >= 6: print ( teenager ) else : print ( kid ) Enter your age : 20 adult 89

Python for... in while 90

for... in

for... in for... in list tuple : animals = [ dog, cat, monkey, pig ] for animial in animals : print ( animial ) print () for i, animial in enumerate ( animals ): print (i, animial ) dog cat monkey pig 0 dog 1 cat 2 monkey 3 pig 91

for... in : 1-100 sum = 0 for x in range ( 101) : sum += x print ( sum ) 5050 92

while

while : 1000 sum = 0 n = 99 while n > 0: sum += n n -= 2 print ( sum ) 2500 93

break

break break : print ( ==================== ) print ( a. apple b. banana ) print ( o. orange q. quit ) print ( ==================== ) while True : letter = input ( Enter a, b, o and q: ) if letter == a : print ( apple ) elif letter == b : print ( banana ) elif letter == o : print ( orange ) elif letter == q : break print (" Exit!") 94

break === ================= a. apple b. banana o. orange q. quit === ================= Enter a, b, o and q: a apple Enter a, b, o and q: b banana Enter a, b, o and q: o orange Enter a, b, o and q: q Exit! 95

continue

continue continue : 100 sum = 0 for i in range ( 100) : if i % 2 == 0: continue sum += i print ( sum ) 2500 96

Python : print ( abs (1000) ) print ( abs ( -20) ) print ( abs (12.34) ) # print ( abs ( a )) print ( max (1, 2)) print ( max (2, 3, -1, 5)) print ( max ([1, 2]) ) print ( max ((2, 3, -1, 5))) 1000 20 12.34 2 5 2 5 97

Python : print ( int ( 123 )) print ( int (12.34) ) print ( float ( 12.34 )) print ( str (1.23) ) print ( str (100) ) print ( bool (1) ) print ( bool ( )) 123 12 12.34 1.23 100 True False 98

: print ( hex (255) ) print ( hex (1000) ) print ( oct (255) ) print ( oct (1000) ) print ( bin (255) ) print ( bin (1000) ) 0 xff 0 x3e8 0 o377 0 o1750 0 b11111111 0 b1111101000 99

a = abs print (a( -1)) 1 100

Python def : return 101

Python def : return : my_abs() def my_abs (x): if x >= 0: return x else : return -x if name == main : print ( my_abs ( -1)) 1 101

: my_abs() my_functions.py from my_functions import my_abs my_abs() my_functions.py from my_ functions import my_ abs print ( my_abs ( -20) ) 20 102

pass def empty (): pass 103

pass def empty (): pass pass 103

pass def empty (): pass pass pass pass 103

pass def empty (): pass pass pass pass pass if age >= 18: pass pass 103

Python TypeError >>> my_abs (1, 2) Traceback ( most recent call last ): File "<stdin >", line 1, in <module > TypeError : my_ abs () takes 1 positional argument but 2 were given Python 104

my_abs abs >>> my_abs ( A ) Traceback ( most recent call last ): File "<stdin >", line 1, in <module > File "<stdin >", line 2, in my_abs TypeError : unorderable types : str () >= int () >>> abs ( A ) Traceback ( most recent call last ): File "<stdin >", line 1, in <module > TypeError : bad operand type for abs (): str abs my_abs if abs 105

my_abs isinstance() def my_abs (x): if not isinstance (x, ( int, float )): raise TypeError ( bad operand type ) if x >= 0: return x else : return -x if name == main : print ( my_abs ( -1)) print ( my_abs ( A )) 106

my_abs isinstance() def my_abs (x): if not isinstance (x, ( int, float )): raise TypeError ( bad operand type ) if x >= 0: return x else : return -x if name == main : print ( my_abs ( -1)) print ( my_abs ( A )) 1 Traceback ( most recent call last ): File " src / slide01 / code / my_abs1.py", line 11, in <module > print ( my_abs ( A )) File " src / slide01 / code / my_abs1.py", line 3, in my_abs raise TypeError ( bad operand type ) TypeError : bad operand type 106

Python : (x,y) import math def move (x, y, step, angle =0) : nx = x + step * math. cos ( angle ) ny = y - step * math. sin ( angle ) return nx, ny if name == main : x, y = 100, 100 step = 60 angle = math. pi / 6 x_new, y_new = move (x, y, step, angle ) print (f"{ x_new :.3 f}, { y_new :.3 f}") 151.962, 70.000 107

import math math math sin cos tuple tuple 108

Python 109

: x 2. def power (x): return x * x print ( power (5) ) print ( power (15) ) 25 225

: x 2. def power (x): return x * x print ( power (5) ) print ( power (15) ) 25 225 power() x x 110

x 3 power3() x 4,x 5, : x n. def power (x, n): s = 1 while n > 0: n -= 1 s *= x return s 25 125 print ( power (5, 2)) print ( power (5, 3)) power(x, n) x n x n 111

power(x, n) >>> power (5) Traceback ( most recent call last ): File "<stdin >", line 1, in <module > TypeError : power () missing 1 required positional argument : n power() n 112

x 2 n 2 : x n. def power (x, n =2) : s = 1 while n > 0: n -= 1 s *= x return s 25 25 print ( power (5) ) print ( power (5, 2)) power(5) power(5, 2) n 2 power(5, 3) 113

1. Python 2. 114

: name gender def enroll (name, gender ): print (f" name : { name }") print (f" gender : { gender }") enroll ( Sarah, F ) name : Sarah gender : F 115

: def enroll (name, gender, age =6, city = Wuhan ): print (f" name : { name }, gender : { gender }, age : { age }, city : { city }") enroll ( Sarah, F ) enroll ( Bob, M, 7 ) enroll ( Adam, F, city = Beijing ) name : Sarah, gender : F, age : 6, city : Wuhan name : Bob, gender : M, age : 7, city : Wuhan name : Adam, gender : F, age : 6, city : Beijing 116

117

enroll( Bob, M, 7) name gender age city enroll( Adam, M, city= Beijing ) city 118

Python 1 2 0 119

Python 1 2 0 : a,b,c, a 2 +b 2 +c 2 + a,b,c, list tuple def calc ( numbers ): sum = 0 for n in numbers : sum += n* n return sum 30 84 print ( calc ([1, 2, 3, 4]) ) print ( calc ((1, 3, 5, 7))) list tuple 119

: def calc (* numbers ): sum = 0 for n in numbers : sum += n* n return sum print ( calc (1, 2, 3, 4)) print ( calc (1, 3, 5, 7)) print ( calc ()) 30 84 0

: def calc (* numbers ): sum = 0 for n in numbers : sum += n* n return sum print ( calc (1, 2, 3, 4)) print ( calc (1, 3, 5, 7)) print ( calc ()) 30 84 0 * numbers tuple 0 120

list tuple nums = [1, 2, 3] print ( calc ( nums [0], nums [1], nums [2]) ) 121

list tuple nums = [1, 2, 3] print ( calc ( nums [0], nums [1], nums [2]) ) Python list tuple * list tuple print ( calc (* nums )) 121

0 tuple 0 dict 122

0 tuple 0 dict def person (name, age, ** kw): print (f" name : { name }, age : { age }, other : {kw}") person ( Michael, 30) person ( Bob, 35, city = Wuhan ) person ( Sarah, 22, gender = F, city = Beijing ) 122

0 tuple 0 dict def person (name, age, ** kw): print (f" name : { name }, age : { age }, other : {kw}") person ( Michael, 30) person ( Bob, 35, city = Wuhan ) person ( Sarah, 22, gender = F, city = Beijing ) name : Michael, age : 30, other : {} name : Bob, age : 35, other : { city : Wuhan } name : Sarah, age : 22, other : { gender : F, city : Beijing } 122

person() name age kw person ( Michael, 30) person ( Bob, 35, city = Beijing ) person ( Adam, 45, gender = M, job = Engineer ) 123

person() name age 124

dict dict extra = { city : Beijing, job : Engineer } person ( Jack, 24, ** extra ) name : Jack, age : 24, other : { city : Beijing, job : Engineer } **extra extra dict key-value **kw kw dict kw dict extra kw extra 125

126

: gender city def person (name, age, *, gender, city ): print (f" name : { name }, age : { age }, gender : { gender }, city : { city }") person ( Sarah, 22, gender = F, city = Beijing ) name : Sarah, age : 22, gender : F, city : Beijing 126

: gender city def person (name, age, *, gender, city ): print (f" name : { name }, age : { age }, gender : { gender }, city : { city }") person ( Sarah, 22, gender = F, city = Beijing ) name : Sarah, age : 22, gender : F, city : Beijing **kw * * 126

* def person (name, age, *args, gender, city ): print (f" name : { name }, age : { age }, args : { args }, gender : { gender }, city : { city }") person ( Sarah, 22, Engineer, gender = F, city = Beijing ) name : Sarah, age : 22, args : ( Engineer,), gender : F, city : Beijing 127

def person (name, age, *, gender = M, city ): print (f" name : { name }, age : { age }, gender : { gender }, city : { city }") person ( Sarah, 22, city = Beijing ) name : Sarah, age : 22, gender : M, city : Beijing 128

Python 5 : def f1(a, b, c=0, *args, ** kw): print (f a = {a}, b = {b}, c = {c}, args : { args }, kw: { kw} ) def f2(a, b, c=0, *, d, ** kw): print (f a = {a}, b = {b}, c = {c}, d: {d}, kw: {kw} ) 129

Python f1 (1, 2) f1 (1, 2, c =3) f1 (1, 2, 3, a, b, x =99) f1 (1, 2, d=99, ext = None ) a = 1, b = 2, c = 0, args : (), kw: {} a = 1, b = 2, c = 3, args : (), kw: {} a = 1, b = 2, c = 3, args : ( a, b ), kw: { x : 99} a = 1, b = 2, c = 0, args : (), kw: { d : 99, ext : None } tuple dict args = (1, 2, 3, 4) kw = { d : 99, x : # } f1 (* args, ** kw) args = (11, 22, 33) kw = { d : 44, x : ## } f2 (* args, ** kw) 130

func(*args, **kw) 131