python基礎二
1、while循環
1、while循環 無線循環
2、while 循環的結構
while 條件:
循環體
3、如何終止循環
1、改變條件(標誌位的概念)
flag = True
while flag:
print(‘開始循環‘)
flag = False #改變條件
2、break跳出循環
flag = True
while flag:
print(‘hello Linda‘)
break #break跳出循環
3、練習
1、打印1--100
方法一:
flag = True
i = 1
while flag:
print(i)
i += 1
if i == 101:
flag = False
方法二:
i = 1
while i < 101
print(i)
i += 1
2、計算1+2+3+、、+100
方法一:
flag = True
i = 1
count = 0
while flag:
count += i
i += 1
if i == 101:
falg = False
print(count)
方法二:
i = 1
count = 0
while True:
count += i
i += 1
if i == 101:
break
print(count)
方法三:
i = 1
count = 0
while i < 101:
count += i
i += 1
print(count)
4、continue:借宿本次循環,繼續下一次循環
flag = True
while flag:
print(111)
flag = False
continue
print(222)
最終結果:111
5、while else 結構:如果while循環被break打斷,則else不會被執行
1、 i = 1
while i < 5:
print(i)
i += 1
else:
print(10)
執行結果是:1,2,3,4,10
2、 i = 1
while i < 5:
print(i)
i += 1
if i == 3:break
else:
print(6666)
執行結果是:1,2
6、應用場景:
1、驗證用戶名密碼,重新輸入這個功能需要用while循環
2、無限次的顯示頁面,無限次的輸入
2、格式化的輸出
1、制作一個模板,某些位置的參數是動態的,像這樣,就需要格式化輸出
2、字符串的動態替換
3、常見形式:
name = input(‘請輸入你的姓名:‘)
age = int(input(‘請輸入你的年齡:‘))
print(‘你的姓名是:%s,你的年齡是:%d‘ % (name,age))
print(‘你的姓名是:%(name)s,你的年齡是%(age)d‘ % {‘name‘:name,‘age‘:age})
註意:在格式化輸出中,只想單純的表示一個%時,應該用%% 表示
msg = ‘我叫%s,今年%d,我的學習進度1%%‘ % (‘張三‘,28)
print(msg)
3、運算符
1、== 比較兩邊的值是否相等
2、= 賦值運算
3、!= 不等於
4、+= -= *= /= **= //= %= 等等
5、邏輯運算符 and or not
6、優先級 ()>>not>and>or
7、前後條件為比較運算
print(1 < 2 or 3 > 1)
print(1 < 2 and 3 > 4)
print(1 < 2 and 3 > 4 or 8 < 6 and 9 > 5 or 7 > 2)
print(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8)
print(1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)
執行結果為:True、False、True、False、False
8、前後兩邊的條件為數值
x or y,if x isTrue,return x
x is False,return y
print(1 or 2)
print(1 and 2)
print(5 or 2)
print(5 and 2)
print(0 or 2)
print(-1 or 2)
執行結果為:1、2、5、2、2、-1
9、補充類型轉換
1、int轉bool 0為False,非0都是True
2、bool轉int True 1 False 0
4、編碼初識
ASCII: 最初版本的密碼本:所有的英文字母,數字,特殊字符。
最初:
一個字符 000 0001
後來優化
A: 01000001 8位 == 1個字節
a: 01100001
c: 01100011
對於ASCII碼來說:
‘hello laddy‘ 11個字符,11個字節。
unicode:萬國碼,將所有國家的語言文字都寫入這個密碼本。
起初:1個字符 16位 2個字節表示。
A: 01000001 01000001
b: 01000001 01100001
中:01000001 01100101
改版:1個字符 32位 4個字節表示。
A: 01000001 01000001 01000001 01000001
b: 01000001 01100001 01000001 01000001
中:01000001 01100101 01000001 01000001
浪費資源,占空間。
utf-8: 最少用8位表示一個字符。
A: 01000001 一個字節
歐洲文字: 01000001 01100001 兩個字節
中:01000001 01100101 01000001 三個字節
‘old男孩‘:9個字節
gbk:國標,只包含 中文,英文(英文字母,數字,特殊字符)
A: 01000001 一個字節
中:01000001 01100101 兩個字節
8 bit == 1bytes
1024bytes == kb
1024kb == 1MB
1024MB == 1GB
1024GB == 1TB
1024TB == 1PB
python基礎二