1. 程式人生 > >Python3 原始數據類型和運算符

Python3 原始數據類型和運算符

num 浮點 優先 浮點數 除法 none == uic ant

# 整數
    3  # => 3

# 算術沒有什麽出乎意料的
    1 + 1  # => 2
    8 - 1  # => 7
    10 * 2  # => 20

# 但是除法例外,會自動轉換成浮點數
    35 / 5  # => 7.0
    5 / 3  # => 1.6666666666666667

# 整數除法的結果都是向下取整
    5 // 3     # => 1
    5.0 // 3.0 # => 1.0 # 浮點數也可以
    -5 // 3  # => -2
    -5.0 // 3.0 # => -2.0

# 浮點數的運算結果也是浮點數
    3 * 2.0 # => 6.0

# 模除
    7 % 3 # => 1

# x的y次方
    2**4 # => 16

# 用括號決定優先級
    (1 + 3) * 2  # => 8

# 布爾值
    True
    False

# 用not取非
    not True  # => False
    not False  # => True

# 邏輯運算符,註意and和or都是小寫
    True and False #=> False     False or True #=> True # 整數也可以當作布爾值     0 and 2 #=> 0     -5 or 0 #=> -5     0 == False #=> True     2 == True #=> False     1 == True #=> True # 用==判斷相等     1 == 1 # => True     2 == 1 # => False # 用!=判斷不等     1 != 1 # => False     2 != 1 # => True # 比較大小     1 < 10 # => True     1 > 10 # => False     2 <= 2 # => True     2 >= 2 # => True # 大小比較可以連起來!     1 < 2 < 3 # => True     2 < 3 < 2 # => False # 字符串用單引雙引都可以     "這是個字符串"     ‘這也是個字符串‘
# 用轉義字符\來進行字符串的轉義
    ‘I\‘m \"OK\"!‘ # => I‘m "OK"!
# \n
表示換行,\t表示制表符,\\表示\本身
    print("\\\t\\") # => \    \
# 原始字符串。r"" 表示""內的字符串不轉義
    print(r"\\\t\\") # => \\\t\\
# 用加號連接字符串     "Hello " + "world!" # => "Hello world!" # 字符串可以被當作字符列表     "This is a string"[0] # => ‘T‘ # 用.format來格式化字符串     "{} can be {}".format("strings", "interpolated") # => ‘strings can be interpolated‘ # 可以重復參數以節省時間     "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")             # => "Jack be nimble, Jack be quick, Jack jump over the candle stick" # 如果不想數參數,可以用關鍵字     "{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" # 如果你的Python3程序也要在Python2.5以下環境運行,也可以用老式的格式化語法     "%s can be %s the %s way" % ("strings", "interpolated", "old") # => ‘strings can be interpolated the old way‘ # None是一個對象     None # => None # 當與None進行比較時不要用 ==,要用is。is是用來比較兩個變量是否指向同一個對象
。     "etc" is None # => False     None is None # => True # None,0,空字符串,空列表,空字典都算是False。所有其他值都是True。
    bool(0) # => False     bool("") # => False     bool([]) # => False     bool({}) # => False

Python3 原始數據類型和運算符