Python 基礎教學

7f110257501127300df3f923119ba043?s=47 Inndy
November 02, 2015

Python 基礎教學

這份投影片適用的對象是已經具有基礎程式能力,至少熟悉一門程式語言的人,所有的程式都採用 Python 3

7f110257501127300df3f923119ba043?s=128

Inndy

November 02, 2015
Tweet

Transcript

  1. #BTJD1ZUIPO NTUST Coding Club — Inndy

  2. 㛇劥Ꟛ涮橇㞯 ˙⯝顥箁♳Ꟛ涮橇㞯IUUQTDJP ˙♳铭涸湱ꡠ须俲IUUQTKNQODDBEWQZ ˙*1ZUIPOIUUQTJQZUIPOPSH

  3. 簮䱖莅玑䒭⼦㝆 a = input("a: ") if int(a) == 1: print("A

    is 1") else: print("A is not 1") 3
  4. 簮䱖莅玑䒭⼦㝆 • Ӟ㮆婘矎դ蔭Ӟ㮆纷ୗ玟璸 • 磪ٛ蒈磪婘矎 • 磪ٛ蒈಍磪婘矎牧犋胼㫂婘矎 • ೲ Tab

    • Python 秂伛傶ࢥ㮆܎୵绚ጮ牧IDLE䨝䒻֦旉矦 • if, for, while, with, class, def, try ...etc. 4
  5. a = input("a: ") if int(a) == 1: print("A is

    1") else: print("A is not 1") 5
  6. a = input("a: ") if int(a) == 1: print("A is

    1") else: print("A is not 1") 6
  7. a = input("a: ") if int(a) == 1: print("A is

    1") else: print("A is not 1") ग़訏ጱ婘矎牫 7
  8. a = input("a: ") if int(a) == 1: print("A is

    1") else: print("A is not 1") ग़訏ጱ婘矎牫 8
  9. ⴅ䒭EFG 碍䋊獢碍物 Python獢ୗ物 def f(x, y): res = x *

    3 res += 5 * y ** 2 return res f (x, y) = 3x + 5y2 9
  10. ⴅ䒭EFG def 獢ୗݷ圸(㷢碍1, 㷢碍2, …): # 獢ୗ獉਻ return Something 10

  11. ⴅ䒭EFG • 蜍獈虻碘牧螀ᓒҁ牧蜍ڊ奾ຎ҂ • 犖ݢ犥犋ࢧ㯽 • ᯿蕦ጱ纷ୗ䌃౮獢ୗ牧ݢ犥᯿蕦ڥአ牧ො׎狕硬 • 犋ٚ襑ᥝک蒂蕦蕣揳Ӥ 11

  12. def add(x, y): result = x + y return result

    result = add(5, 6) print(result) 12
  13. def add(x, y): result = x + y return result

    result = add(5, 6) print(result) ࢥ㮆܎୵绚ጮ 13
  14. ⴅ䒭EFG箻绢 1. 旉౮碍ਁ୵眲ҁint҂ 2. ፘ仂஑کଙ请ҁA - B҂ 3. ࢧ㯽奾ຎҁreturn҂ 14

    def YearToAge(birth): .... 箻绢㻨♧ⴅ䒭鱒Ⰵⴀ欰䎃⟨銯⯋䎃⚛㔐⫄䎃룲 塅ֺ蜍ڊ物 ڊኞଙ犩ҁᥜزଙ҂物1995 ֦犡ଙ 19 䵇ԧ
  15. JGⴼ倬哭⟝ if 礿կ1: # 纷ୗ粙ྦྷ 1 elif 礿կ2: # 纷ୗ粙ྦྷ

    2 # else-if ݢ犥盄ग़㮆 # ౲ᘏ䷱磪 elif 礿կ3: # 纷ୗ粙ྦྷ 3 else: # ইຎ獮ᶎӣ殻礿կ᮷犋ᒧݳ 15
  16. JGⴼ倬哭⟝ a = input("Input a number:") a = int(a) if

    a > 5: print("a is bigger than 5") print("First branch") elif a < 3: print("a is smaller than 3") a = a + 5 else: print("a is between 3 and 5") print("a = ", a) 16
  17. JGⴼ倬哭⟝ a = input("Input a number:") a = int(a) if

    a > 5: print("a is bigger than 5") print("First branch") elif a < 3: print("a is smaller than 3") a = a + 5 else: print("a is between 3 and 5") print("a = ", a) 17
  18. JG哭⟝ⴼ倬箻绢 ˙ 锞鱒Ⰵⴀ欰䎃⟨銯⯋䎃⚛⚂ⴼ倬僽や䧭䎃 ˙ ⢪欽ⶍⶍ涸:FBS5P"HFⴅ䒭 18 塅ֺ蜍ڊ物 ڊኞଙ犩ҁᥜزଙ҂物1995 ֦౮ଙԧ 塅ֺ蜍ڊ物

    ڊኞଙ犩ҁᥜزଙ҂物1999 ֦蝡㮆ੜ疵਎
  19. GPS鶬㕖 19 for i in iterable: print(i)

  20. JUFSBCMF ݢ犥ᤩ吚֢iteratorֵአጱ 20

  21. ➊랃僽JUFSBUPS 21

  22. 22 22 ➊랃僽JUFSBUPS

  23. 23 23 ➊랃僽JUFSBUPS

  24. 24 24 ➊랃僽JUFSBUPS

  25. 25 25 ➊랃僽JUFSBUPS

  26. ➊랃僽JUFSBUPS 26 26

  27. ➊랃僽JUFSBUPS 27 27

  28. Ջ讕ฎiterator牫 28 28 JUFSBUPS

  29. Ջ讕ฎiterator牫 • ℂ਻瑊獉瞟ڊྯӞ㮆زᔰጱૡٍ • ℂፋৼ獉ጱᒫӞ㮆ᇔߝ蚎ک磧盅Ӟ㮆ᇔߝ • 犋஠橕ஞፋৼ愊ᶎ裾Ջ讕䰬ৼ 29

  30. for 蝅瑹 30 for i in [1, 3, 5]: print(i)

    1 3 5
  31. for 蝅瑹 31 for i in [1, 3, 5]: print(i)

    1 3 5 list
  32. for 蝅瑹 32 for i in "ASD": print(i) A S

    D
  33. for 蝅瑹 33 for i in range(1, 4): print(i) 1

    2 3
  34. for 蝅瑹 34 for i in range(1, 10, 3): print(i)

    1 4 7
  35. for 蝅瑹 35 sum = 0 for i in range(1,

    11): sum += i print(sum)
  36. GPS鶬㕖  data = "" for i in range(40, 60):

    data += chr(i) print(data) print(ord("A"))
  37. range獢ୗ 37 range(stop) # ۱珀 start ֕犋۱珀 stop range(start, stop)

    range(start, stop, step) # Example range(3) # [0, 1, 2] range(1, 4) # [1, 2, 3] range(8, 2, -2) # [8, 6, 4] range(3, 0, -1) # [3, 2, 1]
  38. GPS SBOHF竸ざ箻绢 • 懯ᓒ 1 + 5 + 9 +

    13 + 17 + … + 9997 ԏ者޾ • 懯ᓒ 100! % 123456789012345 ҁ褩犔҂ • 懯ᓒ 12 + 22 + 32 + 42 + … + 1002 38 sum = 0 for i in range(1, 11): sum += i print(sum)
  39. ⳯讍鶋㺙岁  mode = input("1 = ےੂ 2 = 薹ੂ物")

    data = input("蜍獈ᥝےੂጱ虻碘物") output = "" # 伛猋አ㬵硯奾ຎ for i in data: # 玲ڊ蜍獈ጱྯӞ㮆ਁ n = ord(i) # 旉矦౮ ASCII 嘨 if mode == "1": n = n + 5 # ےੂ else: n = n - 5 # 薹ੂ c = chr(n) # ℂ ASCII 旉ࢧਁԀ output += c # ಩ےੂ / 薹ੂਠጱਁԀ蚏㬵 print(output)
  40. 鶬㕖涸䱾ⵖ • break 泷ӤӾ䥁蝅瑹 • continue 泷Ӥ᪡کӥӞ稞䁆ᤈ • else ইຎ蝅瑹䁆ᤈਠԧ䷱磪ᤩ

    break 
  41. 鶬㕖涸䱾ⵖ  for i in range(10): if i % 2

    == 0: continue print(i)
  42. 㼦䪪_涸颶侸  颶侸 ꤑ✫莅荈䊹尝剤Ⱖ➮姻侮侸涸㔔侸

  43. 㼦䪪_涸颶侸 ˙ 睨岁增叆僽やⰨ剤Ⱖ➮㔔侸 ˙ O  O佖葻睨岁涸眕㕠 ˙ 4JFWFPG&SBUPTUIFOFT⿾麕⢵⨞涸睨岁 ˙

    鼩剤Ⱖ➮刿㢵刿隶䢀刿醳꧹涸倰岁 
  44. 㼦䪪_涸颶侸  for i in range(2, 100 + 1): for

    j in range(2, i): if i % j == 0: break else: # ইຎ䷱磪ᤩbreak print(i, "is prime.")
  45. 8IJMF鶬㕖 • 犖ฎӞ圵蝅瑹 • ݝᥝ瞲ਧጱ礿կ౮缏疰Ӟፗ䁆ᤈ • while {condition}:
 do_some_thing("this")
 and_some_thing("that",

    3, 4, 5) 
  46. 8IJMF鶬㕖  i = 10 m = 1 while i

    > 1: m *= i i -= 1 print(m)
  47. # 娞聜物糔碍ਁ蝿瞁 http://j.mp/py-guess-num from random import randint r = randint(1,

    10) print("I have a random number: ", r) secret = _______(1, 100) # 㫂碍 _____ True: # 蝅瑹 guess = input("Guess a number:") guess = ___(_____) # ਁԀ牫碍ਁ牫 if _____ __ ______: # 糔䌘ԧ牫 print("You got it!") _____ # 蝿瞁奾๳ elif _____ _ ______: # ইຎ糔ॡय़ԧ print("Lower please.") else: print("Bigger and bigger.")
  48. -JTU ˙ 겳⡂"SSBZ ˙ 䖎㢵匌銯佞㖈♧饱꧌⚥盘椚 ˙ 嫦⦐匌銯鿪剤♧⦐管贫*OEFY ˙ 䖰Ꟛ㨥鼹 

  49. -JTU • empty_list = [] • nums = [1,2,3,4,5,6] #

    nums[0] == 1 • nums[0] = 9 • nums.append(7) • nums += [8, 9, 10] • print(nums[2:5]) • data = [1,[2,3,4],5] 
  50. -JTU  a = [1, 2, 3, 4, 5] #

    List for num in a: print(num) print("a[2] is", a[2]) a.append(333) print(a)
  51. -JTU  a = [4, 6, 3, 9, 1] a.sort()

    print(a)
  52. -JTU • min • max • sorted • reversed •

    sum 
  53. -JTU  䒊用♧⦐MJTU〭⨞QSJNFT ⚛⚂㖈酭꬗佞_涸颶侸 搭䖕⽫ⴀ痧_⦐颶侸 #FTNBSU锞♶銴QSJNFT<    >

  54. 0099(BNF  http://j.mp/py-ooxx-game

  55. 㥶卓⡹銴-JTU剤_䙦랃⨞ 䖎矦㋲㉇欽GPS 

  56. 56 a = [] for i in range(1, 11): a.append(i)

    欽GPS鶬㕖
  57.  a = [ i for i in range(1, 11)

    ] -JTU$PNQSFIFOTJPO
  58.  a = list(range(1, 11)) 85' 

  59. 銴-JTU剤_䙦랃⨞ 䖎矦㋲㉇欽GPS 

  60. 60 a = [] for i in range(1, 11): a.append(i

    ** 2) 欽GPS鶬㕖
  61.  a = [i ** 2 for i in range(1,

    11)] -JTU$PNQSFIFOTJPO
  62. -JTU$PNQSFIFOTJPO  [ {expr} for i in {iter} ] [

    {expr} for i in {iter} if {cond} ]
  63. -JTU$PNQSFIFOTJPO  a = [ i * 2 for i

    in range(5) ] # [0, 2, 4, 6, 8]
  64. -JTU$PNQSFIFOTJPO  b = [i for i in range(8) if

    i % 2 == 1] # [1, 3, 5, 7]
  65. -JTU$PNQSFIFOTJPO  箻绢 ⴪ⴀ    ⴪ⴀ  

  66.  print([ n for n in range(2, 100) if not

    any( n % i == 0 for i in range(2, n) ) ]) -JTU$PNQSFIFOTJPO
  67.  print([ n for n in range(2, 100) if not

    any( n % i == 0 for i in range(2, n) ) ]) -JTU$PNQSFIFOTJPO FYQSFTTJPO GPS DPOEJUJPO
  68.  print([ n for n in range(2, 100) if not

    any( n % i == 0 for i in range(2, n) ) ]) -JTU$PNQSFIFOTJPO FYQSFTTJPO GPS DPOEJUJPO FYQSFTTJPO GPS
  69. TUS欽岁  "ABCDEFG"[2:4] "Repeat Me" * 16 "some" in "something

    is here" "this" not in "what about that" print("\n".join(["A", "B", "C"]))
  70. 竸ざ箻绢  欽♧妄QSJOU⽫ⴀ⟃♴㕬䕎 * ** *** **** ***** ****** ******

    ***** **** *** ** * * *** ***** *******
  71. 竸ざ箻绢  欽♧妄QSJOU⽫ⴀ⟃♴㕬䕎 3, 1 ___* 2, 3 __*** 1,

    5 _***** 0, 7 *******
  72. 㶶⚮贖椚 • s[:5] # 玲ڊ獮Բ㮆ਁ • s[-3:] # 玲ڊ磧盅ӣ㮆ਁ •

    s[0:4] # 玲ڊᒫ0㮆کᒫ3㮆ਁ • s[3:12:2] # 玲ڊᒫ3㮆کᒫ11㮆ਁ牧֕ฎྯ稞螂Ӟ 㮆ҁ2-1҂ 4VCTUSJOH
  73. 㶶⚮贖椚 • "ababa".count("a") # 3 • "dcba".startswith("dc") • "abcd".endswith("d") •

    "AbcD".upper() # 旉य़䌃 • "AbcD".lower() # 旉ੜ䌃
  74. 㶶⚮贖椚 • "\n".join(['a', 'b', 'c']) • "ab cd ef".split(" ")

    • "fly in sky".index("in") • "123".zfill(5) # 酢ꨫ • ZJOTLZSFQMBDF JO PO
  75. 㶶⚮贖椚 def is_mirror(s): return s == s[::-1] 㔐俒ⴼ倬♧遤晝劥

  76. %JDU ˙ %JDUJPOBSZ ˙ ,FZ7BMVF ˙ *OEFY〳⟃僽⟤⡦匌銯涸-JTU • d =

    { "A": "A string", "B": 456.7 } 
  77. %JDU • d[123] = 456 • d['key'] = 'value' •

    d.update({'mixin': ‘this-dict'}) • print(d.keys()) • print(d.get('no-this-key', 123)) • del d['a'] 
  78. %JDU for key, val in d.items(): print("%s -> %s" %

    (key, val)) 
  79. %JDU e = { i: '(%04d)' % i for i

    in range(5) } print(e) 
  80. %JDU e = { i: '(%04d)' % i for i

    in range(5) } print(e) 
  81. 墂呪贖椚  墂呪そ珖

  82. 墂呪贖椚  墂そ 墂そ墂呪涸そ㶶荈䊹《

  83. 墂呪贖椚  ⶰ墂そ陏ⴽ墂呪涸겳㘗 ⶰ墂そ

  84. 墂呪贖椚  8JOEPXT涸ⶰ墂そ갸鏤♶곏爚

  85. 墂呪贖椚  墂呪騟䖜穪㼩騟䖜㸤侮騟䖜

  86. 墂呪贖椚  墂呪騟䖜湱㼩騟䖜

  87. 墂呪贖椚 • fo = open("file name", "mode") • fo.write("data to

    write") • fo.readline() • fo.readlines() • fo.read(length) • fo.close() 87
  88. 墂呪贖椚 • r物捝玲 • w物䌃獈ҁ薟荠碉㮆䲆礯҂ • a物ᴫےҁ䌃獈ک䲆礯ੲᒒ҂ • b物覍෈ਁ䲆礯秇ୗ •

    +物窾ݳ秇ୗҁݢ捝ݢ䌃҂  䎙珏䌢鋅涸墂呪Ꟛ㉬垸䒭
  89. 墂呪贖椚 • r+ ݢ捝ݢ䌃 • ab ᴫےکӞ㮆 binary 䲆礯 •

    wb ୌ缏౲竃绚Ӟ㮆 binary 䲆礯牧ݢ犥䌃獈  䎙珏䌢鋅涸墂呪Ꟛ㉬垸䒭
  90. 90 name = input("What is your name? ") file_obj =

    open("test.txt", "w") file_obj.write("Hi, " + name + "\n") file_obj.close() 墂呪贖椚
  91. 91 name = input("What is your name? ") file_obj =

    open("test.txt", "w") file_obj.write("Hi, " + name + "\n") file_obj.close() Ꟛ㉬墂呪 墂呪そ珖 Ꟛ㉬垸䒭 ꡠꟗ墂呪 㻨Ⰵ墂呪 䳖遤 墂呪贖椚
  92. 92 fo = open("primes.txt", "r") s = 0 for i

    in fo: s += int(i) print("Sum =", s) fo.close() 墂呪贖椚
  93. 93 fo = open("primes.txt", "r") s = 0 for i

    in fo: s += int(i) print("Sum =", s) fo.close() 墂呪贖椚
  94. 娞聜物dict 膏䲆礯 94 ˙ 䪾EJDU㶸鹎墂呪 ˙ 䖰墂呪隡㔐EJDU

  95. 5FYU &ODPEJOHBOE#JOBSZ  TUS CZUFT CZUFBSSBZ MJTUPGJOU <  >

  96. $PNNPO&SSPS )BOEMJOH try: parse_data() except Exception as e: print(e)

  97. 7BMVF&SSPS s = input("Give me a number: ") try: n

    = int(s) print(s, "^2 =", n * n) except ValueError: print(s, "is not a valid number") 97
  98. 'JMF/PU'PVOE&SSPS try: fobj = open("readme.txt", "r") print(fobj.read()) fobj.close() except FileNotFoundError:

    print("File 'readme.txt' not found") 98
  99. 5ZQF&SSPS s = input('Give me a number: ') print("ready for

    an error?") print(s + 5) 99
  100. *OEFY&SSPS months = ("Jan Feb Mar Apr May Jun Jul

    " + "Aug Sep Oct Nov Dec").split(" ") try: m = int(input("Which month? ")) print("Month #" + str(m) + " is " + months[m - 1]) except ValueError: print("Not a valid integer") 100
  101. ,FZ&SSPS data = { "name": "Lightning", "type": "Pet", "age": 5,

    "weight": 18 } while True: column = input("Which column? ") if not column: break print(data[column]) 101
  102. ;FSP%JWJTJPO&SSPS print("Input some numbers") s, n = 0, 0 while

    True: m = input() if not m: break s += int(m) n += 1 print("Avg = " + str(s / n)) 102
  103. *T"%JSFDUPSZ&SSPS fobj = open('this-is-directory', 'r') # 玱ྋ䨝㽆梊藮牧獵ӥጱ纷ୗ嘨፜ኼ 103

  104. $47 $PNNB4FQBSBUFE7BMVFT 鸊贫ⴕꥬ须俲

  105. $47 Name,Age,Score Quentin,23,79 Marti,24,54 Avelina,19,51 Gayle,24,49 Kimiko,18,64 Chara,18,51 April,19,40 Alina,24,86

    105
  106. $478SJUFS3FBEFS import csv, sys try: filename = sys.argv[1] fobj =

    open(filename, 'w') writer = csv.writer(fobj) writer.writerow(['Name', 'Age']) writer.writerows([['lady gaga', 28], ['linroex', 19]]) fobj.close() except IndexError: print("Usage: python3 " + sys.argv[0] + " output.csv") 106
  107. $478SJUFS3FBEFS import csv, sys try: filename = sys.argv[1] fobj =

    open(filename, 'r') reader = csv.reader(fobj) skip_first_line = True for row in reader: if skip_first_line: skip_first_line = False continue print(row) fobj.close() except IndexError: print("Usage: python3 " + sys.argv[0] + " output.csv") except FileNotFoundError: print("File not found -> " + filename) 107
  108. $MBTTBOE0CKFDU ˙ $MBTTˋ겳ⴽ ˙ 鏤鎙㕬䒊眡话㕬 ˙ .FUIPEˋ倰岁㿂倴暟⟝涸ⴅ䒭 ˙ 0CKFDUˋ暟⟝ ˙

    㻜넓欴ㅷ覈ⴀ⢵涸䒊眡暟 ˙ "UUSJCVUFˋ㿂䚍꣡⸈倴暟⟝涸须俲 108
  109. $MBTTBOE0CKFDU 109 def FirstClass: def __init__(self, name): print('Hi, %s' %

    name) first_object = FirstClass('Inndy') print(first_object)
  110. $MBTTBOE0CKFDU 110 def FirstClass: def __init__(self, name): print('Hi, %s' %

    name) def leaving(self): print('Bye, %s' % self.name) obj = FirstClass('Inndy') obj.leaving() print(obj)
  111. $MBTTBOE0CKFDU class Animal: def __init__(self, name, sound = None): self.name

    = name self.sound = sound def say_hi(self): if self.sound == None: print("Hi, I'm " + self.name) else: print(self.name, ":", self.sound * 7) cat = Animal("Cat", "meow~") # init cat.say_hi() cat.sound = None cat.say_hi() 112