TKU STAT × Python Basic

Basic


Kristen Chan

Agenda


  • 物件 (Object)
  • 變數命名規則 (Variable Name Rules)
  • 變數賦值 (Assignment Statements)
  • 交換變數 (Swap variables)
  • 資料型態 (Data Type)
  • 運算子 (Operator)
  • 資料型態轉換 (Data Type Conversion)
  • 補充

Object

Object


  • 物件可以重複利用,程式碼可以更為簡潔
  • 使用 = 對物件賦值
名稱(標籤) = 內容 
a         = 'Hello Python!'

Object

In [1]:
a = 'Hello Python!'

Object


  • 存放位置(抽屜位置) ObjectLocation
In [2]:
print('a 物件的存放位置:', id(a))
a 物件的存放位置: 4558719984

Object


Note

  • a 賦予新的值 (更換 a 標籤的內容)
  • 存放的位置也會改變 ObjectLocation
In [3]:
a = 3
print('a 物件的存放位置:', id(a))
a 物件的存放位置: 4510262672

Variable Name Rules

Variable Name Rules


  • First character
    A letter (a - z, A - B) or underscore ( _ )

  • Other characters
    Letters (a - z, A - B) , numbers (0-9) or ( _ )

  • No
    : !, @, #, $, %, - etc.

  • Reserved words 保留字

Variable Name Rules


Reserved words 保留字

Falseclassfinallyisreturn
Nonecontinueforlambdatry
Truedeffromnonlocalwhile
anddelglobalnotwith
aselififoryield
assertelseimportpass
breakexceptinraise

Variable Name Rules


Good

In [4]:
_variable = 1 
In [5]:
variable = 1 
In [6]:
first_variable = 1

Variable Name Rules


Bad

In [7]:
$variable = 1
  File "<ipython-input-7-9eb304bfdbe9>", line 1
    $variable = 1
    ^
SyntaxError: invalid syntax
In [8]:
1variable = 1
  File "<ipython-input-8-e5103f12584c>", line 1
    1variable = 1
            ^
SyntaxError: invalid syntax

Variable Name Rules


Note

  • 不能以數字開頭
  • 不可以使用保留字 (ex: import, for, in, str....)
  • 好的命名方式會讓程式碼容易閱讀
    • Good
      url = "https://softnshare.wordpress.com"
      
    • Bad
      abc = "https://softnshare.wordpress.com"
      

Assignment Statements

Assignment Statements


  • Single assignment
  • Multiple Assignment

Assignment Statements


Single assignment

In [9]:
myname = 'Kristen'
In [10]:
print('My Name : ',myname)
My Name :  Kristen

Assignment Statements


Multiple Assignment

In [11]:
yourname = hisname = hername = 'Kristen' #Multiple Assignment
In [12]:
print('Your Name : ',yourname)
print('His Name : ',hisname)
print('Her Name : ',hername)
Your Name :  Kristen
His Name :  Kristen
Her Name :  Kristen

Assignment Statements


Multiple Assignment

In [13]:
my_age, my_gender, my_city = 80, "Female", "Taipei" #Multiple Assignment
In [14]:
print('Age : ',my_age)
print('Gender : ',my_gender)
print('City : ',my_city)
Age :  80
Gender :  Female
City :  Taipei

Swap variables

Swap variables


In [15]:
student1_name = 'Vincent'
In [16]:
student2_name = 'Benson'
In [17]:
print('Student 1 : ',student1_name)
print('Student 2 : ',student2_name)
Student 1 :  Vincent
Student 2 :  Benson

Swap

In [18]:
student1_name , student2_name = student2_name , student1_name
In [19]:
print('Student 1 : ',student1_name)
print('Student 2 : ',student2_name)
Student 1 :  Benson
Student 2 :  Vincent

Data Type

Data Type


  • 數值型態(Numeric type)
  • 字串型態(String type)
  • 布林型態(Boolean type)
TpyeExample
int10
float3.14
booleanTrue , False
string'Apple'

Data Type


  • 數值型態(Numeric type)
In [20]:
type(10)
Out[20]:
int
In [21]:
type(3.14)
Out[21]:
float

NOTE type( x ) : 使用 type 來得知 x 的型態

Data Type


  • 字串型態(String type)
In [22]:
type('10')
Out[22]:
str

NOTE type( x ) : 使用 type 來得知 x 的型態

Data Type


  • 布林型態(Boolean type)
In [23]:
type(True)
Out[23]:
bool
In [24]:
type(1>3)
Out[24]:
bool

NOTE type( x ) : 使用 type 來得知 x 的型態

Data Type


  • 布林型態(Boolean type)

注意 Boolean : True / False 的 T 和 F 要大寫

In [25]:
type(True)
Out[25]:
bool
In [26]:
type(true)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-26-6f4d8242c3d0> in <module>()
----> 1 type(true)

NameError: name 'true' is not defined
In [27]:
type(False)
Out[27]:
bool
In [28]:
type(false)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-28-5d8f55c25b5e> in <module>()
----> 1 type(false)

NameError: name 'false' is not defined

Operator

Operator


  • 算術運算子 (Arithmetic Operator)
  • 關係運算子 (Comparison Operator)
  • 指派運算子 (Assignment Operator)
  • 邏輯運算子 (Logical Operator)

Operator


Arithmetic Operator

運算子功能
加法運算
減法運算/負號
*乘法運算
**指數運算
/除法運算
//整除
%取餘數

Operator


Arithmetic Operator

In [29]:
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

Exercise

Q. 現在台北溫度是 19$℃$,請將$℃$ 轉成 $℉$

公式: $Fahrenheit = Celsius × (9/5) + 32$

Answers

In [30]:
Taipei_Celsius = 19

Taipei_Fahrenheit = Taipei_Celsius * (9/5) + 32

print(Taipei_Fahrenheit)
66.2

Operator


Comparison Operator

運算子說明
$<$小於
$>$大於
$<=$小於等於
$>=$大於等於
$==$等於
$!=$不等於

Operator


Comparison Operator

In [31]:
x = 10
In [32]:
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

Operator


Assignment Operator

運算子說明
$=$將右邊的運算結果,指定給左邊的變數
$+=$將左邊變數值加右邊的值,再指定給左邊的變數
$-=$將左邊變數值減右邊的值,再指定給左邊的變數
$*=$將左邊變數值乘右邊的值,再指定給左邊的變數
$/=$將左邊變數值除右邊的值,再指定給左邊的變數
% $=$將左邊變數值除右邊的值,再指定餘數給左邊的變數

Operator


Assignment Operator

In [33]:
y = 10
y += 3
print(y)
13
In [34]:
y = 10
y -= 3
print(y)
7
In [35]:
y = 10
y *= 3
print(y)
30

Operator


Assignment Operator

In [36]:
y = 10
y /= 3
print(y)
3.3333333333333335
In [37]:
y = 10
y %= 3
print(y)
1

Operator


Logical Operator

運算子功能
and且 ( And )
or或 ( Or )
not反向

Operator


Logical Operator (and)

In [38]:
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

Operator


Logical Operator (or)

In [39]:
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

Data Type II

Data Type II


Note : 想要儲存全班同學的名字

Method 1 .

Student1 = 'Emma'
Student2 = 'Sophia'
Student3 = 'Mia' 
Student4 = 'Jason' 
Student5 = 'Vivian'

Data Type II


Note : 想要儲存全班同學的名字

Method 2 .

STAT_A = ['Emma' ,'Sophia' ,'Mia' ,'Jason' ,'Vivian']

Data Type II


  • 容器型態(Container type)
    • list
    • tuple
    • dictionary
    • set

Data Type II


TypeExample
list[1,2,'YA']
tuple(1,2,'YA')
dictionary{'Key1' : 'value1', 'Key2' : 'value2'}
set{1,2}

Data Type II


list

  • [ ]一串以 , 分開的值包起來
    e.g. my_list = [ 1 , 2 , ’YA’ ]
  • list 中的元素不必放相同的資料型態 (int, float, boolean, string)
  • Python index 從 0 開始
    e.g. my_list[ 0 ] = 1

Data Type II


list

In [40]:
weather_list = [ 'Taipei' , 18.5 , 'rainy' ]
In [41]:
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

Data Type II


Note : 在 list 中一次取多個元素

  • list[m:n] : 從第 m 個開始到第 n-1 個
  • list[:] : 從最前面到最後面 (全部)

Question 取出 weather_list 中第一到第二個元素

In [42]:
print( 'weather_list 取出第一到第二個元素 : ' ,weather_list[0:1] )
weather_list 取出第一到第二個元素 :  ['Taipei']

Wrong

Data Type II


Note : 在 list 中一次取多個元素

  • list[m:n] : 從第 m 個開始到第 n-1 個
  • list[:] : 從最前面到最後面 (全部)

Question 取出 weather_list 中第一到第二個元素

In [43]:
print( 'weather_list 取出第一到第二個元素 : ' ,weather_list[0:2] )
weather_list 取出第一到第二個元素 :  ['Taipei', 18.5]

Data Type II


Note : 在 list 中一次取多個元素

  • list[m:n] : 從第 m 個開始到第 n-1 個
  • list[:] : 從最前面到最後面 (全部)

Question 取出 weather_list 中全部的元素

In [44]:
weather_list[:]
Out[44]:
['Taipei', 18.5, 'rainy']
In [45]:
weather_list[0:3]
Out[45]:
['Taipei', 18.5, 'rainy']

Data Type II


list

  • list.append( x )
    list 後面加入一個新的元素 x,直接放入該元素

  • list.extend( x )
    list 後面加入一個新的元素 x,先將元素展開再放入

  • list.insert( 索引位置 , x )
    新增元素 x ,並放在指定的索引位置之前

Note 元素 x : int , string , list , tuple

Data Type II


list

list.append( x )

In [46]:
weather_list.append('80%') #濕度
print(weather_list)
['Taipei', 18.5, 'rainy', '80%']
In [47]:
weather_list.append(['Northeast',4]) #風相關[風向,風力級]
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4]]
In [48]:
print('weather_list 第五個元素的資料型態是' ,type(weather_list[4]))
weather_list 第五個元素的資料型態是 <class 'list'>

Note 可以加入 int , string , list , tuple

Data Type II


list

list.extend( x )

In [49]:
weather_list.extend(['Kaohsiung',25.9,'sunny','69%'])
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Kaohsiung', 25.9, 'sunny', '69%']
In [50]:
weather_list.append(('Northwest',3)) #風相關[風向,風力級]
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Kaohsiung', 25.9, 'sunny', '69%', ('Northwest', 3)]

Data Type II


list

list.insert

In [51]:
print(weather_list)
['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Kaohsiung', 25.9, 'sunny', '69%', ('Northwest', 3)]
In [52]:
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)]

Exercise

Q. 請將 weather_list[9] 中的 list [‘North’] 後面加入一個風力 2 級 的資訊

[ 'North' , 2 ]

Note

In [53]:
print('目前 weather_list 中第十個元素是 : ' ,weather_list[9] )
目前 weather_list 中第十個元素是 :  ['North']

Answers

In [54]:
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 中的元素的數量

Exercise

Q. 請輸出 color_list 中第一及最後一個元素

In [55]:
color_list = ["Red","Green","White" ,"Black" ,"Pink"]

Answers

In [56]:
print( '第一個元素 : ', color_list[0])
print( '最後一個元素 : ', color_list[-1])
第一個元素 :  Red
最後一個元素 :  Pink

Data Type II


tuple

  • ( )一串以 , 分開的值包起來
    e.g. my_tuple = ( 1 , 2 , ’YA’ )
  • tuple 中的元素不必放相同的資料型態 (int, float, boolean, string)
  • tuplelist 很像
  • tuple 不能新增、刪除、修改

Data Type II


tuple

In [57]:
weather_tuple = ( 'Taipei' , 18.5 , 'rainy' )
In [58]:
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

Data Type II


tuple

Note : tuple 不能新增、刪除、修改

In [59]:
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'

Data Type II


tuple

  • tuple.count( x )
    元素 x 在 tuple 中出現幾次

  • tuple.index( x )
    元素 x 在 tuple 的索引位置是哪裡

Data Type II


tuple

tuple.count( x )

In [60]:
city = ('Taipei','Taichung','Kaohsiung','Taipei')
In [61]:
city.count('Taipei')
Out[61]:
2

Data Type II


tuple

tuple.index( x )

city = ('Taipei','Taichung','Kaohsiung','Taipei')
In [62]:
city.index('Taichung')
Out[62]:
1

Data Type II


set

  • { }一串以 , 分開的值包起來
    e.g. my_set = { 1 , 2 , ’YA’ }
  • set 中的元素不必放相同的資料型態 (int, float, boolean, string)
  • 沒有順序性
  • set 中的元素是不重複

Data Type II


set

In [63]:
weather_set = { 'Taipei' , 18.5 , 'rainy', 18.5 }
In [64]:
print( 'weather_set 的 type : ' ,type(weather_set) )
print( 'weather_set 自動排除重複值 : ' ,weather_set)
weather_set 的 type :  <class 'set'>
weather_set 自動排除重複值 :  {'Taipei', 18.5, 'rainy'}

Note

  • 沒有按照原本輸入的順序擺放
  • 相同的元素會被剔除

Data Type II


set

  • set1.difference( set2 )
    找出 set1 中不存在 set2 的元素

  • set1.symmetric_difference( set2 )
    找出兩個 set 中不同的元素

  • set1.intersection( set2 )
    找出兩個 set 中相同的元素

Data Type II


set

set1.difference( set2 )

In [65]:
set1 = {1,2,3,4,6}
set2 = {2,3,4,5}
In [66]:
set1.difference( set2 )
Out[66]:
{1, 6}

Data Type II


set

set1.symmetric_difference( set2 )

set1 = {1,2,3,4,6}
set2 = {2,3,4,5}
In [67]:
set1.symmetric_difference( set2 )
Out[67]:
{1, 5, 6}

Data Type II


set

set1.intersection( set2 )

set1 = {1,2,3,4,6}
set2 = {2,3,4,5}
In [68]:
set1.intersection( set2 )
Out[68]:
{2, 3, 4}

Data Type II


set

Note : 比較兩個 set

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

Exercise

Q. 請找出在 color_set1 但不在 color_set2 中的顏色

In [69]:
color_set1 = set(["White", "Black", "Red" ,"Yellow" ,"Purple"]) 
color_set2 = set(["Red", "Green" ,"Yellow" ,"Orange"])

Answers

In [70]:
print( '在 color_set1 但不在 color_set2 的顏色 : ', color_set1.difference( color_set2 ) )
在 color_set1 但不在 color_set2 的顏色 :  {'White', 'Black', 'Purple'}

Data Type II


dictionary

  • { }一群由 Key,Value 配對組合而成的東西包起來
    e.g. my_dict = { 'Key1':'value1','Key2':'value2' }
  • Key 有大小寫之分
  • 不必放相同的資料型態
  • Key 不能重複,否則會被後面取代
  • 沒有順序之分

Data Type II


dictionary

In [71]:
weather_dict = { 'Taipei':'rainy', 'Taichung':'cloudy' , 'Tainan':'sunny' , 'Kaohsiung':'sunny' , 'Kaohsiung':'rainy'}
In [72]:
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 不能重複,所以會留下後面的

Data Type II


dictionary

In [73]:
weather_dict = { 'Taipei':[18.5,'rainy','80%', 'Northeast', 4], 'Taichung': [21.5, 'cloudy', '73%', 'North', 2] }
In [74]:
print(weather_dict)
{'Taipei': [18.5, 'rainy', '80%', 'Northeast', 4], 'Taichung': [21.5, 'cloudy', '73%', 'North', 2]}

Note value 也可以是一個 list

Data Type II


dictionary

In [75]:
weather_dict['Taipei']
Out[75]:
[18.5, 'rainy', '80%', 'Northeast', 4]

Note 取出 weather_dict 中 Taipei 的資訊

Data Type Conversion

Data Type Conversion


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

Data Type Conversion


int(x) : 將 x 轉成 int

In [76]:
int('10')
Out[76]:
10
In [77]:
int(3.14)
Out[77]:
3

Data Type Conversion


float(x) : 將 x 轉成 float

In [78]:
float('10')
Out[78]:
10.0
In [79]:
float(10)
Out[79]:
10.0

Data Type Conversion


str(x) : 將 x 轉成 str

In [80]:
str(10)
Out[80]:
'10'
In [81]:
str(3.14)
Out[81]:
'3.14'
In [82]:
str(weather_list)
Out[82]:
"['Taipei', 18.5, 'rainy', '80%', ['Northeast', 4], 'Taichung', 21.5, 'cloudy', '73%', ['North', 2], 'Kaohsiung', 25.9, 'sunny', '69%', ('Northwest', 3)]"
In [83]:
str(weather_tuple)
Out[83]:
"('Taipei', 18.5, 'rainy')"
In [84]:
str(weather_dict)
Out[84]:
"{'Taipei': [18.5, 'rainy', '80%', 'Northeast', 4], 'Taichung': [21.5, 'cloudy', '73%', 'North', 2]}"

Data Type Conversion


list(x) : 將 x 轉成 list

In [85]:
list('10')
Out[85]:
['1', '0']
In [86]:
list(weather_tuple)
Out[86]:
['Taipei', 18.5, 'rainy']
In [87]:
list(weather_dict)
Out[87]:
['Taipei', 'Taichung']

Data Type Conversion


tuple(x) : 將 x 轉成 tuple

In [88]:
tuple('10')
Out[88]:
('1', '0')
In [89]:
tuple(weather_list)
Out[89]:
('Taipei',
 18.5,
 'rainy',
 '80%',
 ['Northeast', 4],
 'Taichung',
 21.5,
 'cloudy',
 '73%',
 ['North', 2],
 'Kaohsiung',
 25.9,
 'sunny',
 '69%',
 ('Northwest', 3))

補充

補充


string

  • 使用單引號(')或雙引號(")包起來的資料
  • 允許空的資料
  • 可以使用 + 來串接兩個字串
  • 利用 { } 與 format ,可以彈性填入字、詞
In [90]:
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 !!

補充


string

Note : 如果沒有用到引號,Python 可能會遇到的問題

In [91]:
print("1"+"2") #字串
print(1+2)   #數值
12
3

Note 數值型的物件

補充


string

Note : 如果沒有用到引號,Python 可能會遇到的問題

In [92]:
Hi = "Hello"
In [93]:
print("Hi")
print(Hi)  
Hi
Hello

Note 已經被命名的物件

補充


Note : Print Formatting

  • s:字串
  • f:浮點數
  • i:整數
In [94]:
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 : Print Formatting

  • s:字串
  • f:浮點數
  • d,i:整數
In [95]:
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

補充


Note : Print Formatting

  • s:字串
  • f:浮點數
  • d,i:整數
In [96]:
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.

補充


Note : Print Formatting

  • s:字串
  • f:浮點數
  • d,i:整數
In [97]:
pi = 3.14159265359
print("圓周率:%1.2f" % pi)      
圓周率:3.14

Note 最少要 1 個字元,取四捨五入到小數 2

In [98]:
print("圓周率:%6.2f" % pi)      
圓周率:  3.14

Note 最少要 6 個字元,取四捨五入到小數 2 位 => 發現多了兩個空白

Exercise

Q. 創建一個 my_name 變數,並存入自己的名字,接著利用 { }format 的方法,輸

Hello Kristen !!

Answers

In [99]:
my_name = "Kristen"
my_string = "Hello {} !!".format(my_name)
print(my_string)
Hello Kristen !!

補充


Note : Python 程式結構與語法

跳脫字元

  • 單引號:\'
  • 雙引號:\"
  • 反斜線:\\
  • tab:\t
  • 換行:\n
In [100]:
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

補充


string

  • 字串是由一個個字母組成的 list
In [101]:
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

補充


Note : 字串( string ) & 串列 ( list ) 都可以用的功能

  • len:計算長度
  • count:計算某個元素出現過幾次
  • 取初第 i 個位置的元素
In [102]:
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
In [103]:
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

補充


string

  • split (切割)
In [104]:
my_string = "Hello Kristen"
print (my_string.split(" "))
['Hello', 'Kristen']
In [105]:
print (my_string.split(" ")[0])
print (my_string.split(" ")[1])
Hello
Kristen

Note 依照空格切割

補充


string

  • replace (取代)
In [106]:
my_string = "Hello Kristen !!"
my_string = my_string.replace("Kristen" ,"Rick")
print(my_string)
Hello Rick !!

補充


Note : split 應用 (取出一篇文章中的單字)

In [107]:
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."
In [108]:
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.']
In [109]:
print ("文章中第二個字 : ",article.split(" ")[1])
文章中第二個字 :  Korea

補充


Note : replace 應用 (將文章中北韓替換掉)

In [110]:
article = "美國總統川普昨天警告北韓別再挑釁,否則將面臨「戰火與怒火」回擊。對此,白宮發言人桑德斯今天聲明,川普談話的語氣與力道,白宮國安會團隊及幕僚長凱利事先都知情。"
In [111]:
print (article)
美國總統川普昨天警告北韓別再挑釁,否則將面臨「戰火與怒火」回擊。對此,白宮發言人桑德斯今天聲明,川普談話的語氣與力道,白宮國安會團隊及幕僚長凱利事先都知情。
In [112]:
article=article.replace("北韓","朝鮮民主主義人民共和國")
print (article)
美國總統川普昨天警告朝鮮民主主義人民共和國別再挑釁,否則將面臨「戰火與怒火」回擊。對此,白宮發言人桑德斯今天聲明,川普談話的語氣與力道,白宮國安會團隊及幕僚長凱利事先都知情。