Python3 基礎學習之基本數值賦值、型別轉換

ZY_FlyWay發表於2018-01-20

 上一篇介紹了Mac環境的安裝,安裝完之後,我們需要一個編輯器來寫Python程式碼。為了便於學習,我們可以使用Python自帶的IDLE,類似Xcode的playGround。就在Python3資料夾裡,開啟就行了。


這篇主要介紹數字的運算和賦值,新手入門整理和歸類。

賦值

Python雖然是強型別語言,但是有自己的型別判斷機制,所以我們無需判斷資料型別。

整型、浮點型賦值:

a=1
>>> a
1
>>> b=1.2345
>>> b
1.2345

 科學計演算法賦值:

>>> c=1e5
>>> c
100000.0
>>> d=2e-3
>>> d
0.002

不同進位制賦值:

 二進位制:0b

 八進位制:0o

 十六進位制:0x

>>> e=0b11
>>> e
3 
>>> f=0o17
>>> f
15
>>> g=0x1a
>>> g
26
>>> 

型別轉換

float 轉int :是用int()函式就行轉換,可以吧float轉成int ,規律是捨棄小數部分。

>>> f=1.6
>>> int(f)
1
>>> f=-1.6
>>> int(f)
-1

str轉int:這裡要求字串必須是int型別否則報錯

>>> g="123abc"
>>> int(g)
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    int(g)
ValueError: invalid literal for int() with base 10: '123abc'
>>> g="1.2345"
>>> int(g)
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    int(g)
ValueError: invalid literal for int() with base 10: '1.2345'
>>> g="1234"
>>> int(g)
1234


總結:
同理int、str轉float把int()函式換成float()函式即可。int、float轉str 用str()即可。

>>> str(123)
'123'
>>> str(1.23)
'1.23'
>>> float(str(1.23))
1.23


相關文章