Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python 基礎教學

Inndy
November 02, 2015

Python 基礎教學

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

Inndy

November 02, 2015
Tweet

More Decks by Inndy

Other Decks in Technology

Transcript

  1. 簮䱖莅玑䒭⼦㝆 • Ӟ㮆婘矎դ蔭Ӟ㮆纷ୗ玟璸 • 磪ٛ蒈磪婘矎 • 磪ٛ蒈಍磪婘矎牧犋胼㫂婘矎 • ೲ Tab

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

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

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

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

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

    3 res += 5 * y ** 2 return res f (x, y) = 3x + 5y2 9
  7. def add(x, y): result = x + y return result

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

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

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

    2 # else-if ݢ犥盄ग़㮆 # ౲ᘏ䷱磪 elif 礿կ3: # 纷ୗ粙ྦྷ 3 else: # ইຎ獮ᶎӣ殻礿կ᮷犋ᒧݳ 15
  11. 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
  12. 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
  13. for 蝅瑹 35 sum = 0 for i in range(1,

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

    data += chr(i) print(data) print(ord("A"))
  15. 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]
  16. 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)
  17. ⳯讍鶋㺙岁  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)
  18. 㼦䪪_涸颶侸  for i in range(2, 100 + 1): for

    j in range(2, i): if i % j == 0: break else: # ইຎ䷱磪ᤩbreak print(i, "is prime.")
  19. 8IJMF鶬㕖  i = 10 m = 1 while i

    > 1: m *= i i -= 1 print(m)
  20. # 娞聜物糔碍ਁ蝿瞁 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.")
  21. -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] 
  22. -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)
  23.  a = [ i for i in range(1, 11)

    ] -JTU$PNQSFIFOTJPO
  24.  a = [i ** 2 for i in range(1,

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

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

    in range(5) ] # [0, 2, 4, 6, 8]
  27.  print([ n for n in range(2, 100) if not

    any( n % i == 0 for i in range(2, n) ) ]) -JTU$PNQSFIFOTJPO
  28.  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
  29.  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
  30. TUS欽岁  "ABCDEFG"[2:4] "Repeat Me" * 16 "some" in "something

    is here" "this" not in "what about that" print("\n".join(["A", "B", "C"]))
  31. 㶶⚮贖椚 • s[:5] # 玲ڊ獮Բ㮆ਁ • s[-3:] # 玲ڊ磧盅ӣ㮆ਁ •

    s[0:4] # 玲ڊᒫ0㮆کᒫ3㮆ਁ • s[3:12:2] # 玲ڊᒫ3㮆کᒫ11㮆ਁ牧֕ฎྯ稞螂Ӟ 㮆ҁ2-1҂ 4VCTUSJOH
  32. 㶶⚮贖椚 • "\n".join(['a', 'b', 'c']) • "ab cd ef".split(" ")

    • "fly in sky".index("in") • "123".zfill(5) # 酢ꨫ • ZJOTLZSFQMBDF JO PO
  33. %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'] 
  34. %JDU e = { i: '(%04d)' % i for i

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

    in range(5) } print(e) 
  36. 墂呪贖椚 • fo = open("file name", "mode") • fo.write("data to

    write") • fo.readline() • fo.readlines() • fo.read(length) • fo.close() 87
  37. 墂呪贖椚 • r+ ݢ捝ݢ䌃 • ab ᴫےکӞ㮆 binary 䲆礯 •

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

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

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

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

    in fo: s += int(i) print("Sum =", s) fo.close() 墂呪贖椚
  42. 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
  43. *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
  44. ,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
  45. ;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
  46. $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
  47. $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
  48. $MBTTBOE0CKFDU ˙ $MBTTˋ겳ⴽ ˙ 鏤鎙㕬䒊眡话㕬 ˙ .FUIPEˋ倰岁㿂倴暟⟝涸ⴅ䒭 ˙ 0CKFDUˋ暟⟝ ˙

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

    name) first_object = FirstClass('Inndy') print(first_object)
  50. $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)
  51. $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