读程序,总结程序的功能:
numbers = 1
for i in range(0, 20):
numbers *= 2
print(numbers)
初始化为1,循环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之间所有数的和、平均值
for循环求和:
sum1 = 0
for num in range(1, 101):
sum1 += num
print(sum1)
while循环求和:
sum1 = 0
num = 1
while num < 101:
sum1 += num
num += 1
print(sum1)
for循环求平均值:
sum1 = 0
for num in range(1, 101):
sum1 += num
ave = sum1 / 100
print(ave)
while循环求平均值:
sum1 = 0
num = 1
while num < 101:
sum1 += num
ave = sum1 / 100
num += 1
print(ave)
2.计算1-100之间能3整除的数的和
num = 1
sum1 = 0
while num < 101:
if num % 3 == 0:
sum1 += num
num += 1
print(sum1)
3.计算1-100之间不不能被7整除的数的和
- 求斐波那契数列列中第n个数的值:1,1,2,3,5,8,13,21,34....
n = int(input("请输入第n个数的位置:"))
sum1 = 0
num = 1
for _ in range(n):
sum2 = sum1 + num
num = sum1
sum1 = sum2
print("第n个数的值为:", sum2)
nums = int(input("number:"))
num1 = 0
num2 = 1
for x in range(nums):
sum2 = num1 + num2
num2, num1 = num1, sum2
# num2 = num1
# num1 = sum2
print("第n个数的值为:", sum2)
- 判断101-200之间有多少个素数,并输出所有素数。判断素数的方法:用一个数分别除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数
for i in range(101, 200):
for j in range(2, i):
if i % j == 0:
break
else:
print(i)
- 打印出所有的水仙花数,所谓水仙花数是指一个三位数,其各位数字立方和等于该数本身。例如:153是⼀个水仙花数,因为153 = 1^3 + 5^3 + 3^3
for n in range(100, 1000):
n1 = n // 100
n2 = n % 100 // 10
n3 = n % 10
if (n1 ** 3) + (n2 ** 3) + (n3 ** 3) == n:
print(n)
- 有⼀分数序列列:2/1,3/2,5/3,8/5,13/8,21/13. 求出这个数列的第20个分数.分子:上一个分数的分子加分⺟, 分母: 上⼀个分数的分子 fz = 2 fm = 1 fz+fm / fz
count = 1
fz = 2
fm = 1
while count < 20:
f = fz
fz = fz + fm
fm = f
count += 1
print(fz, '/', fm)
- 给一个正整数,要求:1、求它是几位数 2.逆序打印出各位数字
m = eval(input("请输入数字:"))
n = int(m)
i = list(str(m))
if m >= 0 and m == n:
print('它是%d位数' % len(i))
i.reverse()
a = "".join(i)
print('逆序打印为:', a)
else:
print("不是一个正整数!")