一:使用Python的while嵌套循環打印如下圖形:
*
* *
* * *
* * * *
* * * * *
i = 1 while i <= 5: j = 1 str = '' while j <= i: str = str + '* ' j += 1 print(str) i += 1
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
1 i = 1 2 while i <= 5: 3 j = 1 4 str = '' 5 while j <= i: 6 str = str + '* ' 7 j+=1 8 print(str) 9 i+=1 10 i = 4 11 while i>=1: 12 j=i 13 str = '' 14 while(j>=1): 15 str = str + "* " 16 j-=1 17 print(str) 18 i-=1
總結:之前學的Java,寫習慣了,Python有點不習慣,他的代碼特別靈活,按行縮進,稍不注意就陷入死循環;但是很好玩;哈哈!
二:Python嵌套循環輸出九九乘法表
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
1 i = 1 2 while i <= 9: 3 j = 1 4 while j <= i: 5 print("%d*%d=%-2d"%(j,i,j * i), end=' ') 6 j += 1 7 print("\n") 8 i += 1
三:實現簡單的用戶登錄控制
1 i =0 2 userName = 'Python' 3 userPassword = '123456' 4 while i<3: 5 name = input("請輸入用戶名:") 6 password = input("請輸入密碼:") 7 if(name==userName and password==userPassword): 8 print("登陸成功!") 9 break 10 elif(name==userName): 11 print("密碼有誤,請重新輸入!") 12 elif(password == userPassword): 13 print("用戶名輸入有誤,請重新輸入!") 14 else: 15 print("用戶名和密碼錯誤!") 16 i+=1; 17 print("溫馨提示:您還有%d次登錄機會"%(3-i)) 18 print("今天登陸次數已達上限,今晚想想;明天再來哈!")