Inndy
November 02, 2015
680

# Python 基礎教學

## Inndy

November 02, 2015

## Transcript

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

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 ֦蝡㮆ੜ疵਎

1 3 5

1 3 5 list

D

2 3

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)

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

== 0: continue print(i)

43. ### 㼦䪪_涸颶侸 ˙ 睨岁增叆僽やⰨ剤Ⱖ➮㔔侸 ˙ O  O佖葻睨岁涸眕㕠 ˙ 4JFWFPG&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.")

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.")

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)

print(a)

sum 

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

] -JTU\$PNQSFIFOTJPO

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]

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(" ")

• "ﬂy in sky".index("in") • "123".zﬁll(5) # 酢ꨫ • ZJOTLZSFQMBDF JO PO

76. ### %JDU ˙ %JDUJPOBSZ ˙ ,FZ7BMVF ˙ *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) 

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() 墂呪贖椚

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

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

105
106. ### \$478SJUFS3FBEFS 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. ### \$478SJUFS3FBEFS 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. ### \$MBTTBOE0CKFDU ˙ \$MBTTˋ겳ⴽ ˙ 鏤鎙㕬䒊眡话㕬 ˙ .FUIPEˋ倰岁㿂倴暟⟝涸ⴅ䒭 ˙ 0CKFDUˋ暟⟝ ˙

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

name) first_object = FirstClass('Inndy') print(first_object)
110. ### \$MBTTBOE0CKFDU 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. ### \$MBTTBOE0CKFDU 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