读程序,总结程序的功能:
numbers=1
for i in range(0,20):
numbers*=2
print(numbers)
答:1乘2的20次方
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到100之间所有数的和、平均值
- 计算1-100之间能3整除的数的和
- 计算1-100之间不能被7整除的数的和
答:1.for:
sum1 = 0
summation = 0
for num in range(1,101):
sum1 += num
summation += 1
print(sum1) #总和
print(sum1 / summation) #平均值
while:
num = 1
sum1 = 0
summation = 0
while num <= 100:
sum1 += num
summation += 1
num += 1
print(sum1) #总和
print(sum1/summation) #平均值
2.for:
sum1 = 0
for num in range(101):
if num % 3 == 0:
sum1 += num
print(sum1)
while:
sum1 = 0
num = 1
while num <= 100:
if num % 3 == 0:
sum1 += num
num += 1
print(sum1)
3.for:
sum1 = 0
for num in range(101):
if num % 7 != 0:
sum1 += num
print(sum1)
while:
sum1 = 0
num = 0
while num <= 100:
if num % 7 != 0:
sum1 += num
num += 1
print(sum1)
- 求斐波那契数列中第n个数的值:1,1,2,3,5,8,13,21,34....
答:
sum3 = 1
sum1 = 1
sum2 = 0
n = int(input('n的值为:'))
num = 2
while num <= n:
sum3 = sum1 + sum2
sum2 = sum1
sum1 = sum3
num += 1
print(sum3)
- 判断101-200之间有多少个素数,并输出所有素数。判断素数的⽅法:⽤⼀个数分别除2到sqrt(这个
数),如果能被整除,则表明此数不是素数,反之是素数
答:
方法1
for num in range(101,201):
for x in range(2,num):
if num % x == 0:
print(num,'不是素数')
break
else:
print(num,'是素数')
方法2:
for num in range(101,201,2):
count = 0 #cunchu 2~ num-1之间有几个能够被num整除的
for x in range(2,num):
count += 1
break
if count == 0:
print(num,'是素数')
- 打印出所有的⽔仙花数,所谓⽔仙花数是指⼀个三位数,其各位数字⽴⽅和等于该数本身。例如:153是
⼀个⽔仙花数,因为153 = 1^3 + 5^3 + 3^3
答:
for num in range(100, 1000):
a = num % 10
b = num // 10 % 10
c = num // 100
if num== a ** 3 + b ** 3 + c ** 3:
print('水仙花数为:',num)
- 有⼀分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的第20个分数
分⼦:上⼀个分数的分⼦加分⺟ 分⺟: 上⼀个分数的分⼦ fz = 2 fm = 1 fz+fm / fz
答:
fz = 1
fm = 1
for n in range(int(input('请输入n的数值'))):
f = (fz + fm)/fz
ft = fz
fz += fm
fm = ft
print('第n个分数为:',f)
- 给⼀个正整数,要求:1、求它是⼏位数 2.逆序打印出各位数字
答:
num = int(input('请输入一个正整数:'))
n = 1
while (10 ** n) / num <= 1:
n += 1
print(n) #打印个数
str1 = str(num)
m = 1
new_str1 = ''
while m <= n:
str2 = str1[-m]
new_str1 += str2
m += 1
print(new_str1) #打印逆序数字
基础
稍微困难