day4作业

读程序,总结程序的功能:

1.

numbers=1 
for i in range(0,20): 
  numbers*=2 
print(numbers)

i = 0,number = 1 * 2 = 2
i = 1,number = 2 * 2 = 4
i = 2,number = 4 * 2 = 8
...
i = 19,number = 2 ** 20 = 1048576

2.


summation=0
num=1
while num<=100:
  if (num%3==0 or num%7==0) and num%21!=0:
    summation += 1
  num+=1
print(summation)

num = 1 <= 100,但不满足if后面的条件语句,summation += 1不执行,num = num + 1 = 2
num = 2 <= 100,但不满足if后面的条件语句,summation += 1不执行,num = num + 1 = 3
num = 3 <= 100,满足if后面条件语句,summation =summation + 1 = 1,num = num + 1 = 4
...
num = 7 <= 100,满足if后面条件语句,summation =summation + 1 = 2,num = num + 1 = 8
...
num = 21 <= 100,但不满足if后面的条件语句,summation += 1不执行,num = num + 1 = 22

最后打印的summation为100以内能被3或7整除,但是不能同时被3或7整除的数的个数,为39个

编程实现(for和while各写⼀遍):

1. 求1到100之间所有数的和、平均值

for语句

求和

a = 0
for b in range(101):
    a += b
print(a)

求平均数

a = 0
count = 0
for b in range(1,101):
    a += b
    count += 1
print(a/count)

while语句

求和

a = 1
b = 0
while a <= 100:
    b += a
    a += 1
print(b)

求平均数

a = 1
b = 0
count = 0
while a <= 100:
    b += a
    a += 1
    count += 1
print(b/count)

2. 计算1-100之间能3整除的数的和

for语句

a = 0
for b in range(1,101):
    if b % 3 == 0:
        a += b
print(a)

while语句

a = 0
b = 1
while b <= 100:
    if b % 3 == 0:
        a += b
    b += 1
print(a)

3. 计算1-100之间不能被7整除的数的和

for语句

a = 0
for b in range(1,101):
    if b % 7 != 0:
        a += b
    b += 1
print(a)

while语句

a = 0
b = 1
while b <= 100:
    if b % 7 != 0:
        a += b
    b += 1
print(a)

1. 求斐波那契数列中第n个数的值:1,1,2,3,5,8,13,21,34....

current = 1   # 当前数
pre_1 = 1     # 前一个数
pre_2 = 0     # 前两个数
n = 7       
for x in range(n-1):
    current = pre_1 + pre_2
    pre_2 = pre_1
    pre_1 = current

print(current)

print('========')

2. 判断101-200之间有多少个素数,并输出所有素数。判断素数的⽅法:⽤⼀个数分别除2到sqrt(这个

数),如果能被整除,则表明此数不是素数,反之是素数

count = 0
for a in range(101,201):
    for b in range(2,a):
        if a % b == 0:
            break
    else:
        print(a)
        count += 1

print(count)
        

3. 打印出所有的⽔仙花数,所谓⽔仙花数是指⼀个三位数,其各位数字⽴⽅和等于该数本身。例如:153是

⼀个⽔仙花数,因为153 = 1^3 + 5^3 + 3^3

fenzi = 2
fenmu = 1
n = 5
for x in range(n-1):
    fenzi,fenmu = fenzi+fenmu,fenzi

    # temp = fenzi
    # fenzi = fenzi + fenmu
    # fenmu = temp

print(fenzi,'/',fenmu)

4. 有⼀分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的第20个分数

分⼦:上⼀个分数的分⼦加分⺟ 分⺟: 上⼀个分数的分⼦ fz = 2 fm = 1 fz+fm / fz




# 5. 给⼀个正整数,要求:1、求它是⼏位数 2.逆序打印出各位数字

你可能感兴趣的:(day4作业)