# 在 Python 中檢查變數型別

Sahil Bhosale 2023年10月10日

## Python 中的變數及其型別

``````# Variable of type String
newVariable = "This is a new variable"
print(newVariable)

# Variable of type Boolean
booleanVariable = True
print(booleanVariable)

# Variable of type Float
floatVariable = 20.30
print(floatVariable)
``````

``````This is a new variable
True
20.3
``````

## 在 Python 中檢查變數的型別

1. 數字：這一類包含整數、浮點數和複數。
2. 字串：它是 Unicode 字元的序列。Unicode 是一個字符集，包含了全世界所有語言的字元和符號。
3. 布林型：布林型代表 `True``False`
4. 列表：它是不同資料型別元素的有序集合。列表是可以突變的，也就是說在建立了列表之後，列表裡面的值是可以改變的。
5. 元組：它也是不同資料型別元素的有序集合。它也是不同資料型別元素的有序集合。列表和元組的唯一區別是，元組是不可變的，也就是說一旦建立了元組，就不能修改。
6. 集合：集合是一個無序的不含重複元素的集合。
7. 字典：它是鍵值對的無序集合。鍵和值可以是任何型別。

## 使用 `type()` 函式來檢查 Python 中的變數型別

``````myInt = 50
print(type(myInt))

myFloat = 10.50
print(type(myFloat))

myString = "My name is Adam"
print(type(myString))
``````

``````<class 'int'>
<class 'float'>
<class 'str'>
``````

## 在 Python 中使用 `isinstance()` 函式檢查變數型別

``````# A variable 'myVar' having a value 50 inside
myVar = 50

# Printing the value returned by isinstance() function
print("Does myVar belongs to int: ", isinstance(myVar, int))

# This will return false
# As the value passed is string and you are checking it with int
print("Does string belongs to int: ", isinstance("My String", int))

complexNo = 1 + 2j
print("This this number complex: ", isinstance(complexNo, complex))
``````

``````Does myVar belongs to int: True
Does string belongs to int: False
This this number complex: True
``````

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

LinkedIn