自學Python2.9-循環(while、for)
1. while循環
Python中while語句的一般形式:
while 判斷條件:
語句
- 作用:提高開發效率,提高代碼重用型,便於后期代碼的維護!
- 注意:在Python中沒有do..while循環
舉例1:打印十行‘Hello World’
i = 0 #初始化變量操作
#while循環的判斷
while i < 10: #表達式結果真則進入循環內容,表達式結果為假則終止循環!
print('Hello World') #循環內容
i +=1 #變量自增或者自減條件

舉例2:計算1—100的和
n = 100;sum = 0;counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和為: %d" % (n, sum))

舉例3:打印1行10列的星星
i = 0
while i < 10:
print('☆',end = '') # 取消print里面默認的換行符號,是輸出的值橫排顯示
i += 1

舉例4:打印8行5列的星星
j = 0 # 定義初始化j表示行數
while j < 8: #定義循環8次,生成打印1行10列的星星
i = 0 # 定義初始化i表示列數
while i < 5:
print('★', end='') # 打印1行5個星星
i += 1
print('\n', end='') # 為當前行結束添加一個換行符號
j += 1 #j自增操作

舉例5.打印8行5列隔行變色的星星
j = 1 # 定義初始化j表示行數
while j <= 8: #定義循環8次,生成打印1行10列的星星
i = 0 # 定義初始化i表示列數
while i < 5:
if j % 2 == 0: # 判斷是奇數行還是偶數行,偶數打印
print('★', end='')
else:
print('☆', end='') # 判斷是奇數行還是偶數行,奇數打印
i += 1
print('\n', end='') # 為當前行結束添加一個換行符號
j += 1 #j自增操作

舉例6.打印8行5列隔列變色的星星
j = 1 # 定義初始化j表示行數
while j <= 8: #定義循環8次,生成打印1行10列的星星
i = 1 # 定義初始化i表示列數
while i <= 5:
if i % 2 == 0: # 判斷是奇數行還是偶數行,偶數打印
print('★', end='')
else:
print('☆', end='') # 判斷是奇數行還是偶數行,奇數打印
i += 1
print('\n', end='') # 為當前行結束添加一個換行符號
j += 1 #j自增操作

舉例7 .打印三角形
i = 1
while i <= 5:
j = 1
while j <= i:
print('★', end='')
j += 1
print('\n', end='')
i += 1
舉例8.打印九九乘法表
i = 1
while i <= 9:
j = 1
while j <= i:
result = j * i
print(i,'×',j,'=',result,end='\t') #print('%2d*%2d = %2d'%(j,i,result),' ',end = '')
j += 1
print()
i += 1

舉例10. 石頭剪刀布
#1 提示並獲取用戶的輸入
player = int(input("請輸入 0剪刀 1石頭 2布:"))
#2 設定電腦的輸入,默認為1 石頭
computer = 1
#3 判斷用戶的輸入,然后顯示對應的結果
if(player==0 and computer==2) or (player==1 and computer==0) or (player==2 and computer==1):
print("贏了,可以去買奶粉了")
elif(player==computer):
print("平局了,洗洗手決戰到天亮")
else:
print("輸了,回家跪搓衣板")


import random
#1 提示並獲取用戶的輸入
player = int(input("請輸入 0剪刀 1石頭 2布:"))
#2 設定電腦的輸入,導入函數random,采用randin(0,2)表示隨機生成數字0 ~ 2
computer = random.randint(0,2)
print("電腦隨機出數",computer)
#3 判斷用戶的輸入,然后顯示對應的結果
if(player==0 and computer==2) or (player==1 and computer==0) or (player==2 and computer==1):
print("贏了,可以去買奶粉了")
elif(player==computer):
print("平局了,洗洗手決戰到天亮")


2. for循環
for循環是在序列窮盡時停止,while循環是在條件不成立時停止。
Python for循環可以遍歷任何序列的項目,如一個列表或者一個字符串。
for循環的一般格式如下:
for <variable> in <sequence>:
<statements>
else:
<statements>
舉例1:
languages =["C","C++","Perl","Python"] for x in languages: print(x)

舉例2:
# 打印 1—100之間的偶數
# 首先創建一個1—100的集合,利用range函數,生成的半開半閉的區間,所以最后得+1。
num = range(1, 101)
for n in num:
if n % 2 == 0:
print(n,)
else:
print("以上數字為1-100之內的偶數")

舉例3:
d = {'x':1,'y':32,'z':10} # 定義字典d,里面有3個元素
for key in d: #遍歷字典
print(key)

..............
