名稱(標籤) = 內容
a = 'Hello Python!'

a = 'Hello Python!'
print('a 物件的存放位置:', id(a))
a 物件的存放位置: 4558719984
a = 3
print('a 物件的存放位置:', id(a))
a 物件的存放位置: 4510262672
| False | class | finally | is | return |
| None | continue | for | lambda | try |
| True | def | from | nonlocal | while |
| and | del | global | not | with |
| as | elif | if | or | yield |
| assert | else | import | pass | |
| break | except | in | raise |
_variable = 1
variable = 1
first_variable = 1
$variable = 1
File "<ipython-input-7-9eb304bfdbe9>", line 1 $variable = 1 ^ SyntaxError: invalid syntax
1variable = 1
File "<ipython-input-8-e5103f12584c>", line 1 1variable = 1 ^ SyntaxError: invalid syntax
myname = 'Kristen'
print('My Name : ',myname)
My Name : Kristen
yourname = hisname = hername = 'Kristen' #Multiple Assignment
print('Your Name : ',yourname)
print('His Name : ',hisname)
print('Her Name : ',hername)
Your Name : Kristen His Name : Kristen Her Name : Kristen
my_age, my_gender, my_city = 80, "Female", "Taipei" #Multiple Assignment
print('Age : ',my_age)
print('Gender : ',my_gender)
print('City : ',my_city)
Age : 80 Gender : Female City : Taipei
student1_name = 'Vincent'
student2_name = 'Benson'
print('Student 1 : ',student1_name)
print('Student 2 : ',student2_name)
Student 1 : Vincent Student 2 : Benson
student1_name , student2_name = student2_name , student1_name
print('Student 1 : ',student1_name)
print('Student 2 : ',student2_name)
Student 1 : Benson Student 2 : Vincent
| Tpye | Example |
| int | 10 |
| float | 3.14 |
| boolean | True , False |
| string | 'Apple' |
type(10)
int
type(3.14)
float
NOTE type( x ) : 使用 type 來得知 x 的型態
type('10')
str
NOTE type( x ) : 使用 type 來得知 x 的型態
type(True)
bool
type(1>3)
bool
NOTE type( x ) : 使用 type 來得知 x 的型態
type(True)
bool
type(true)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-26-6f4d8242c3d0> in <module>() ----> 1 type(true) NameError: name 'true' is not defined
type(False)
bool
type(false)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-28-5d8f55c25b5e> in <module>() ----> 1 type(false) NameError: name 'false' is not defined
print( '1 + 2 = ' ,1 + 2 )
print( '5 - 10 = ' ,5 - 10 )
print( '4 * 6 = ' ,4 * 6 )
print( '3 / 2 = ' ,3 / 2 )
print( '3 // 2 = ' ,3 // 2 )
print( '7 % 5 = ' ,7 % 5 )
1 + 2 = 3 5 - 10 = -5 4 * 6 = 24 3 / 2 = 1.5 3 // 2 = 1 7 % 5 = 2
公式: $Fahrenheit = Celsius × (9/5) + 32$
Taipei_Celsius = 19
Taipei_Fahrenheit = Taipei_Celsius * (9/5) + 32
print(Taipei_Fahrenheit)
66.2
x = 10
print( 'x < 10 : ' ,x < 10 )
print( 'x > 10 : ' , x > 10 )
print( 'x <= 10 : ' ,x <= 10 )
print( 'x >= 10 : ' ,x >= 10 )
print( 'x == 10 : ' ,x == 10 )
print( 'x != 10 : ' ,x != 10 )
x < 10 : False x > 10 : False x <= 10 : True x >= 10 : True x == 10 : True x != 10 : False
y = 10
y += 3
print(y)
13
y = 10
y -= 3
print(y)
7
y = 10
y *= 3
print(y)
30
y = 10
y /= 3
print(y)
3.3333333333333335
y = 10
y %= 3
print(y)
1
print( 'True and True :' ,True and True )
print( 'True and False :' ,True and False )
print( 'False and True :' ,False and True )
print( 'False and False :' ,False and False )
True and True : True True and False : False False and True : False False and False : False
print( 'True or True :' ,True or True )
print( 'True or False :' ,True or False )
print( 'False or True :' ,False or True )
print( 'False or False :' ,False or False )
True or True : True True or False : True False or True : True False or False : False
Student1 = 'Emma'
Student2 = 'Sophia'
Student3 = 'Mia'
Student4 = 'Jason'
Student5 = 'Vivian'
STAT_A = ['Emma' ,'Sophia' ,'Mia' ,'Jason' ,'Vivian']
| Type | Example |
|---|---|
| list | [1,2,'YA'] |
| tuple | (1,2,'YA') |
| dictionary | {'Key1' : 'value1', 'Key2' : 'value2'} |
| set | {1,2} |
weather_list = [ 'Taipei' , 18.5 , 'rainy' ]
print( 'weather_list 的 type : ' ,type(weather_list) )
print( 'weather_list 的第一個元素 : ' ,weather_list[0] )
print( 'weather_list 的第二個元素 : ' ,weather_list[1] )
weather_list 的 type : <class 'list'> weather_list 的第一個元素 : Taipei weather_list 的第二個元素 : 18.5
print( 'weather_list 取出第一到第二個元素 : ' ,weather_list[0:1] )
weather_list 取出第一到第二個元素 : ['Taipei']

print( 'weather_list 取出第一到第二個元素 : ' ,weather_list[0:2] )
weather_list 取出第一到第二個元素 : ['Taipei', 18.5]
weather_list[:]
['Taipei', 18.5, 'rainy']
weather_list[0:3]
['Taipei', 18.5, 'rainy']
Note 元素 x : int , string , list , tuple
weather_list.append('80%') #濕度
print(weather_list)
['Taipei', 18.5, 'rainy', '80%']
weather_list.append(['Northeast',4]) #風相關[風向,風力級]
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4]]
print('weather_list 第五個元素的資料型態是' ,type(weather_list[4]))
weather_list 第五個元素的資料型態是 <class 'list'>
Note 可以加入 int , string , list , tuple
weather_list.extend(['Kaohsiung',25.9,'sunny','69%'])
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Kaohsiung', 25.9, 'sunny', '69%']
weather_list.append(('Northwest',3)) #風相關[風向,風力級]
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Kaohsiung', 25.9, 'sunny', '69%', ('Northwest', 3)]
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Kaohsiung', 25.9, 'sunny', '69%', ('Northwest', 3)]
weather_list.insert(5,'Taichung')
weather_list.insert(6,21.5)
weather_list.insert(7,'cloudy')
weather_list.insert(8,'73%')
weather_list.insert(9,['North'])
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Taichung', 21.5, 'cloudy', '73%', ['North'], 'Kaohsiung', 25.9, 'sunny', '69%', ('Northwest', 3)]
list [‘North’] 後面加入一個風力 2 級 的資訊¶[ 'North' , 2 ]
Note
print('目前 weather_list 中第十個元素是 : ' ,weather_list[9] )
目前 weather_list 中第十個元素是 : ['North']
weather_list[9].insert(len(weather_list[9]),2)
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Taichung', 21.5, 'cloudy', '73%', ['North', 2], 'Kaohsiung', 25.9, 'sunny', '69%', ('Northwest', 3)]
NOTE len( ) : 使用 len 來得知 list 中的元素的數量
color_list = ["Red","Green","White" ,"Black" ,"Pink"]
print( '第一個元素 : ', color_list[0])
print( '最後一個元素 : ', color_list[-1])
第一個元素 : Red 最後一個元素 : Pink
weather_tuple = ( 'Taipei' , 18.5 , 'rainy' )
print( 'weather_tuple 的 type : ' ,type(weather_tuple) )
print( 'weather_tuple 的第一個元素 : ' ,weather_tuple[0] )
print( 'weather_tuple 的第二個元素 : ' ,weather_tuple[1] )
weather_tuple 的 type : <class 'tuple'> weather_tuple 的第一個元素 : Taipei weather_tuple 的第二個元素 : 18.5
weather_tuple.append('80%') #濕度
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-59-a5f8e0bb3245> in <module>() ----> 1 weather_tuple.append('80%') #濕度 AttributeError: 'tuple' object has no attribute 'append'
city = ('Taipei','Taichung','Kaohsiung','Taipei')
city.count('Taipei')
2
city = ('Taipei','Taichung','Kaohsiung','Taipei')
city.index('Taichung')
1
weather_set = { 'Taipei' , 18.5 , 'rainy', 18.5 }
print( 'weather_set 的 type : ' ,type(weather_set) )
print( 'weather_set 自動排除重複值 : ' ,weather_set)
weather_set 的 type : <class 'set'>
weather_set 自動排除重複值 : {'Taipei', 18.5, 'rainy'}
Note
set1 = {1,2,3,4,6}
set2 = {2,3,4,5}
set1.difference( set2 )
{1, 6}
set1 = {1,2,3,4,6}
set2 = {2,3,4,5}
set1.symmetric_difference( set2 )
{1, 5, 6}
set1 = {1,2,3,4,6}
set2 = {2,3,4,5}
set1.intersection( set2 )
{2, 3, 4}
| Method | 說 明 |
|---|---|
| set1.intersectionset2) | set1 & set2 |
| set1.union(set2) | set1 $|$ set2 |
| set1.symmetric_difference(set2) | set1 ^ set2 |
| set1.difference(set2) | set1 $-$ set2 |
| set1.issubset(set2) | set1 $<=$ set2 |
| set1.issuperset(set2) | set1 $>=$ set2 |
color_set1 = set(["White", "Black", "Red" ,"Yellow" ,"Purple"])
color_set2 = set(["Red", "Green" ,"Yellow" ,"Orange"])
print( '在 color_set1 但不在 color_set2 的顏色 : ', color_set1.difference( color_set2 ) )
在 color_set1 但不在 color_set2 的顏色 : {'White', 'Black', 'Purple'}
weather_dict = { 'Taipei':'rainy', 'Taichung':'cloudy' , 'Tainan':'sunny' , 'Kaohsiung':'sunny' , 'Kaohsiung':'rainy'}
print( 'weather_dict 的 type : ' ,type(weather_dict) )
print( 'weather_dict 的 Key不能重複保留後面的 : ' ,weather_dict )
weather_dict 的 type : <class 'dict'>
weather_dict 的 Key不能重複保留後面的 : {'Taipei': 'rainy', 'Taichung': 'cloudy', 'Tainan': 'sunny', 'Kaohsiung': 'rainy'}
Note 總共有兩個 'Kaohsiung' 的 Key ,因為 Key 不能重複,所以會留下後面的
weather_dict = { 'Taipei':[18.5,'rainy','80%', 'Northeast', 4], 'Taichung': [21.5, 'cloudy', '73%', 'North', 2] }
print(weather_dict)
{'Taipei': [18.5, 'rainy', '80%', 'Northeast', 4], 'Taichung': [21.5, 'cloudy', '73%', 'North', 2]}
Note value 也可以是一個 list
weather_dict['Taipei']
[18.5, 'rainy', '80%', 'Northeast', 4]
Note 取出 weather_dict 中 Taipei 的資訊
| Type | 說明 |
|---|---|
| int(x) | string , float ➜ int |
| float(x) | string , int ➜ float |
| str(x) | int , float , list , tuple , dict ➜ string |
| list(x) | string , tuple, dict ➜ list |
| tuple(x) | string , list ➜ tuple |
int('10')
10
int(3.14)
3
float('10')
10.0
float(10)
10.0
str(10)
'10'
str(3.14)
'3.14'
str(weather_list)
"['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Taichung', 21.5, 'cloudy', '73%', ['North', 2], 'Kaohsiung', 25.9, 'sunny', '69%', ('Northwest', 3)]"
str(weather_tuple)
"('Taipei', 18.5, 'rainy')"
str(weather_dict)
"{'Taipei': [18.5, 'rainy', '80%', 'Northeast', 4], 'Taichung': [21.5, 'cloudy', '73%', 'North', 2]}"
list('10')
['1', '0']
list(weather_tuple)
['Taipei', 18.5, 'rainy']
list(weather_dict)
['Taipei', 'Taichung']
tuple('10')
('1', '0')
tuple(weather_list)
('Taipei',
18.5,
'rainy',
'80%',
['Northeast', 4],
'Taichung',
21.5,
'cloudy',
'73%',
['North', 2],
'Kaohsiung',
25.9,
'sunny',
'69%',
('Northwest', 3))
my_string = 'Hello'
my_string2 = "!!"
my_string3 = ""
my_string4 = "Hello" + my_string3 + " Python " + my_string2
my_string5 = "Hello {} !!".format("Python")
print ("my_string:", my_string)
print ("my_string2:", my_string2)
print ("my_string3:", my_string3)
print ("my_string4:", my_string4)
print ("my_string5:", my_string5)
my_string: Hello my_string2: !! my_string3: my_string4: Hello Python !! my_string5: Hello Python !!
print("1"+"2") #字串
print(1+2) #數值
12 3
Note 數值型的物件
Hi = "Hello"
print("Hi")
print(Hi)
Hi Hello
Note 已經被命名的物件
string_format1 = "Hello {} !!".format("Kristen")
string_format2 = "Hello {:s} !!".format("Kristen")
print("string_format1 : ", string_format1)
print("string_format2 : ", string_format2)
string_format1 : Hello Kristen !! string_format2 : Hello Kristen !!
Note 詳細介紹
string_format3 = 'Hello, {0:s} !! You have {1:d} error messages. Good luck, {0}.'.format('Kristen', 10000)
print("string_format3 : ", string_format3)
string_format3 : Hello, Kristen !! You have 10000 error messages. Good luck, Kristen.
Note 冒號 (:) 前可以自訂變數(format裡面的內容) 的 index
print("--- Method 1 -----------------------------------------------------------")
print('Hello, {:s} !! You have {:d} error messages.'.format('Kristen', 10000))
print("--- Method 2 -----------------------------------------------------------")
print('Hello, {0:s} !! You have {1:d} error messages.'.format('Kristen', 10000))
print("--- Method 3 -----------------------------------------------------------")
print("Hello, %s !! You have %d error messages." %('Kristen', 10000))
--- Method 1 ----------------------------------------------------------- Hello, Kristen !! You have 10000 error messages. --- Method 2 ----------------------------------------------------------- Hello, Kristen !! You have 10000 error messages. --- Method 3 ----------------------------------------------------------- Hello, Kristen !! You have 10000 error messages.
pi = 3.14159265359
print("圓周率:%1.2f" % pi)
圓周率:3.14
Note 最少要 1 個字元,取四捨五入到小數 2 位
print("圓周率:%6.2f" % pi)
圓周率: 3.14
Note 最少要 6 個字元,取四捨五入到小數 2 位 => 發現多了兩個空白
{ } 與 format 的方法,輸¶Hello Kristen !!
my_name = "Kristen"
my_string = "Hello {} !!".format(my_name)
print(my_string)
Hello Kristen !!
print("單引號 :" ,"Hello \'Python\'")
print("雙引號 :" ,"Hello \"Python\"")
print("反斜線 :" ,"Hello \\Python\\")
print("tab :" ,"Hello \tPython")
print("換行 :" ,"Hello \nPython")
單引號 : Hello 'Python' 雙引號 : Hello "Python" 反斜線 : Hello \Python\ tab : Hello Python 換行 : Hello Python
city = 'Taipei'
print("The 1st element of my_string = " ,city[0])
print("The 2st element of my_string = " ,city[1])
print("The last element of my_string = " ,city[-1])
The 1st element of my_string = T The 2st element of my_string = a The last element of my_string = i
my_string = "Hello Python"
print ("my_string 的總長度 :" ,len(my_string))
print ("'o' 總共在 my_string 中出現過幾次 :",my_string.count('a'))
my_string 的總長度 : 12 'o' 總共在 my_string 中出現過幾次 : 0
my_list = ["Taipei", "Kaohsiung", "Taichung" ,"Keelung", "Taipei"]
print ("my_list 的總長度 :" ,len(my_list))
print ("'Taipei' 總共在 my_list 中出現過幾次 :",my_list.count('Taipei'))
my_list 的總長度 : 5 'Taipei' 總共在 my_list 中出現過幾次 : 2
my_string = "Hello Kristen"
print (my_string.split(" "))
['Hello', 'Kristen']
print (my_string.split(" ")[0])
print (my_string.split(" ")[1])
Hello Kristen
Note 依照空格切割
my_string = "Hello Kristen !!"
my_string = my_string.replace("Kristen" ,"Rick")
print(my_string)
Hello Rick !!
article = "North Korea is seriously examining a plan to launch a missile strike targeting an area near the US territory of Guam in response to US President Donald Trump's warning to Pyongyang that any additional threats will be met with fire and fury, according to a new statement from Gen. Kim Rak Gyom published by state-run media KCNA Thursday."
print (article.split(" "))
['North', 'Korea', 'is', 'seriously', 'examining', 'a', 'plan', 'to', 'launch', 'a', 'missile', 'strike', 'targeting', 'an', 'area', 'near', 'the', 'US', 'territory', 'of', 'Guam', 'in', 'response', 'to', 'US', 'President', 'Donald', "Trump's", 'warning', 'to', 'Pyongyang', 'that', 'any', 'additional', 'threats', 'will', 'be', 'met', 'with', 'fire', 'and', 'fury,', 'according', 'to', 'a', 'new', 'statement', 'from', 'Gen.', 'Kim', 'Rak', 'Gyom', 'published', 'by', 'state-run', 'media', 'KCNA', 'Thursday.']
print ("文章中第二個字 : ",article.split(" ")[1])
文章中第二個字 : Korea
article = "美國總統川普昨天警告北韓別再挑釁,否則將面臨「戰火與怒火」回擊。對此,白宮發言人桑德斯今天聲明,川普談話的語氣與力道,白宮國安會團隊及幕僚長凱利事先都知情。"
print (article)
美國總統川普昨天警告北韓別再挑釁,否則將面臨「戰火與怒火」回擊。對此,白宮發言人桑德斯今天聲明,川普談話的語氣與力道,白宮國安會團隊及幕僚長凱利事先都知情。
article=article.replace("北韓","朝鮮民主主義人民共和國")
print (article)
美國總統川普昨天警告朝鮮民主主義人民共和國別再挑釁,否則將面臨「戰火與怒火」回擊。對此,白宮發言人桑德斯今天聲明,川普談話的語氣與力道,白宮國安會團隊及幕僚長凱利事先都知情。