读程序,总结程序的功能:
1.
numbers=1
for i in range(0,20):
numbers*=2
print(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但是不能整除21的数
编程实现(for和while各写⼀遍):
1. 求1到100之间所有数的和、平均值
sum1 = 0
sum2 = 0
for num in range(1,101):
sum1=sum1+num
sum2 = sum1 / 100
print('和是:%d,平均值是:%.2f'%(sum1,sum2))
sum1 = 0
num = 1
ava = 0
while num <= 100:
sum1 = sum1 + num
ava = sum1 / 100
num+=1
print('和是:%d,平均值是:%.2f'%(sum1,ava))
和是:5050,平均值是:50.50
和是:5050,平均值是:50.50
2. 计算1-100之间能3整除的数的和
sum1 =0
for num in range(1,101):
if num % 3 == 0:
sum1=sum1+num
print('被3整除的数和是:%d'%(sum1))
sum1 = 0
num = 1
while num <= 100:
num+=1
if num % 3 != 0:
continue
else:
sum1 += num
print(sum1)
被3整除的数和是:1683
1683
3. 计算1-100之间不能被7整除的数的和
sum1 = 0
for num in range(1,101):
if num % 7 != 0:
sum1 += num
print('不能被7整除的数和是:%d'%(sum1))
sum1 = 0
num =0
while True:
num += 1
if 1<= num <= 100:
if num % 7 != 0:
sum1 += num
else:
break
print(sum1)
不能被7整除的数和是:4315
4315
稍微困难
1. 求斐波那契数列中第n个数的值:1,1,2,3,5,8,13,21,34....
b=1
list=[1,1]
n=int(input("请输入求第几个数:"))
if n <= 2:
print(list[n-1])
else:
for b in range(n-2):
if n >2:
list[b+1] = list[b]+list[b-1]
list.append(list[b+1])
print('结果是:',list[b+1])
请输入求第几个数:8
结果是: 21
2. 判断101-200之间有多少个素数,并输出所有素数。判断素数的⽅法:⽤⼀个数分别除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数
print('素数有:')
for a in range(101,201):
for b in range(2,a):
if a % b ==0:
break
else:
print(end='%d,'%a)
素数有:
101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,
3. 打印出所有的⽔仙花数,所谓⽔仙花数是指⼀个三位数,其各位数字⽴⽅和等于该数本身。例如:153是⼀个⽔仙花数,因153 = 1^3 + 5^3 + 3^3
print('水仙花数有:')
for num in range(100,1000):
a = num // 100
b = num // 10 % 10
c = num % 10
if num == a**3 + b**3 + c**3:
print(end='%d\t'%num)
水仙花数有:
153 370 371 407
4. 有⼀分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的第20个分数分⼦:上⼀个分数的分⼦加分⺟ 分⺟: 上⼀个分数的分⼦ fz = 2 fm = 1 fz+fm / fz
a = 1
b = 2
flag = 1
t=0
while flag < 21:
flag+=1
t = a
a = b
b = t + a
print('%d'%(t + a), '/', '%d'%(a))
28657 / 17711
5. 给⼀个正整数,要求:1、求它是⼏位数 2.逆序打印出各位数字
import random
num = random.randint(1,500000)
num2 = str(num)
print('%d这是一个%d位数'%(num,len(num2)))
print(num2[-1::-1])
460200这是一个6位数
002064