读程序,总结程序的功能:
1.
numbers = 1
for i in range(0, 20):
numbers *= 2
print(numbers)
功能:计算numbers乘以2的20次方的结果
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)
功能:统计从1到100之间有多少个整数能被3或者7整除,但是不能被3和7同时整除的数。
编程实现(for和while各写一遍):
1.求1到100之间所有数的和、平均值
# for
sum = 0
for i in range(1,101):
sum += i
print("1到100之间所有数的和为:%d,平均值为:%f" % (sum,sum/100))
# while
sum = 0
count = 1
while count <=100:
sum += count
count += 1
print("1到100之间所有数的和为:%d,平均值为:%f" % (sum,sum/100))
2.计算1-100之间能被3整除的数的和
# for
sum = 0
for i in range(1,101):
if i % 3 == 0:
sum += i
print("1到100之间能被3整除的数的和为:",sum)
# while
sum = 0
count = 1
while count<=100:
if i % 3 == 0:
sum += i
count +=1
print("1到100之间能被3整除的数的和为:",sum)
3.计算1-100之间不能被7整除的数的和
# for
sum = 0
for i in range(1,101):
if i % 7 != 0:
sum += i
print("1到100之间不能被7整除的数的和为:",sum)
# while
sum = 0
count = 1
while count <= 100:
if i % 7 != 0:
sum += i
count += 1
print("1到100之间不能被7整除的数的和为:",sum)
4.求斐波那契数列列中第n个数的值:1,1,2,3,5,8,13,21,34....
# for
n = input("请输入n的值:")
a,b = 0,1
for i in range(n):
a,b = b,a+b
print(a)
# while
n = input("请输入n的值:")
a,b = 0,1
count = 1
while count <= n:
a,b = b,a+b
print(a)
5.判断101-200之间有多少个素数,并输出所有素数。判断素数的方法:⽤⼀个数分别除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数
# for
number = 0
for i in range(101,201):
for j in range(2,int(i ** (1/2)) + 1):
if i % j ==0:
break
else:
print("%d是素数." % i)
number += 1
print("素数有:%d个" % number)
# while
number = 0
count = 101
while count <= 200:
j = 2
while j<= int(i ** (1/2)):
if i % j ==0:
break
else:
print("%d是素数." % i)
number += 1
print("素数有:%d个" % number)
6.打印出所有的⽔仙花数,所谓水仙花数是指一个三位数,其各位数字立⽅和等于该数本身。例如:153是一个⽔仙花数,因为153 = 1^3 + 5^3 + 3^3
# for
for i in range(100, 999):
h = i // 100 # 百位
t = i // 10 % 10 # 十位
a = i % 10 # 个位
if h**3+t**3+a**3 ==i:
print("%d是水仙花数" % i)
# while
count = 100
while count<=999:
h = i // 100 # 百位
t = i // 10 % 10 # 十位
a = i % 10 # 个位
if h**3+t**3+a**3 ==i:
print("%d是水仙花数" % i)
count += 1
7.有⼀分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的第20个分数 分⼦:上一个分数的分⼦加分母 分母: 上⼀个分数的分子 fz = 2 fm = 1 fz+fm / fz
# for
fm = 1
fz = 2
for i in range(1,20):
t = fz
fz = fz + fm
fm = t
print("第20个分数为:%d/%d" % (fz,fm))
# while
fm = 1
fz = 2
count = 1
while count <20:
t = fz
fz = fz + fm
fm = t
count += 1
print("第20个分数为:%d/%d" % (fz,fm))
8.给一个正整数,要求:1、求它是几位数 2.逆序打印出各位数字
n = int(input("请输入一个正整数:"))
strn = str(n)
print("它是%d位数." % len(strn))
print("逆序:",strn[::-1])
# for
strn = input("请输入一个正整数:")
n = int(strn)
for i in range(0,len(strn)):
t = n % 10
print(t)
n = n // 10
print("该数有:%d位" % i+1)
# while
n = int(input("请输入一个正整数:"))
count = 0
while True:
t = n % 10
print(t)
n = n // 10
count += 1
if n == 0:
break
print("该数有:%d位" % count)