基础
读程序,总结程序的功能:
numbers=1
for i in range(0,20):
numbers*=2
print(numbers)
"""
#计算2的20次方的值
numbers = 1
i = 0~19,20次
i = 0, numbers *= 2 = 2
i = 1, numbers *= 2 = 2*2
i = 2, numbers *= 2 = 2*2*2
···
i = 19, numbers *= 2 = 2**20
打印numbers的值
"""
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)
"""
summation = 0
num = 1
num = 1~100, 100次
num=1,判断while 1<=100成立, (1%3==0 or 1%7==0 ) and 1%21!=0不成立 num= num+1=1+1=2
num=2,判断while 2<=100成立, ···· 不成立 num= num+1=2+1=3
num=3,··· 成立, ···· 成立 summation=0+1=1,num=3+1=4
···
num=7,··· 成立, ···· 成立 summation=1+1=2,num=7+1=8
···
num=21,··· 成立, ···· 不成立 num=21+1
···
num=100,··· 成立, ··· · 成立 sumation=38+1=39,num=100+1=101
num=101,··· 不成立,退出循环,打印39
"""
编程实现(for和while各写一遍):
- 求1到100之间所有数的和、平均值
num = 0
for i in range(0,101):
num += i
print('sum=',num)
print('average=',num/i)
i = 0
num = 0
while i <= 99:
i += 1
num += i
print('sum=', num)
print('average=', num/i)
- 计算1-100之间能3整除的数的和
sum = 0
for i in range(1, 101):
if i%3 == 0:
sum += i
print('100以内能被3整除的数的和是', sum)
sum = 0
i = 0
while i <= 100:
i += 1
if i%3 == 0:
sum += i
print('100以内能被3整除的数的和是', sum)
- 计算1-100之间不不能被7整除的数的和
sum = 0
for i in range(1, 101):
if not i%7 == 0:
print(i)
sum += i
print('100以内不能被7整除的数的和是', sum)
sum = 0
i = 0
while i <= 99:
i += 1
if not i%7 == 0:
print(i)
sum += i
print('100以内不能被7整除的数的和是', sum)
稍微困难
- 求斐波那契数列列中第n个数的值:1,1,2,3,5,8,13,21,34....
def function(n):
num1 = 1
num2 = 1
if n <= 2:
return 1
for i in range(1, n-1):
num = num1 + num2
num2 = num1
num1 = num
return num
p = function(9)
print(p)
def fn(arg1, arg2, i, stop):
arg3 = arg1 + arg2
i += 1
if i < stop:
fn(arg2, arg3, i, stop)
else:
print(arg3)
m = int(input('请输入第几位数:'))
fn(0, 1, 1, m)
- 判断101-200之间有多少个素数,并输出所有素数。判断素数的方法:用一个数分别除2到sqrt(这个数),如果能被整除,则表明此数不不是素数,反之是素数
sum = 0
for i in range(101, 201):
for j in range(2, i):
if i%j == 0:
break
else:
sum += 1
print(i)
print('共有', sum, '个素数')
- 打印出所有的水仙花数,所谓水仙花数是指一个三位数,其各位数字立方和等于该数本身。例例如:153是
一个水仙花数,因为153 = 1^3 + 5^3 + 3^3、
for i in range(100, 1000):
single_digit = i%10
tens_digit = i%100//10
hundreds_digit = i//100
if i == hundreds_digit**3 + tens_digit**3 + single_digit**3:
print(i)
- 有一分数序列列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列列的第20个分数
分子:上一个分数的分⼦子加分母 分母: 上一个分数的分子 fz = 2 fm = 1 fz+fm / fz
from fractions import Fraction
while True:
n = int(input('请输入第几个数:'))
num1 = 1
num2 = 1
for i in range(0, n):
sum1 = num1 + num2
sum2 = sum1 - num2
num2 = num1
num1 = sum1
print(Fraction(sum1, sum2))
- 给一个正整数,要求:1、求它是几位数 2.逆序打印出各位数字
n = 12345
n_string = str(n)
print('这是一个', len(n_string),'位数' )
n_lists = list(n_string)
n_lists.reverse()
for n_list in n_lists:
print(n_list)
num = 123456789
count = 0
while True:
print(num % 10, end='')
num //= 10
count += 1
if num == 0:
break
print(count, '位数')
网友评论