基礎(chǔ)
讀程序仙辟,總結(jié)程序的功能:
1
numbers=1
for i in range(0,20):
numbers*=2
print(numbers)
range函數(shù)形成0~19的整數(shù)序列忘伞,for in循環(huán)乘2
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)
數(shù)字1~100能整除3與不能整除21或能整除7與不能整除21的次數(shù)
次數(shù):39個(gè)
編程實(shí)現(xiàn)(for和while各寫一遍):
- 求1到100之間所有數(shù)的和射众、平均值
求和
sum=0;
for num in range(0,101):
sum = sum + num;
print(sum);
print('=============')
sum=0
num=0
while(num<=100):
sum = sum + num;
num = num+1
print(sum);
求平均值
num = 0
for num1 in range(0,100):
num = (num + num1)%100
print(num)
print('=============')
num=0
sum=0
while sum<=100:
num = (num + sum)/100
sum+=1;
print(num)
- 計(jì)算1-100之間能3整除的數(shù)的和
sum=0
for x in range(0,100):
if x % 3==0:
sum+=x
print(sum)
print('=============')
num=0
sum=0
while(num<=100):
if num % 3 ==0:
sum = sum + num;
num+=1;
print(sum)
- 計(jì)算1-100之間不不能被7整除的數(shù)的和
for x in range(0,100):
if x % 7!=0:
sum+=x
print(sum)
num=0
sum=0
while (num<=100):
if num % 7!=0:
sum=sum+num
num+=1
print(sum)
稍微困難
- 求斐波那契數(shù)列列中第n個(gè)數(shù)的值:1诀紊,1垦垂,2怒炸,3带饱,5,8阅羹,13勺疼,21,34....
n = 8 # 第n-1捏鱼,第n-2
n_1 = 1
n_2 = 1
if n <= 2:
print(1)
for x in range(3,n+1):
# 算出最后一位
current = n_1 + n_2
# 往后移
n_2 = n_1
n_1 = current
print(current)
- 判斷101-200之間有多少個(gè)素?cái)?shù)执庐,并輸出所有素?cái)?shù)。
判斷素?cái)?shù)的方法:?一個(gè)數(shù)分別除2到sqrt(這個(gè)數(shù))导梆,如果能被整除轨淌,則表明此數(shù)不是素?cái)?shù)迂烁,反之是素?cái)?shù)
什么是素?cái)?shù)/質(zhì)數(shù):除了1和它本身以外,不能被其他數(shù)整除
# x取 101~200
for x in range(101,201):
count = 0
# y取 2 ~ x-1
for y in range(2,x):
if x % y ==0:
count += 1
print('%d不是素?cái)?shù)' % (x))
break
if count == 0:
print('%d是素?cái)?shù)' % (x))
for x in range(101,201):
for y in range(2,x):
if x % y == 0:
break
else:
print('%d是素?cái)?shù)' % (x))
- 打印出所有的?仙花數(shù),
所謂水仙花數(shù)是指一個(gè)三位數(shù)递鹉,其各位數(shù)字?方和等于該數(shù)本身盟步。例如:153是?個(gè)?水仙花數(shù),因?yàn)?53 = 1^3 + 5^3 + 3^3
# 取出所有的三位數(shù)
for x in range(100,1000):
ge_wei = x%10
shi_wei = x//10&10
bai_wei = x//100
if x == ge_wei**3 + shi_wei**3 + bai_wei**3:
print('%d是水仙花數(shù)' % x)
- 有?分?jǐn)?shù)序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個(gè)數(shù)列的第20個(gè)分?jǐn)?shù)
分?: 上一個(gè)分?jǐn)?shù)的分?加分母
分?: 上一個(gè)分?jǐn)?shù)的分子 fz = 2 fm = 1 fz+fm / fz
fz = 2
fm = 1
for _ in range(20):
print('%d/%d'%(fz,fm))
fz,fm = fz+fm,fz # fz,fm=3,2 , fz=3,fm=2
# t = fz
# fz = fz+fm # 2+1=3
# fm = t # 3
- 給?個(gè)正整數(shù),要求:1躏结、求它是?位數(shù) 2.逆序打印出各位數(shù)字
num = 16723 #1672 167 16 1 0
count = 0
while num !=0:
count += 1
num //=10
print(count)