练习_1.1
练习题目:
1 打印九九乘法表
2 打印下方菱形
3 打印100以内的斐波那契数列
4 求斐波那契数列第101项
5 求10万内的所有质数
*
***
*****
*******
*****
***
*
6 打印下方的闪电
*
**
***
*******
***
**
*
1 打印九九乘法表
# 1 for i in range(1,10): for j in range(1,i+1): print(j,'x',i,'=',i*j,end='\t') print() # 2 for i in range(1,10): for j in range(1,i+1): product=i*j if product<10: end=' ' else: end=' ' print(str(j)+'*'+str(i)+'='+str(product),end=end) print() # 3 for i in range(1,10): for j in range(1,i+1): print('{0}*{1}={2:<2}'.format(j,i,j*i),end=' ') print() # 4 i=1 while i<10: j=1 while j<=i: print('{0}*{1}={2:<2}'.format(j,i,i*j),end=' ') j+=1 print() i+=1
1.1 打印九九乘法表(反向)
# 1 for i in range(1,10): print(' '*7*(i-1),end='') for j in range(i,10): product=i*j if product<10: end=' ' else: end=' ' print(str(j)+'*'+str(i)+'='+str(i*j),end=end) print() # 2 i=1 j=1 while i<10: j=i print(' '*7*(i-1),end='') while i<=j<10: print('{0}*{1}={2:<2}'.format(j,i,i*j),end=' ') j+=1 print() i+=1
2 打印下方菱形
# 1 for i in range(-3,4): if i<0: i=-i else: i=i print(' '*i+'*'*(7-2*i)) # 2 for i in range(-3,4): print(' '*(-i)+'*'*(7+2*i)) if i < 0 else print(' '*i+'*'*(7-2*i))
3 打印100以内的斐波那契数列
# 1 pre=0 suf=1 for _ in range(100): sum=pre+suf pre=suf suf=sum if sum>100: break else: print(sum) # 2 i = 1 j = 1 while i < 100: print(i) i,j=j,i+j # 3 a = 0 b = 1 print(a,b,end=' ') while True: a = a + b b = b + a if a < 100: print(a, end=' ') else: break if b<100: print(b,end=' ') else: break
4 求斐波那契数列第101项
# 1 count=2 sum_old=0 sum_new=1 sum=0 member=101 if member==1: print(1) else: while count<member+1: sum=sum_old+sum_new sum_old=sum_new sum_new=sum count+=1 else: print(sum) # 2 pre=0 suf=1 for _ in range(100): sum=pre+suf pre=suf suf=sum else: print(sum) # 3 i=1 j=1 for _ in range(100): i,j=j,i+j print(i)
5 求10万内的所有质数
若自然数N不能被不大于根号N的任何素数整除,则N是一个素数 num=1000 if num>2: print(2) if num>3: print(3) if num>5: print(5) if num>7: print(7) for num in range(11,num+1,2): for i in range(3,int(num**0.5)+1,2): # int(num**0.5) 必须大于3,所以num最小值大于9,9和10都不是质数,直接从11开始 if num%i==0: break else: print(num) # 2 num=10000 if num>=2: print(2) for num in range(3,num,2): for i in range(3,int(num**0.5)+1,2): if num%i==0: break else: print(num)
6 打印下方的闪电for i in range(-3,4): if i<0: print(' '*(-i)+'*'*(4+i)) elif i>0: print(' '*3+'*'*(4-i)) else: print('*'*7)