读程序,总结程序的功能:
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整除并且不能被21整除的个数
编程实现(for和while各写⼀遍):
- 求1到100之间所有数的和、平均值
for循环:
sum1 = 0
ave = 0
for i in range(101):
sum1 += i
ave = sum1 / 100
print(sum1, ave)
while循环:
sum1 = 0
ave = 0
num = 0
while num <= 100:
sum1 += num
num += 1
ave = sum1 / 100
print(sum1, ave)
- 计算1-100之间能3整除的数的和
for循环
sum1 = 0
for i in range(101):
if i % 3 == 0:
sum1 += i
print(sum1)
while循环
sum1 = 0
num = 1
while num <= 100:
if num % 3 == 0:
sum1 += num
num += 1
print(sum1)
- 计算1-100之间不能被7整除的数的和
for循环
sum1 = 0
for i in range(101):
if not(i % 7 == 0):
sum1 += i
print(sum1)
while循环
sum1 = 0
num = 1
while num <= 100:
if not (num % 7 == 0):
sum1 += num
num += 1
print(sum1)
稍微困难
- 求斐波那契数列中第n个数的值:1,1,2,3,5,8,13,21,34....
num = int(input("请输入第n个值:"))
def num1(n):
if n <= 2:
return 1
else:
return num1(n - 1) + num1(n - 2)
num2 = num1(num)
print(num2)
- 判断101-200之间有多少个素数,并输出所有素数。判断素数的⽅法:⽤⼀个数分别除2到sqrt(这个
数),如果能被整除,则表明此数不是素数,反之是素数
num1 = 0
for i in range(101, 201):
for j in range(2, i):
if i % j == 0:
break
else:
print(i)
- 打印出所有的⽔仙花数,所谓⽔仙花数是指⼀个三位数,其各位数字⽴⽅和等于该数本身。例如:153是
⼀个⽔仙花数,因为153 = 1^3 + 5^3 + 3^3
for i in range(100, 1000):
a = i // 100
b = i % 100 // 10
c = i % 10
if a ** 3 + b ** 3 + c ** 3 == i:
print(i)
- 有⼀分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的第20个分数
分⼦:上⼀个分数的分⼦加分⺟ 分⺟: 上⼀个分数的分⼦ fz = 2 fm = 1 fz+fm / fz
b = 2
a = 1
for i in range(19):
temp = b
b += a
a = temp
print('%d/%d' % (b, a))
- 给⼀个正整数,要求:1、求它是⼏位数 2.逆序打印出各位数字
基
num1 = input('请输入一个数字:')
num2 = int(num1)
print("%d是%d位数" % (num2, len(num1)))
print(num1[::-1])