基础
读程序,总结程序的功能:
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) # 统计 0 ~ 100 是3或者7的倍数,但不是3和7的公倍数的数的个数.
编程实现(for和while各写⼀遍):
- 求1到100之间所有数的和、平均值
sum = 0 # for循环写
value = 0
for value in range(1, 101):
sum += value
average_value = sum / value
print('总和:%d,平均值:%.2f' % (sum, average_value))
sum = 0 # while循环写
count = 1
while count <101:
sum += count
count += 1
average_value = sum / count
print('总和:%d,平均值:%.2f' % (sum, average_value))
- 计算1-100之间能3整除的数的和
sum = 0
for count in range(1, 101):
if not count % 3:
sum += count
print(sum)
sum = 0
count = 1
while count < 101:
if not count % 3:
sum += count
count += 1
print(sum)
- 计算1-100之间不能被7整除的数的和
sum = 0
for count in range(1, 101):
if count % 7:
sum += count
print(sum)
sum = 0
count = 1
while count < 101:
if count % 7 :
sum += count
count += 1
print(sum)
稍微困难
- 求斐波那契数列中第n个数的值:1,1,2,3,5,8,13,21,34....
n = int(input('求斐波那契数列中第n个数的值:'))
A_n = [1,1]
num1 = 0
if n < 3:
print(A_n[n-1])
else:
for count in range(2,n): # 还需要循环 n-2次
num1 = A_n[count - 2] + A_n[count - 1] # 求下一个数
A_n.append(num1) # 存储进列表
print(A_n[n-1])
或者
a_1 = 1
a_2 = 1
a = 0
n = input()
for _ in range(int(n)):
a = a_1 + a_2
a_1 = a
a_2 = a_1
print(a)
- 判断101-200之间有多少个素数,并输出所有素数。判断素数的⽅法:⽤⼀个数分别除2到sqrt(这个数),如果能被整除,则表明此数不是,反之是素数
count1 = 0
import math
for num in range(101,201): # 取 101 - 200的数
for count2 in range(2, int(math.sqrt(num)) + 1):
if not num % count2:
break # 检验是不是素数,不是则退出循环,
else: # 是素数,执行以下代码
print(num)
count1 += 1
print(count1)
- 打印出所有的⽔仙花数,所谓⽔仙花数是指⼀个三位数,其各位数字⽴⽅和等于该数本身。例如:153是⼀个⽔仙花数,因为153 = 1^3 + 5^3 + 3^3
for num1 in range(100, 1000):
if num1 == (num1 % 10) ** 3 + (num1 // 10 % 10) ** 3 + (num1 // 100 %10) ** 3:
print(num1) # 153 370 371 407
- 有⼀分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的第20个分数
分⼦:上⼀个分数的分⼦加分⺟ 分⺟: 上⼀个分数的分⼦ fz = 2 fm = 1 fz+fm / fz
num_fz = 2
num_fm = 1
for _ in range(2,21):
a = num_fz
num_fz += num_fm
num_fm = a
print('%d/%d'%(num_fz, num_fm,))
- 给⼀个正整数,要求:1、求它是⼏位数 2.逆序打印出各位数字
while 1:
num1 = input('输入一个正整数:')
if num1.isdigit() and float(num1) - int(num1) == 0 and int (num1) > 0:
print('%s是%d位数' % (num1, len(num1)) + '\n' + num1[::-1])
print('请确认输入了一个正整数:')