讀程序祠挫,總結(jié)程序的功能:
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的范圍內(nèi)溢谤,求出當(dāng)num能被3整除或者被7整除同時(shí)不能被21整除捂寿,此時(shí)summation的次數(shù)是多少龙优。
編程實(shí)現(xiàn)(for和while各寫?一遍):
1.求1到100之間所有數(shù)的和抬伺、平均值
sum = 0
number = 1
for x in range(1,101):
sum +=number
number +=1
print(sum)
avg = sum/100
print(avg)
sum = 0
number = 1
while number<=100:
sum += number
number +=1
print(sum)
avg = sum/100
print(avg)
結(jié)果
5050
50.5
5050
50.5
2.計(jì)算1-100之間能3整除的數(shù)的和
sum = 0
for x in range(1,101):
if x%3 == 0:
sum +=x
print(sum)
sum = 0
x = 3
while 1<=x<=100:
sum +=x
x +=3
print(sum)
結(jié)果
1683
1683
3.計(jì)算1-100之間不不能被7整除的數(shù)的和
sum = 0
for i in range(1,101):
if i%7!=0:
sum +=i
i += 1
print(sum)
x = 1
sum = 0
while x<=100:
if x%7!=0:
sum +=x
x+=1
print(sum)
結(jié)果
4315
4315
1.有一對(duì)兔子,從出生后第3個(gè)月起读慎,每個(gè)月都生一對(duì)兔子漱贱,小兔子長(zhǎng)到第三個(gè)月后每個(gè)月又生一對(duì)兔子,假如兔子都不死夭委,問第n個(gè)月的兔子總共有多少幅狮?
n = 5
pre_1 = 1
pre_2 = 1
#x代碼的是當(dāng)前是第幾個(gè)數(shù)
for x in range(1,n+1):
if x == 1 or x ==2:
print(1)
continue
current = pre_1+pre_2
print(current)
pre_1,pre_2 = pre_2,current
print('第%d個(gè)數(shù)是%d'%(n,current))
結(jié)果
3
5
第5個(gè)數(shù)是5
- 判斷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ù)
for number in range(101,201):
count = 0
for x in range(2,number):
if number%x == 0:
count += 1
# print('%d不是素?cái)?shù)'%,number)
break
if count == 0:
print('%d是素?cái)?shù)'%number)
199是素?cái)?shù)
- 打印出所有的水仙花數(shù),所謂水仙花數(shù)是指一個(gè)三位數(shù)逐抑,其各位數(shù)字立方和等于該數(shù)本身。例如:153是一個(gè)水仙花數(shù),因?yàn)?53 = 1^3 + 5^3 + 3^3
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)
結(jié)果
153是水仙花數(shù)
370是水仙花數(shù)
371是水仙花數(shù)
407是水仙花數(shù)
- 有一分?jǐn)?shù)序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個(gè)數(shù)列的第20個(gè)分?jǐn)?shù)
1 2 1
2 3 2
3 5 3
4 8 5
分子:上一個(gè)分?jǐn)?shù)的分子加分母 分母: 上一個(gè)分?jǐn)?shù)的分子
fz = 2 fm = 1
fz+fm / fz
fen_zi = 2
fen_mu = 1
for x in range(1,20):
if x ==1:
fen_zi,fen_mu =fen_zi+fen_mu,fen_zi
print('%d/%d'%(fen_zi,fen_mu))
結(jié)果
17711/10946
- 給一個(gè)正整數(shù)屹蚊,要求:1厕氨、求它是幾位數(shù) 2.逆序打印出各位數(shù)字
n = 1653
number1 = (len(str(n)))
print('這個(gè)數(shù)是%d位數(shù)'%number1)
number2 = str(n)
print(number2[::-1])
結(jié)果
這個(gè)數(shù)是4位數(shù)
3561