1.讀程序,總結(jié)程序的功能:
(1).
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)
答:求100以內(nèi)能被3麸祷,7整除不能被21整除的數(shù)的個數(shù)撮抓。
2.編程實現(xiàn)(for和while各寫?遍):
(1). 求1到100之間所有數(shù)的和、平均值
sum1 = 0
for num in range(1, 101):
sum1 += num
ave = sum1 / 100
print(sum1, ave)
sum1 = 0
num = 1
while num in range(1, 101):
sum1 += num
num += 1
ave = sum1 / 100
print(sum1, ave)
(2). 計算1-100之間能3整除的數(shù)的和
sum1 = 0
for num in range(1, 101):
if num % 3 == 0:
sum1 += num
print(sum1)
sum1 = 0
num = 1
while num in range(1, 101):
if num % 3 == 0:
sum1 += num
num += 1
print(sum1)
(3). 計算1-100之間不能被7整除的數(shù)的和
sum1 = 0
for num in range(1, 101):
if num % 7 != 0:
sum1 += num
print(sum1)
sum1 = 0
num = 1
while num in range(1, 101):
if num % 7 != 0:
sum1 += num
num += 1
print(sum1)
- 求斐波那契數(shù)列中第n個數(shù)的值:1摇锋,1丹拯,2,3荸恕,5乖酬,8,13融求,21咬像,34....
a = 1
b = 1
sum1 = 0
n = int(input('請輸入一個數(shù)'))
for sum1 in range(0, n-2):
x = a +b
a = b
b = x
sum1 += 1
print(b)
- 判斷101-200之間有多少個素數(shù),并輸出所有素數(shù)。判斷素數(shù)的?法:??個數(shù)分別除2到sqrt(這個
數(shù))县昂,如果能被整除肮柜,則表明此數(shù)不是素數(shù),反之是素數(shù)
import math
for i in range(101, 201):
# for j in range(2, i):
for j in range(2, int(math.sqrt(i))):
if i % j == 0:
print(i, '不是素數(shù)')
break
else:
print(i, '是素數(shù)')
# 方法2
import math
for i in range(101, 201):
flag = True #假設(shè)當(dāng)前數(shù)是素數(shù)
for j in range(2, int(math.sqrt(i))):
if i % j == 0:
flag = False # 如果在2-i之間遇到一個能整除的假設(shè)不成立
break
if flag:
print(i, '是素數(shù)')
- 打印出所有的?仙花數(shù),所謂?仙花數(shù)是指?個三位數(shù)倒彰,其各位數(shù)字??和等于該數(shù)本身审洞。例如:153是
?個?仙花數(shù),因為153 = 1^3 + 5^3 + 3^3
for n in range(100,1000):
if n == (n // 100) ** 3 + (n % 100 // 10)**3 \
+ (n % 100 % 10) ** 3:
print(n)
- 有?分數(shù)序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個數(shù)列的第20個分數(shù)
分?:上?個分數(shù)的分?加分? 分?: 上?個分數(shù)的分? fz = 2 fm = 1 fz+fm / fz
fz = 1
fm = 1
for n in range(20):
fz, fm = fz + fm, fz
# sum1 = fz + fm
# fm = fz
# fz = sum1
print(fz, '/', fm)
- 給?個正整數(shù),要求:1待讳、求它是?位數(shù) 2.逆序打印出各位數(shù)字
m = int(input("請輸入:"))
string = ""
count = 0
while True:
string += str(m % 10) + " "
m = int(m / 10)
count += 1
if m == 0:
break
print("m是" + str(count) + "位數(shù)")
print(string)