基础
读程序,总结程序的功能:
numbers=1
for i in range(0,20):
numbers*=2
print(numbers)
答:求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之间所有数的和、平均值
for:
sum1 = 0
for x in range(1, 101):
sum1 += x
sum2 = sum1 / 100
print(sum1, sum2)
while:
sum1 = 0
num = 0
while num <= 100:
sum1 += num
num += 1
sum2 = sum1 / 100
print(sum1, sum2)
- 计算1-100之间能3整除的数的和
for:
sum1 = 0
for x in range(1, 101):
if x % 3 == 0:
sum1 += x
print(sum1)
while:
sum1 = 0
num = 0
while num <= 100:
if num % 3 == 0:
sum1 += num
num += 1
print(sum1)
- 计算1-100之间不不能被7整除的数的和
for:
sum1 = 0
for x in range(1, 101):
if x % 7 != 0:
sum1 += x
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....
n = int(input('请输入一个正整数'))
a = 1
b = 1
c = 1
for i in range(3,n+1):
c = a+b
a = b
b = c
print('第%d个数是%d' % (n,c))
- 判断101-200之间有多少个素数,并输出所有素数。判断素数的方法:用一个数分别除2到sqrt(这个
数),如果能被整除,则表明此数不不是素数,反之是素数
count = 0
for num in range(101,201):
for x in range(2, num):
if num % x == 0:
# print(num, '不是素数')
break
else:
print(num, '是素数')
count += 1
print('101到200的素数的个数', count)
- 打印出所有的水仙花数,所谓的水仙花数是指一个三位数,其各位数字立方和等于该数本身。例例如:153是
一个水仙花数,因为153 = 1^3 + 5^3 + 3^3
for n in range(100,1000):
a = n // 100
b = n % 100 //10
c = n % 10
if n == a**3+b**3+c**3:
print('水仙花数:', n)
- 有一分数序列列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列列的第20个分数
分子:上一个分数的分子加分母 分母: 上一个分数的分子 fz = 2 fm = 1 fz+fm / fz
fen_zi = 1
fen_mu = 1
for _ in range(20):
fen_zi, fen_mu = fen_zi + fen_mu, fen_zi
print(fen_zi, '/', fen_mu)
- 给一个正整数,要求:1、求它是几位数 2.逆序打印出各位数字
num = int(input('输入一个整数:'))
count = 0
while True:
count += 1
print(num % 10, end='')
num //= 10
if num == 0:
break
print('\n', count)