python基础while,for循环练习题

循环练习:

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))

猜你喜欢

转载自blog.csdn.net/weixin_43567965/article/details/85602585