python基礎while,for迴圈練習題
阿新 • • 發佈:2019-01-02
迴圈練習:
1.隨機輸入5個數,輸出最大值和最小值:
num = 1 # 定義隨機變數num 是輸入的個數 while num <= 5: a = int(input('請輸入第{}個數:'.format(num))) # 將輸入的數轉化為整數型 if num == 1: # 輸入第一個數時最大值最小值都是這個數 max = a min = a else: if a > max: max = a elif a < min: min = a num += 1 print('最大值max是:{},最小值min是{}:'.format(max, min)
2.用while和for迴圈列印九九乘法表:
while:
row = 1 # 行
while row<=9:
col = 1 # 列
while col<=row:
print(col,'*',row,'=',col*row,end='\t')
col+=1
print()
row+=1
for :
for row in range(1,10): for col in range(1,row+1): print(col,'*',row,'=',col*row,end='\t') print()
3.判斷字串中字母,數字,下劃線的個數。
s = 's3j_d67h_a5s624b_u'
方法一: s = 's3j_d67h_a5s624b_u' count1 = 0 # 定義字母個數 count2 = 0 # 定義數字個數 count3 = 0 # 定義下劃線個數 for i in s: if i >='a'and i<='z'or i >= 'A'and i <='Z': count1+=1 elif i >='1' and i<= '9 ': count2+=1 else: count3+=1 print('字母為{}個,數字為{}個,下劃線為{}個'.format(count1,count2,count))
方法二:
s = 's3j_d67h_a5s624b_u'
count1 = 0
count2 = 0
count3 = 0
for i in s: # 遍歷字串s
if i.isalpha(): # 判斷是否是字母組成
count1 += 1
elif i.isdigit(): # 判斷是否是數字組成
count2 += 1
else: # 其餘為下劃線
count3 += 1
print('字母為{}個,數字為{}個,下劃線為{}個'.format(count1, count2, count3))