讀程序喂链,總結(jié)程序的功能:
numbers=1
for i in range(0,20):
numbers*=2
print(numbers)
答:1乘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內(nèi)能被3或者7整除同時(shí)不能被3和7同時(shí)整除的數(shù)的個(gè)數(shù)。
編程實(shí)現(xiàn)(for和while各寫?遍):
- 求1到100之間所有數(shù)的和妥泉、平均值
- 計(jì)算1-100之間能3整除的數(shù)的和
- 計(jì)算1-100之間不能被7整除的數(shù)的和
答:1.for:
sum1 = 0
summation = 0
for num in range(1,101):
sum1 += num
summation += 1
print(sum1) #總和
print(sum1 / summation) #平均值
while:
num = 1
sum1 = 0
summation = 0
while num <= 100:
sum1 += num
summation += 1
num += 1
print(sum1) #總和
print(sum1/summation) #平均值
2.for:
sum1 = 0
for num in range(101):
if num % 3 == 0:
sum1 += num
print(sum1)
while:
sum1 = 0
num = 1
while num <= 100:
if num % 3 == 0:
sum1 += num
num += 1
print(sum1)
3.for:
sum1 = 0
for num in range(101):
if num % 7 != 0:
sum1 += num
print(sum1)
while:
sum1 = 0
num = 0
while num <= 100:
if num % 7 != 0:
sum1 += num
num += 1
print(sum1)
- 求斐波那契數(shù)列中第n個(gè)數(shù)的值:1椭微,1,2盲链,3蝇率,5,8刽沾,13本慕,21,34....
答:
sum3 = 1
sum1 = 1
sum2 = 0
n = int(input('n的值為:'))
num = 2
while num <= n:
sum3 = sum1 + sum2
sum2 = sum1
sum1 = sum3
num += 1
print(sum3)
- 判斷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ù)
答:
方法1
for num in range(101,201):
for x in range(2,num):
if num % x == 0:
print(num,'不是素?cái)?shù)')
break
else:
print(num,'是素?cái)?shù)')
方法2:
for num in range(101,201,2):
count = 0 #cunchu 2~ num-1之間有幾個(gè)能夠被num整除的
for x in range(2,num):
count += 1
break
if count == 0:
print(num,'是素?cái)?shù)')
- 打印出所有的?仙花數(shù),所謂?仙花數(shù)是指?個(gè)三位數(shù),其各位數(shù)字??和等于該數(shù)本身纵揍。例如:153是
?個(gè)?仙花數(shù),因?yàn)?53 = 1^3 + 5^3 + 3^3
答:
for num in range(100, 1000):
a = num % 10
b = num // 10 % 10
c = num // 100
if num== a ** 3 + b ** 3 + c ** 3:
print('水仙花數(shù)為:',num)
- 有?分?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 = 1
fm = 1
for n in range(int(input('請(qǐng)輸入n的數(shù)值'))):
f = (fz + fm)/fz
ft = fz
fz += fm
fm = ft
print('第n個(gè)分?jǐn)?shù)為:',f)
- 給?個(gè)正整數(shù)顿乒,要求:1、求它是?位數(shù) 2.逆序打印出各位數(shù)字
答:
num = int(input('請(qǐng)輸入一個(gè)正整數(shù):'))
n = 1
while (10 ** n) / num <= 1:
n += 1
print(n) #打印個(gè)數(shù)
str1 = str(num)
m = 1
new_str1 = ''
while m <= n:
str2 = str1[-m]
new_str1 += str2
m += 1
print(new_str1) #打印逆序數(shù)字
基礎(chǔ)
稍微困難