用戶登錄程序
username = "chenxi" passwed = "testki" counter = 0 while counter < 3: # 測試3次 user = input("輸入用戶名:") passw = input("輸入密碼:") if user == username and passw == passwed : print("登錄成功") break #退出 else: print("重新輸入") counter += 1
測試-1
D:\python\python.exe D:/untitled/dir/for.py 輸入用戶名:bhghjb 輸入密碼:njbmnbm 重新輸入 輸入用戶名:bhbjb 輸入密碼:nnbnbm 重新輸入 輸入用戶名:nnbmnb 輸入密碼:jhjh 重新輸入 Process finished with exit code 0
測試-2
D:\python\python.exe D:/untitled/dir/for.py 輸入用戶名:chenxi 輸入密碼:testki 登錄成功
打印0-9,小於5不打印
for i in range(10): if i < 5 : continue # 結束本次循環 print(i)
測試
D:\python\python.exe D:/untitled/dir/for.py 5 6 7 8 9
打印雙層循環
for i in range(10): print ("chenxi:",i) for j in range(10): print(j)
測試
D:\python\python.exe D:/untitled/dir/for.py chenxi: 0 0 1 2 3 4 5 6 7 8 9 chenxi: 1 0 1 2 3 4 5 6 7 8 9 chenxi: 2 0 1 2 3 4 5 6 7 8 9 chenxi: 3 0 1 2 3 4 5 6 7 8 9 chenxi: 4 0 1 2 3 4 5 6 7 8 9 chenxi: 5 0 1 2 3 4 5 6 7 8 9 chenxi: 6 0 1 2 3 4 5 6 7 8 9 chenxi: 7 0 1 2 3 4 5 6 7 8 9 chenxi: 8 0 1 2 3 4 5 6 7 8 9 chenxi: 9 0 1 2 3 4 5 6 7 8 9 Process finished with exit code 0
i小於5不循環
for i in range(10): if i < 5 : continue # 結束本次循環 print ("chenxi:",i) for j in range(10): print(j)
測試
D:\python\python.exe D:/untitled/dir/for.py chenxi: 5 0 1 2 3 4 5 6 7 8 9 chenxi: 6 0 1 2 3 4 5 6 7 8 9 chenxi: 7 0 1 2 3 4 5 6 7 8 9 chenxi: 8 0 1 2 3 4 5 6 7 8 9 chenxi: 9 0 1 2 3 4 5 6 7 8 9 Process finished with exit code 0
利用break當j=6時跳出本次循環體
for i in range(10): if i < 5 : continue # 結束本次循環 print ("chenxi:",i) for j in range(10): print(j) if j == 6 : break #當j=6時跳出循環體
測試
D:\python\python.exe D:/untitled/dir/for.py chenxi: 5 0 1 2 3 4 5 6 chenxi: 6 0 1 2 3 4 5 6 chenxi: 7 0 1 2 3 4 5 6 chenxi: 8 0 1 2 3 4 5 6 chenxi: 9 0 1 2 3 4 5 6 Process finished with exit code 0
利用標志物位跳出多層循環
# 小於5 不打印 exit_flag = False #設置exit_flag初始值 for i in range(10): if i < 5 : continue # 結束本次循環 print ("chenxi:",i) for j in range(10): print(j) if j == 6 : exit_flag = True# 當j = 6 時;修改exit_flag變量值為True break #當j=6時跳出循環體 if exit_flag: #判斷exit_flag=True時,跳出第二層循環體 break
測試
D:\python\python.exe D:/untitled/dir/for.py chenxi: 5 0 1 2 3 4 5 6