DAY 3
0
Big Data

## [第 03 天] 變數類型的轉換

``````days = 30
print("In order to become an ironman, you have to publish an article a day for " + days + " days in a row.")
``````

## 建立物件

Python 具備很便利的指派運算子像是：`+=``-=``*=``/=``%/` 讓我們的程式更簡潔，像是這段程式：

``````days = 30
days = days + 3
days # 33
``````

``````days = 30
days += 3
days # 33
``````

``````days = 30
days += 3
print(days) # 33
days -= 3
print(days) # 30
days *= 5
print(days) # 150
days /= 5
print(days) # 30.0
days %= 7
print(days) # 2.0
``````

## R 語言變數類型的轉換

``````days <- 30
paste("In order to become an ironman, you have to publish an article a day for", days, "days in a row.")
``````

R 語言轉換變數類型的函數都是以 `as.` 作為開頭然後將要轉換為的變數類型接於後面，方便我們記憶。

• `as.numeric()`：轉換變數類型為 numeric
• `as.integer()`：轉換變數類型為 integer
• `as.complex()`：轉換變數類型為 complex
• `as.logical()`：轉換變數類型為 logical
• `as.character()`：轉換變數類型為 character

``````my_logical <- TRUE
class(my_logical) # "logical"
as.numeric(my_logical) # 1
as.integer(my_logical) # 1
as.complex(my_logical) # 1+0i
as.character(my_logical) # "TRUE"
``````

## Python 變數類型的轉換

``````days = 30
print("In order to become an ironman, you have to publish an article a day for " + str(days) + " days in a row.")
``````

Python 轉換變數類型的函數：

• `float()`：轉換變數類型為 float
• `int()`：轉換變數類型為 int
• `complex()`：轉換變數類型為 complex
• `bool()`：轉換變數類型為 bool
• `str()`：轉換變數類型為 str

``````my_bool = True
print(type(my_bool)) # 'bool'
print(float(my_bool)) # 1.0
print(int(my_bool)) # 1
print(complex(my_bool)) # 1+0j
print(type(str(my_bool))) # 'str'
``````

57 人訂閱