Day2 Python學習筆記

2021-09-24 10:36:03 字數 3325 閱讀 5346

1.1 if … (else …)

只考慮一種情況 。

例:

print(111)

if 5>4 :

print(222)

print(333)

考慮兩種情況,且為互補關係。

例:

if 4 > 5:

print('4>5')

else:

print('5>4')

1.2 if … elif … else …

考慮多種情況。

例:

score=int(input('請輸入你的成績:'))

if score==100:

print('perfect')

elif score>90:

print('excellent')

elif score>80:

print('great')

elif score>70:

print('good')

else:

print('keep trying')

1.3 巢狀
print("請輸入三個不相等的數:")

a=int(input('a:'))

b=int(input('b:'))

c=int(input('c:'))

if a>b:

if b>c:

print('a>b>c')

else:

if a>c:

print('a>c>b')

else:

print('c>a>b')

else:

if a>c:

print('b>a>c')

else:

if b>c:

print('b>c>a')

else:

print('c>b>a')

2.1 無限迴圈

沒有設定結束迴圈的條件時,即為無限迴圈。

例:

while  1:

print('根本停不下來')

注:"while 1:"的效率高於"while true:"。

2.2 條件迴圈

設有結束迴圈的條件時,為條件迴圈。

例:計算1-100的和:

count = 1

sum = 0

while count <= 100:

sum += count

print(count)

count += 1

print("1-%d的和為:%d" %(count-1,sum))

2.3 break和continue

break為結束迴圈,continue為結束本次迴圈。

例:

count = 0

while count < 100:

count += 1

if count%2 == 0:

continue

if count > 50:

break

print(count)

%:佔位符,s:字串,d:數字

%%:顯示%

例:

name = input('請輸入姓名:')

age = int(input('請輸入年齡:'))

msg = '我是%s,今年%d歲。' % (name, age)

print('我是%s,今年%d歲。' % (name, age))

當while不被break打斷時,執行else的內容。

例:

i = 0

while i < 10:

i += 1

if i == 8:

break

print(i)

else:

print("成功輸出1-10。")

電腦傳輸、儲存實際上都是在使用二進位制編碼:01。

5.1 ascii碼

美國建立了ascii碼

0000 0001   8位(bit ) == 1位元組(byte) 1024byte == 1kb 1024kb==1mb 之後還有g t p e z

5.2 unicode碼

為解決全球化文字問題,建立了萬國碼,unicode

最開始用1個位元組表示所有英文,特殊字元,數字等等;用2個位元組表示中文。由於2個位元組不能表示9萬多個中文,因此用4個位元組表示中文。

5.3 utf - 8

utf - 8:unicode公升級版。英文本母用1個位元組表示,歐洲文字用2個位元組表示,中文用3個位元組表示。

5.4 gbk

gbk:在國內使用,英文用1個位元組表示,中文用2個位元組表示。

注:utf-8和gbk的轉換要通過unicode。

6.1 and or not

優先順序:() > not > and > or

例:

print(2 >1 and (3 > 1 or 2 >3))

print(2 > 1 and 3 > 4 and 2 > 5 or 2 < 4 and 1 > 3 or 2 > 3)

6.2 x or y 和 x and y的結果

x or y的結果:x為true返回x,x為false返回y

因為:or有乙個為真則為真,乙個為假則取決於另乙個

x and y的結果: x為true返回y,x為false返回x

因為:and有乙個為假則為假,乙個為真則取決於另乙個

例:

print(1 or 3)

print(0 or 3)

print(1 and 2)

print(0 and 2)

6.3 bool和int的轉換

bool轉換為int:true>1、false>0

int轉換為bool:0>false、其他均為true

print(int(true))

print(bool(-3))

print(bool(0))

6.4 1 > 2 and 3 or 4 and 3 < 2的結果

比較運算的結果為bool值,遵循x or y和x and y的規律,注意x、y的格式為bool或int即可。

例:

print(3 > 4 or 0)

print(1 > 2 and 3 or 4 and 3 < 2)

附:參考運算子優先順序

Day2 Python學習筆記

師從 小甲魚 and 與運算 or 或運算 not 非運算 非0整數全解釋為true randint隨機輸入乙個數字,randint a,b 隨機輸入乙個a b之間的數字。需import random。import random print 我愛兜兜 answer random.randint 1,...

day2 python學習筆記 chapter4

1.標準型別 integer,boolean,long integer,floating point real number,complex number,string,list,tuple,dictionary 其他內建型別 型別,null物件 none 檔案,集合,函式,模組,類 2.type ...

day2 Python學習之路筆記(2)

1.1.我們寫好的.py檔案頭沒有加 coding utf 8 這樣的宣告,那麼在windows終端中呼叫python2直譯器執行時,檔案中的中文會顯示亂碼,為何?原來我們windows終端是以gbk編碼來讀的,而python2中不是預設的utf8的編碼格式。呼叫python3直譯器就沒問題,有中文...