基础
读程序,总结程序的功能:
- 输出number乘以2的20次方的值。
numbers=1
for i in range(0,20):
numbers*=2
print(numbers)
- 输出100以内可被3整除或者能被7整出但不能同时被3和7整出的数的个数。
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)
编程实现(for和while各写⼀遍):
- 求1到100之间所有数的和、平均值
for:
num = 1
sum = 0
for num in range(1,101):
sum += num
num += 1
print(sum, (sum / 100))
while:
num = 1
sum = 0
while num < 101:
sum += num
num += 1
print(sum, (sum / 100))
- 计算1-100之间能3整除的数的和
for
num = 0 sum = 0 for i in range(1,101):
num += 1
if num % 3 == 0:
sum += num
print(sum)
while
num = 0 sum = 0 while True:
if num < 101:
num += 1
if num % 3 == 0:
sum += num
else:
break print(sum)
- 计算1-100之间不能被7整除的数的和
for
num = 0
sum = 0
for num in range(1, 101):
if num % 7 != 0:
sum += num
print(sum)
while
num = 0 sum = 0 while True:
if num < 100:
num += 1
if num % 7 != 0:
sum += num
else:
break
print(sum)
稍有困难
- 求斐波那契数列中第n个数的值:1,1,2,3,5,8,13,21,34....
n = int(input('请输入一个正整数:'))
a = 0
b = 1
sum = 0
if n == 1:
print(1)
else:
for x in range(2,n + 1):
sum = a + b
a = b
b = sum
print(sum)
- 判断101-200之间有多少个素数,并输出所有素数。判断素数的⽅法:
⽤⼀个数分别除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数
num = 0
for x in range(101,201):
for n in range(2,x):
if x % n == 0:
break
else:
num += 1
print(x, '是')
print(num,'个')
- 打印出所有的⽔仙花数,所谓⽔仙花数是指⼀个三位数,
其各位数字⽴⽅和等于该数本身。例如:153是 ⼀个⽔仙花数,
因为153 = 1^3 + 5^3 + 3^3
a = 0
b = 0
c = 0
for x in range(100,1000):
a = x % 10
b = x % 100 // 10
c = x // 100
if a*a*a + b*b*b + c*c*c == x:
print(x,'是')
- 有⼀分数序列:2/1,3/2,5/3,8/5,13/8,21/13...
求出这个数列的第20个分数
分⼦:上⼀个分数的分⼦加分⺟
分⺟: 上⼀个分数的分⼦
fz = 2 fm = 1 fz+fm / fz 5.
fz1 = 1
fm1 = 1
fs = 0
for x in range(1,21):
fz1 = fz1 + fm1
fm1 = fz1
fs = fz1 / fm1
print(fs)
- 给⼀个正整数,要求:1、求它是⼏位数 2.逆序打印出各位数字
num = int(input('给一个正整数:'))
m = 0
num2 = num
while True:
m += 1
print(num % 10)
num //= 10
if num == 0:
break
print(num2, '是一个', m, '位数')