2024-06-06|閱讀時間 ‧ 約 24 分鐘

[Python][ITS] #1. 資料型別與運算子的操作

主要的資料型別 ( int, str, bool, float)

int 和 float 資料型別都是在儲存數字資料時使用的,搭配的運算字要特別注意的是除號有分 // 和 /。

raw-image

例子:

x = 14
y = 3
print(x/y) # 結果會是 4.666666666666667
print(x//y) # 結果會是 4

注: // 會是無條件捨棄小數位的值。

bool 型別的值只有 False, True這兩種值。

注1: 不要跟str的 "False" 和 "True" 搞混。沒有單引號或雙引號包起來的字串值。

注2: int和float的變數值是0的話,就當成是False。非0的話就當成是True。

例子:

a = 0
if a:
print("True")
else:
print("False")
# 結果會是印出False

注3: str的變數值若是空字串 ("") 的話,就當成是False。非空的字串就當成是True。

例子:

txt = ""
if txt:
print("True")
else:
print("False")
# 結果會印出False

資料型別之間的操作及轉換

基本原則:由 input( ) 函式取得的值一律是str的型別,若要當成是數字型別來操作的話需要以eval( ), int( ), float( )等轉換函式處理過才能當成是數字來處理。

例子:

aa = int(input("please input the price:"))
please input the price:100
bb = aa * 0.6
print(bb) # 結果會印出 60.0

type(aa)  # 結果會印出 <class 'int'>
type(bb)  # 結果會印出 <class 'float'>

aa = input("please input the price:")
please input the price:100
bb = aa * 0.6 # 結果會印出如下的Error message, 因為str型別無法與float型別作運算

Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
bb = aa * 0.6
TypeError: can't multiply sequence by non-int of type 'float'

運算子的先後順序

參考連結: https://docs.python.org/3/reference/expressions.html#operator-precedence

注: 基本上是由左到右的順序來處理, 但是, 需要注要各別運算子在同一行時,有其先後順序,這時候就要先以高優先的運算子先處理。

括號"( ), [ ], { }" > 指數"**" > 正負號 "+, -, ~" > 乘除 "*, /, //, %" > 加減 "+, -" > bit shift " >>, <<" > bit operation " &, |, ^"

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.