python while循环求最大值_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))

4.使用for循环和while循环打印1-2+3-4+5... +99 的结果

# while 循环

num = 1

sum = 0

while num<100:

if num % 2==1: # 判断是奇数

sum+=num

else: # 判断是偶数

sum-=num

num+=1

print(sum)

输出结果:50

# for 循环:

sum = 0

for i in range (1,100):

if i % 2==1:

sum+=i

else:

sum-=i

print(sum)

输出结果:50

5.使用range()函数打印 100,99,98,...0

for i in range (100,-1,-1):

# 源码:(step:range,start:int,end:int,step:int)---> None

print(i)

你可能感兴趣的:(python,while循环求最大值)