基础
读程序,总结程序的功能:
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中能够被3或者7整除,但是不能同时被3和7整除的数字的个数
编程实现(for和while各写⼀一遍):
1.求1到100之间所有数的和、平均值
- for循环:
sum1 = 0
for i in range(101):
sum1 += i
avg = sum1 / 100
print(sum1)
print(avg)
- while循环:
sum1 = 0
i = 1
while i <= 100:
sum1 += i
i += 1
avg = sum1 / 100
print(sum1)
print(avg)
2.计算1-100之间能3整除的数的和
- for循环:
sum1 = 0
for i in range(101):
if not i % 3:
sum1 += i
print(sum1)
- while循环:
sum1 = 0
i = 1
while i <= 100:
if i % 3:
i += 1
continue
sum1 += i
i += 1
print(sum1)
3.计算1-100之间不不能被7整除的数的和
- for循环:
sum1 = 0
for i in range(1,101):
if i % 7:
sum1 += i
print (sum1)
- while
sum1 = 0
i = 1
while i <= 100:
if i % 7:
sum1 += i
i += 1
print(sum1)
稍微困难
- 求斐波那契数列列中第n个数的值:1,1,2,3,5,8,13,21,34....
num1 = 1
num2 = 1
sum1 = 0
n = input('请问想求第几个斐波那契数:')
n = int(n)
if n <= 2:
#求第1和第2个斐波那契数
print(1)
else:
#求第3个以后的斐波那契数
for _ in range(n-2):
sum1 = num1 + num2
num2 = num1
num1 = sum1
print(sum1)
2.判断101-200之间有多少个素数,并输出所有素数。判断素数的⽅方法:⽤用⼀一个数分别除2到sqrt(这个数),如果能被整除,则表明此数不不是素数,反之是素数
count = 0
for num in range(101,201):
i = 2
while 2 <= i <= num**0.5 + 1:
if not num % i:
break
i += 1
else:
count += 1
print('%d是素数' % (num))
print(count)
输出为21
3.打印出所有的⽔水仙花数,所谓⽔水仙花数是指⼀一个三位数,其各位数字⽴立⽅方和等于该数本身。例例如:153是
⼀一个⽔水仙花数,因为153 = 1^3 + 5^3 + 3^3
for num in range(100,1000):
hun_num = num // 100
ten_num = num // 10 % 10
uni_num = num % 10
if num == hun_num**3 + ten_num**3 + uni_num**3:
print(num)
153
370
371
407
[Finished in 0.2s]
- 有⼀一分数序列列:2/1,3/2,5/3,8/5,13/8,21/13. 求出这个数列列的第20个分数
分⼦子:上⼀一个分数的分⼦子加分⺟母 分⺟母: 上⼀一个分数的分⼦子 fz = 2 fm = 1 fz+fm / fz
fz = 2
fm = 1
for _ in range(19):
next_fm = fz
next_fz = fm + fz
fz = next_fz
fm = next_fm
print('%s/%s' % (fz,fm))
17711/10946
[Finished in 0.3s]
老师答案:
fz = 2
fm = 1
for _ in range(19):
fz, fm = fz + fm, fz
print('%s/%s' % (fz,fm))
- 给⼀一个正整数,要求:1、求它是⼏几位数 2.逆序打印出各位数字
num = input('请输入一个正整数: ')
num = int(num)
qty = 1
while True:
dig = num % 10
print(dig)
if not num // 10:
break
num = num // 10
qty += 1
print('%d是%d位数' % (num,qty))
老师答案:
num = 16723
count = 0
while num:
count +=1
print(num%10)
num //= 10
print(count)
方法二:
num = 16723
num_str = str(num)
print(len(num_str),num_str(::-1))