1. 程式人生 > 其它 >運算子 2021.07.29

運算子 2021.07.29

今日內容

1、記憶體管理機制

垃圾回收機制GC

1.引用計數:被引用的個數

2.分代回收:為了解決引用計數的效率問題

問題:1.個別垃圾可能得不到及時的清理

3.標記/清除:為了解決迴圈引用帶來的記憶體洩露問題

核心:一個變數值沒有任意一條可以從棧區出發到自己的引用,就會把標記下 來,方便後續清除。

小整數池

2.與使用者互動

接受使用者輸入

python3中的input會把使用者輸入的所有內容都儲存成str型別

python2中raw_input()與python3的Input一樣

age = int(input("請輸入您的年齡:"))
print(age)

補充:int可以把純數字組成的字串轉換整型

格式化輸出

print("my name is egon and my age is 18")
str_2 = "my name is %s and my age is %s" % ("egon", 18)
print(str_2)
str_1 = "my name is %s and my age is %s" % ("egon", [1, 2, 3])
print(str_1)

3.運算子

3.1算數運算子:+、-、*、/、//、%、**

補充:python是一門解釋型、強型別、動態語言

GO是一門編譯型型、強型別、靜態語言

3.2比較運算子

判斷是否相等,沒有型別限制

print("abc" == 10) # 判斷的是值及其型別是否相等
print("abc" != 10) # 判斷的是值及其型別是否相等
x = "abcdefg"
y = "abz"
print(x > y)

x = [111, 'abcdefg', 666]
y = [111,'z']
print(x > y)

3.3賦值運算子

3.3.1 增量賦值

age = 18
age += 1 # age = age + 1
age -= 1 # age = age - 1
print(age)

3.3.2 鏈式賦值

x = y = z = 100

3.3.3 交叉賦值

 x = 100 
y = 200

temp = x
x = y
y = temp
del temp

x,y=y,x
print(x) # 200
print(y) # 100

3.3.4 解壓賦值

salaries = [11, 22, 33, 44, 55]
mon1 = salaries[0]
mon2 = salaries[1]
mon3 = salaries[2]
mon4 = salaries[3]
mon5 = salaries[4]

mon1, mon2, mon3, mon4, mon5 = salaries
mon1, mon2, mon3, mon4, mon5 ,mon6= salaries # 錯誤
mon1, mon2, mon3, mon4 = salaries # 錯誤

print(mon1, mon2, mon3, mon4, mon5)

mon1,mon2,*_ ,last = salaries
print(mon1)
print(mon2)
print(_)

_,*x,_ = salaries
print(x)


# 瞭解:
# x, y, z = {'k1': 111, 'k2': 222, 'k3': 3333}
# x, y, z = "abc"
# print(x,y,z)

3.4 邏輯運算子


# 邏輯運算子是用來運算條件的,那什麼是條件???
# 只要結果為布林值的都可以當做條件

# 總結:邏輯運算子,算的是顯式的布林值或者隱式的布林值

#3.4.1 not
print(not 10 > 3)
print(not False)
print(not 123)

# 3.4.2 and: 連結多個條件,多個條件必須同時成立,最終結果才為True
print(10 > 3 and True and 'xx' == 'xx')
print(10 > 3 and False and 'xx' == 'xx')

print(10 > 3 and None and 'xx' == 'xx')
print(10 > 3 and True and 'xx' == 'xx' and 111)


# 3.4.3 or: 連結多個條件,多個條件但凡有一個成立,最終結果就為True
print(10 > 3 or False or 'xx' == 'xx')

print(0 or None or "" or 1 or True or 10 > 3)


# 強調:優先順序not>and>or
print(3 > 4 and 4 > 3 or 1 == 3 and not 'x' == 'x' or 3 > 3)
#(3 > 4 and 4 > 3) or (1 == 3 and not 'x' == 'x') or 3 > 3

# ps:短路運算-》偷懶原則


# 3.5 成員運算子
print("abc" in "xxxabcxxxxx")
print(111 in [222,333,1111])
print('k1' in {'k1':111,'k2':222}) # 字典的成員運算判斷的是key
print('k3' not in {'k1': 111, 'k2': 222}) # 推薦
print(not 'k3' in {'k1': 111, 'k2': 222}) # 不推薦

# 3.6 身份運算子:is判斷的是id是否一樣
x = 100
y = x
print(x is y)
print(x == y)


l1 = [111]
res=l1.append(222)
print(res == None) # 可以,但是不夠好
print(res is None) # 推薦

總結:==成立is不一定成立,但是is成立==一定成立

is:是比較記憶體地址一不一樣

==:是比較值是否相等