Python縮進原則
- 頂級代碼必須頂行寫,即如果一行代碼本身不依賴於任何條件,那它必須不能進行任何縮進
- 同一級別的代碼,縮進必須一致
- 官方建議縮進用4個空格
Python程序語言指定任何非0和非空的布爾值為true,0 或者空的布爾值為false。
if判斷
Python 編程中的 if判斷語句用於控制程序的執行,基本形式為:
if 條件:
子代碼1
子代碼2
子代碼3
…………
else:
子代碼4
子代碼5
子代碼6
其中"判斷條件"成立時(非零),則執行后面的語句,而執行內容可以多行,以縮進來區分表示同一范圍。
else 為可選語句,當需要在條件不成立時執行內容則可以執行相關語句
具體舉栗說明
score=input('>>: ') score=int(score) if score >= 90: print('A')#用戶輸入的數大於等於90時走這里 elif score >=80: print('B')#用戶輸入的數大於等於80時走這里 elif score >=70: print('C')#用戶輸入的數大於等於70時走這里 elif score >=60: print('D')#用戶輸入的數大於等於60時走這里 else:#用戶輸入的數不符合以上規范時走這里 print('E')
python 的多個條件判斷,用 elif 來實現,如果需要對多個條件進行同時判斷時,可以使用or和and, or (或)表示兩個條件有一個成立時判斷條件成功;and (與)表示只有兩個條件同時成立的情況下,判斷條件才成功。
num1=6 num2=10 if num1>3 and num2<20: print('num1>3並且num2<20同時成立時走這里') else: print('有一個條件不滿足') if num1>3 or num2<5: print(' 只要num1>3和num2<5兩者中走一個成立就走這里') else: print('兩個條件都沒有被滿足')
while循環
what's the while 循環?
當程序需要循環使用某段代碼時,對這段代碼進行復制粘貼就可以,可是這是極其low的方法。我們可以使用while循環。
while 語句用於循環執行程序,即在某條件下,循環執行某段程序,以處理需要重復處理的相同任務。執行語句可以是單個語句或語句塊。判斷條件可以是任何表達式,任何非零、或非空的值均為true。當判斷條件假false時,循環結束。
基本形式為:
while 條件:
循環體的代碼1
循環體的代碼2
循環體的代碼3
count=0 while count < 10: print(count) count+=1 while True: #死循環 print('ok') while 1: #死循環 print('ok')
當while的條件始終為True或1(1就代表True,0代表False)時,循環就進入了死循環,即循環永遠不會結束。死循環是有應用場景的,不過最后肯定需要某個機制幫助我們跳出死循環,這里就用到了break功能。
break:跳出本層循環
break的功能就是時循環結束,無論原來的代碼進行到何種程度,只要碰到break,這層縮進的代碼就結束,接下來運行上一層縮進的內容。下面用代碼舉個栗子
count=0#初始的count值為0 while count < 10:#當count<10時執行縮進的語句 if count == 5:#當count的值等於5時執行縮進語句 break#當count的值等於5時停止循環 print(count)#當count的值不等於5時執行 count+=1#即count=count+1 print('循環結束')#停止循環后執行
continue:跳出本次循環
continue 語句用來告訴Python跳過當前循環的剩余語句,然后繼續進行下一輪循環。它與break不同的地方是break一執行本層的循環就終止了然后執行while循環之后的同級代碼,而continue只是使continue以后的代碼被跳過,循環繼續執行,即碰到continue后本次循環結束進入下一次循環。下面用代碼舉個栗子
#輸出0123789 count=0#初始的count值為0 while count < 10:#當count<10時執行縮進語句 if count >=4 and count <=6:#當count大於等於4並且小於等於6時執行縮進語句 count += 1#count=count + 1 continue#本次循環結束,以下代碼不執行,返回while位置 print(count) count+=1
while循環也可以和else連用,並且在最后執行,而且只能在while循環沒有break打斷的情況下才執行。
嵌套的定義:在循環中又套用了循環,具體實例會在下面的習題中出現
for循環
what's the for 循環?
與while類似也是循環語句,for循環可以遍歷任何序列的項目,可循環取出字符串、列表、元祖、字典中的各元素。
基本的語法格式為
for iterating_var in sequence: statements(s)
用代碼舉栗說明
msg1='hello' msg2=['a','b','c','d','e'] msg3=('a','b','c','d','e') for i in range(len(msg1)):#range是范圍,即當i在msg1的長度范圍以內時執行以下代碼 print(i,msg1[i])#輸出的是元素的位置序數和元素 #結果為1 h # 2 e # 3 l # 4 l # 5 o #range顧頭不顧尾,默認從0開始 for i in range(1,10,1):#最后一個1的意思是步距為1 print(i) #for循環也可與break、continue、else連用,方法與while相似
用for循環對字典進行遍歷
#循環取字典的key for k in info_dic: print(k) #循環取字典的value for val in info_dic.values(): print(val) #循環取字典的items for k,v in info_dic.items(): #k,v=('name', 'egon') print(k,v)
這里利用for循環順便補充幾個小知識點
albums = ('Poe', 'Gaudi', 'Freud', 'Poe2') years = (1976, 1987, 1990, 2003) #sorted:排序 for album in sorted(albums): print(album)#字符串按長度排序 #reversed:翻轉 for album in reversed(albums): print(album) #enumerate:返回項和 for i in enumerate(albums,100):#默認從0開始 print(i) '''(100, 'Poe') (101, 'Gaudi') (102, 'Freud') (103, 'Poe2')''' #zip:組合,一一對應並以元祖的形式返回 for i in zip(albums,years): print(i) '''('Poe', 1976) ('Gaudi', 1987) ('Freud', 1990) ('Poe2', 2003)'''
for循環和while循環一樣都可以進行嵌套,下面用一個九九乘法表作為舉例。
for line in range(1,10): for row in range(1,line+1): print('%s*%s=%s'%(line,row,line*row),end=' ') print() #print默認end='\n',即會自動回車,這里設置end=' '就不會自動換行了
這里插一個小知識點
占位符:%s(可以為字符串占也可以為數字),%d(只能作為數字的占位符)。
占位符即實現占位用的,之后可以進行傳值。傳值方式如上面的九九乘法表中所示,每個占位符只能傳一個值
習題
最后引入幾道習題,幫助更好的了解while循環
習題一:輸出1到100所有的數字
#使用while循環 count=0 while count<=100:#只要比100小就不斷執行以下代碼 print('number',count) count+=1#即每執行一次就把count+1 #當count>100時,判斷就為false,自動跳出循環 #使用for循環 for i in range(101):#顧頭不顧尾 print(i)
習題二:輸出1到100內的所有偶數,包括100
#使用while循環 count = 0 while count <= 100 : if count % 2 == 0:#是偶數 print('number',count) count+=1 #使用for循環 for i in range(1,101): if i%2==0: print(i)
習題三:輸出1到100內的所有奇數,包括100
#使用while循環 count = 0 while count <= 100 : if count % 2 == 1:#是奇數 print('loop',count) count+=1 #使用for循環 for i in range (1,100): if i%2==1: print(i)
習題四:輸出1-2+3-4+5-6+7-8....+99的和
sum=0 for i in range(1,100): if i%2==1: sum+=i elif i%2==0: sum+=-i print(sum)
習題五:輸出1-9,並在最后輸出一段話
count=0 while count < 10: if count == 3: count+=1 continue print(count) count+=1 else: #最后執行 print('在最后執行,並且只有在while循環沒有被break打斷的情況下才執行') #0 #1 #2 #4 #5 #6 #7 #8 #9 #在最后執行,並且只有在while循環沒有被break打斷的情況下才執行
習題六:用戶登錄程序交互小習題
while True:#死循環 name=input('please input your name: ')#讓用戶自行輸入名字 password=input('please input your password: ')#讓用戶自行輸入密碼 if name == 'jack' and password == '123':#如果輸入的名字為jack並且密碼是123 print('login successfull')#輸出登陸成功 while True:#死循環 cmd=input('>>: ')#讓用戶輸入命令 if cmd == 'quit':#如果輸入的命令是quit的話 break#本層死循環結束,即內層死循環結束 print('====>',cmd)#如果輸入的命令不是quit的話,打印輸入的命令 break#本層死循環結束,即外層死循環結束 else:#如果輸入的名字不為jack或者密碼不是123 print('name or password wrong') #輸出錯誤,並重新輸入名字和密碼
習題七:猜年齡的游戲
#允許猜3次喬布斯的年齡 JOBS_AGE=55#定義一個常量,喬布斯55歲 count=1#次數為1 while True:#死循環 if count>3:#當次數超過3時 break#循環結束 age=input('猜猜年齡:')#用戶交互,讓用戶輸入他猜的年齡 age=int(age)#輸入的內容是字符串的格式,需強轉成數字格式才可與數字進行比較 if age>JOBS_AGE: print("你猜的太大啦") elif age<JOBS_AGE: print("你猜的太小啦") else: print("恭喜你猜對了") break#猜對了以后執行,即循環結束 count+=1#沒猜對的情況下count會加1,當count>3的時候就不讓猜咯
進階大作業一:實現簡易購物清單
要求如下:給出以下購物列表,用戶輸入想要購買的物品,之后讓用戶輸入想要購買該物品的數量,打印物品名、價格即數量。用戶可循環輸入
msg_dic={
'iPhone':4000,
'apple':10,
'mac':8000,
'lenovo':3000,
'chicken':28
}

msg_dic={ 'iPhone':4000, 'apple':10, 'mac':8000, 'lenovo':3000, 'chicken':28 } goods_l=[] while True: for k in msg_dic: print('NAME:<{name}> PRICE:<{price}>'.format(name=k,price=msg_dic[k])) name=input('please input your goods name:').strip() if len(name)==0 or name not in msg_dic:continue while True: count=input('please input your count:').strip() if count.isdigit():break goods_l.append((name,msg_dic[name],int(count))) print(goods_l)
進階大作業二:實現簡易工資條
要求如下:給出一個系統讓用戶輸入自己的名字、密碼、工資和工作時長,系統中可供用戶查詢自己的總工資和用戶身份,查詢結束后可退出程序。(jobs是頂級用戶(super user),cook和cue是普通用戶(normal user),其他皆為不知名用戶(unknown user)

tag = True while tag: user = input("請輸入用戶名:") if user == "": print("用戶名不能為空,請重新輸入:") continue password = input("請輸入密碼:") if password == "": print("密碼不能為空,請重新輸入:") continue work = input("請輸入工作了幾個月") if work == "" or work.isdigit() == False: print("工齡不能為空且必須為整數,請重新輸入:") continue money = input("請輸入工資:") if money == "" or money.isdigit() == False: print("工資不能為空且必須為整數,請重新輸入:") continue print( ''' 1查詢總工資 2查詢用戶身份 3退出程序 ''' ) while tag: choose = input('>>') if choose == "" or choose.isdigit() == False: print("輸入有誤,請重新輸入") continue if choose == '1': print(''' 總工資為:%s 1查詢總工資 2查詢用戶身份 3退出程序 ''' % (int(work)*int(money))) elif choose == '2': if user == 'jobs': print(''' super user 1查詢總工資 2查詢用戶身份 3退出程序 ''') elif user == 'cook' or 'cue': print(''' normal user 1查詢總工資 2查詢用戶身份 3退出程序 ''') else: print(''' unknow user 1查詢總工資 2查詢用戶身份 3退出程序 ''') elif choose == '3': tag = False continue else: print('沒有這個選項') continue
進階大作業三:實現省市縣三級菜單
要求如下:給出一個三級菜單,要求能循環輸出省、市、縣

menu = { '浙江省':{ '杭州市':{ '西湖區':{ '西湖':{}, '雷峰塔':{}, '宋城':{} }, '臨安區':{ '天目山':{}, '大明山':{}, '白水澗':{}, }, '蕭山區':{ '機場':{}, }, }, '余杭區':{ '西溪濕地':{}, '良渚遺址':{}, '塘棲古鎮':{}, }, '上城區':{}, '下城區':{}, }, '上海':{ '閔行':{ "人民廣場":{ '炸雞店':{} } }, '閘北':{ '火車戰':{ '攜程':{} } }, '浦東':{}, }, '山東':{}, }

menu = { '浙江省':{ '杭州市':{ '西湖區':{ '西湖':{}, '雷峰塔':{}, '宋城':{} }, '臨安區':{ '天目山':{}, '大明山':{}, '白水澗':{}, }, '蕭山區':{ '機場':{}, }, }, '余杭區':{ '西溪濕地':{}, '良渚遺址':{}, '塘棲古鎮':{}, }, '上城區':{}, '下城區':{}, }, '上海':{ '閔行':{ "人民廣場":{ '炸雞店':{} } }, '閘北':{ '火車戰':{ '攜程':{} } }, '浦東':{}, }, '山東':{}, } exit_flag = False current_layer = menu layers = [menu] print(layers) while not exit_flag: for k in current_layer: print(k) choice = input(">>:").strip() if choice == "b": current_layer = layers[-1] #print("change to laster", current_layer) layers.pop() elif choice not in current_layer:continue else: layers.append(current_layer) current_layer = current_layer[choice]