1.读程序,总结程序的功能:
(1).
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)
答:求100以内能被3,7整除不能被21整除的数的个数。
2.编程实现(for和while各写⼀遍):
(1). 求1到100之间所有数的和、平均值
sum1 = 0
for num in range(1, 101):
sum1 += num
ave = sum1 / 100
print(sum1, ave)
sum1 = 0
num = 1
while num in range(1, 101):
sum1 += num
num += 1
ave = sum1 / 100
print(sum1, ave)
(2). 计算1-100之间能3整除的数的和
sum1 = 0
for num in range(1, 101):
if num % 3 == 0:
sum1 += num
print(sum1)
sum1 = 0
num = 1
while num in range(1, 101):
if num % 3 == 0:
sum1 += num
num += 1
print(sum1)
(3). 计算1-100之间不能被7整除的数的和
sum1 = 0
for num in range(1, 101):
if num % 7 != 0:
sum1 += num
print(sum1)
sum1 = 0
num = 1
while num in range(1, 101):
if num % 7 != 0:
sum1 += num
num += 1
print(sum1)
- 求斐波那契数列中第n个数的值:1,1,2,3,5,8,13,21,34....
a = 1
b = 1
sum1 = 0
n = int(input('请输入一个数'))
for sum1 in range(0, n-2):
x = a +b
a = b
b = x
sum1 += 1
print(b)
- 判断101-200之间有多少个素数,并输出所有素数。判断素数的⽅法:⽤⼀个数分别除2到sqrt(这个
数),如果能被整除,则表明此数不是素数,反之是素数
import math
for i in range(101, 201):
# for j in range(2, i):
for j in range(2, int(math.sqrt(i))):
if i % j == 0:
print(i, '不是素数')
break
else:
print(i, '是素数')
# 方法2
import math
for i in range(101, 201):
flag = True #假设当前数是素数
for j in range(2, int(math.sqrt(i))):
if i % j == 0:
flag = False # 如果在2-i之间遇到一个能整除的假设不成立
break
if flag:
print(i, '是素数')
- 打印出所有的⽔仙花数,所谓⽔仙花数是指⼀个三位数,其各位数字⽴⽅和等于该数本身。例如:153是
⼀个⽔仙花数,因为153 = 1^3 + 5^3 + 3^3
for n in range(100,1000):
if n == (n // 100) ** 3 + (n % 100 // 10)**3 \
+ (n % 100 % 10) ** 3:
print(n)
- 有⼀分数序列: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(20):
fz, fm = fz + fm, fz
# sum1 = fz + fm
# fm = fz
# fz = sum1
print(fz, '/', fm)
- 给⼀个正整数,要求:1、求它是⼏位数 2.逆序打印出各位数字
m = int(input("请输入:"))
string = ""
count = 0
while True:
string += str(m % 10) + " "
m = int(m / 10)
count += 1
if m == 0:
break
print("m是" + str(count) + "位数")
print(string)
网友评论