12. string(字串)
數字字串 int() 數字
x = '10'
y = int(x)
print(type(y))
# <class 'int'>
x = 'a'
y = int(x)
print(y)
print(type(y))
#ValueError: invalid literal for int() with base 10: 'a'
13. string(字串)
可透過slicing取出特定字元
無法透過slicing更換字元
x = "hello world"
y = x[0:5]
print(y)
# hello
x = "hello world"
x[0:5] = "wonderful"
print(x)
# TypeError: 'str' object does not support item assignment
17. string.format
語法:"{},{}".format(v1, v2)
"{},{}"稱為格式化字串、{}稱為格式化的位置參數
print("{} is the best {} in the {}".format("Python", "language", "world"))
# Python is the best language in the world
位置參數
print("{} * {} = {}".format(2, 3, 2*3))
# 2 * 3 = 6
位置參數指定
print("{0} is the best {1} in the {2}".format("Python", "language", "world"))
# Python is the best language in the world
print("{1} is the best {2} in the {0}".format("Python", "language", "world"))
# language is the best world in the Python
19. f-string
String Interpolation(字串插值) , 在字串中進行格式化
語法: f“{x1} {x2}”,其中f大小寫皆可
fruit = "apple"
print(f"My favorite fruit is {fruit}")
# My favorite fruit is apple
{} 可放入有效的expression
print(f"2*6 is equal to {2*6}") # 2*6 is equal to 12
name = "bob"
print(f"My name is {name.upper()}") # My name is BOB
32. tuple
有序資料但資料不可變
用()建立
x = () # 空tuple
x = (1, 2, 3, 4)
如何建立單一個元素的tuple
x = (1)
print(x) # 1 is a int type
我們直覺建立 正確:(元素, )
x = (1, )
print(x) # (1, )
33. tuple with slicing
slicing僅能讀取資料,不能修改,否則出現TypeError。
x = (1, 2, 3, 4)
print(x[2]) # 3
x = (1, 2, 3, 4)
x[2] = "aaa"
print(x)
# TypeError: 'tuple' object does not support item assignment
47. for loop
如何用for loop + range產出一樣的結果?
x = range(1, 10)
print(list(x))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
nums = []
for num in range(1, 10):
nums.append(num)
print(nums)
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
48. list comprehension
語法: [運算式 for 變數 in iterable if 條件成立]
nums = [num for num in range(1, 10)]
print(nums)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
簡潔, 可讀性降低
y = [num**2 for num in range(20) if num >10]
print(y)
#[121, 144, 169, 196, 225, 256, 289, 324, 361]
y = []
for num in range(20):
if num > 10:
y.append(num**2)
print(y)
# [121, 144, 169, 196, 225, 256, 289, 324, 361]
49. break / continue
break 取消迴圈
continue 略過後面程式碼,同步進入下一個迴圈
while True:
value = input(“enter integer number (q when exit): ”)
if value == “q” :
break # 離開迴圈
value = int(value)
if value % 2 != 0:
continue #跳過,在進入下一個迴圈
print("the even value is", value)
# 執行結果如下
# enter integer number (q when exit): 1
# enter integer number (q when exit): 2
# the even value is 2
# enter integer number (q when exit): q
50. 有同樣功能該怎做…….?
ctrl + c / ctrl + v
#設定x, y變數值,印出加總結果
x = 10
y = 20
print(x + y) # 30
#再次設定x, y變數值,印出加總結果
x = 100
y = 299
print(x +y) # 399
如有數個地方使用同功能,難道要一直複製貼上?
如這功能有調整,複製的地方全要同步手動調?
65. 如何取用類別的屬性與method?
更改實例物件屬性資料,僅影響自身的屬性值
class Human:
def __init__(self,name,age):
self.name = name
self.age = age
def sound(self, voice):
return f“{self.name} has the {voice} sound”
king = Human(“king”, 22)
queen = Human(“Queen”, 20)
queen.name = “Elsa”
queen.age = 21
print(“After changing name is ”, king.name) # After changing name is king
print(“After changing age is ”,king.age) # After changing age is 22
print(“After changing name is ”,queen.name) # After changing name is Elsa
print(“After changing age is ”,queen.age) # After changing age is 21
66. inheritance
當你發現寫過類
別的程式碼在新
類別仍然可用,
你會怎麼做?
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
d = Animal("Doff", 2)
print("{} is {} years old".format(d.name, d.age)) # Doff is 2 years old
print(d.sound("bark")) # bark
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
poppy = Dog("Poppy", 3)
print("{} is {} years old".format(poppy.name, poppy.age)) # Poppy is 3 years old
print(poppy.sound("bark")) # bark
如何解決呢?
繼承(inheritance)
67. inheritance
從既有類別(Parent Class)中創造出新的子類別(Child Class),新的子
類別承襲了既有類別的所有屬性與method
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
pass # 雖然無程式碼,但Python仍會執行
poppy = Dog("Poppy", 3)
print("{} is {} years old".format(poppy.name, poppy.age)) #Poppy is 3 years old
print(poppy.sound("bark")) #bark
68. inheritance
Child class 如何取用 Parent class的方法(method)?
super().method
ParentClass.method
明確知道取用哪個Parent Class
缺乏彈性, 當Parent Class改名, 就要逐一修改
69. inheritance_ super().method
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
def __init__(self, name, age, color):
super().__init__(name,age)
self.color = color
def sound(self, voice):
return f"{self.name} has the {voice} sounds"
poppy = Dog("Poppy", 3, "Brown")
print("{} is {} years old and the color is {}".format(poppy.name, poppy.age, poppy.color))
# Poppy is 3 years old and the color is Brown
print(poppy.sound("bark"))
# Poppy has the bark sounds
70. inheritance_ ParentClass.method
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
def __init__(self, name, age, color):
Animal.__init__(self, name,age) # 類別名稱後面不用加()、第一個參數須為self
self.color = color
def sound(self, voice):
return f"{self.name} has the {voice} sounds"
poppy = Dog("Poppy", 3, "Brown")
print("{} is {} years old and the color is {}".format(poppy.name, poppy.age, poppy.color))
# Poppy is 3 years old and the color is Brown
print(poppy.sound("bark")) # Poppy has the bark sounds
71. inheritance with Override
Childe class 與 Parent
class有相同的方法
(method)名,實質內容不
同
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
def __init__(self, name, age, color):
super().__init__(name,age)
self.color = color
def sound(self, voice):
return f"{self.name} has the {voice} sounds"
kity = Animal("Kity", 6)
poppy = Dog("Poppy", 3, "Brown")
print(f"{poppy.name} is {poppy.age} years old and the color is {poppy.color}")
# Poppy is 3 years old and the color is Brown
print(poppy.sound("bark")) # Poppy has the bark sounds
print(kity.sound("Haha....")) # Haha....
72. inheritance with Add
子類別建立自己的操
作方式(mehotd)
僅適用子類別
Parent class呼叫會
出現錯誤
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
def __init__(self, name, age, color):
Animal.__init__(self, name,age) # 類別名稱後面不用加()、第一個參數須為self
self.color = color
def sound(self, voice):
return f"{self.name} has the {voice} sounds"
def run(self):
return "Running fast"
doff = Animal("Doff",1)
poppy = Dog("Poppy", 3, "Brown")
print(poppy.run()) # Running fast
print(doff.run()) # AttributeError: 'Animal' object has no attribute 'run'