Python基础练习题100例(Python 3.x)

1:题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?

程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。

程序源代码:

1 for i in range(1, 5):
2     for j in range(1, 5):
3         for k in range(1, 5):
4             if (i != k) and (i != j) and (j != k):
5                 print(i, j, k)
View Code

以上实例输出结果为:

 1 1 2 3
 2 1 2 4
 3 1 3 2
 4 1 3 4
 5 1 4 2
 6 1 4 3
 7 2 1 3
 8 2 1 4
 9 2 3 1
10 2 3 4
11 2 4 1
12 2 4 3
13 3 1 2
14 3 1 4
15 3 2 1
16 3 2 4
17 3 4 1
18 3 4 2
19 4 1 2
20 4 1 3
21 4 2 1
22 4 2 3
23 4 3 1
24 4 3 2
View Code

2:题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的

部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,

可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?

程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。

程序源代码:

 1 i = int(input('净利润:'))
 2 arr = [1000000,600000,400000,200000,100000,0]
 3 rat = [0.01,0.015,0.03,0.05,0.075,0.1]
 4 r = 0
 5 for idx in range(0,6):
 6     if i>arr[idx]:
 7         r+=(i-arr[idx])*rat[idx]
 8         print ((i-arr[idx])*rat[idx])
 9         i=arr[idx]
10 print(r)
View Code

以上实例输出结果为:

1 净利润:120000
2 1500.0
3 10000.0
4 11500.0
View Code

3:题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?

程序分析:

假设该数为 x。

1、则:x + 100 = n2, x + 100 + 168 = m2

2、计算等式:m2 - n2 = (m + n)(m - n) = 168

3、设置: m + n = i,m - n = j,i * j =168,i 和 j 至少一个是偶数

4、可得: m = (i + j) / 2, n = (i - j) / 2,i 和 j 要么都是偶数,要么都是奇数。

5、从 3 和 4 推导可知道,i 与 j 均是大于等于 2 的偶数。

6、由于 i * j = 168, j>=2,则 1 < i < 168 / 2 + 1

7、接下来将 i 的所有数字循环计算即可。

程序源代码:

1 for i in range(1,85):
2     if 168 % i == 0:
3         j = 168 / i;
4         if  i > j and (i + j) % 2 == 0 and (i - j) % 2 == 0 :
5             m = (i + j) / 2
6             n = (i - j) / 2
7             x = n * n - 100
8             print(x)
View Code

以上实例输出结果为:

1 -99.0
2 21.0
3 261.0
4 1581.0
View Code

4:题目:输入某年某月某日,判断这一天是这一年的第几天?

程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天:

程序源代码:

 1 year = int(input('year:\n'))
 2 month = int(input('month:\n'))
 3 day = int(input('day:\n'))
 4 
 5 months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
 6 if 0 < month <= 12:
 7     sum = months[month - 1]
 8 else:
 9     print('data error')
10 sum += day
11 leap = 0
12 if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
13     leap = 1
14 if (leap == 1) and (month > 2):
15     sum += 1
16 print('It is the %dth day in the year.' % sum)
View Code

以上实例输出结果为:

1 year:
2 2018
3 month:
4 3
5 day:
6 23
7 It is the 82th day in the year
View Code

5:题目:输入三个整数x,y,z,请把这三个数由小到大输出。

程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换,然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。

程序源代码:

1 l = []
2 for i in range(3):
3     x = int(input('Please input sorted number:\n'))
4     l.append(x)
5 l.sort()
6 print(l)
View Code

以上实例输出结果为:

1 Please input sorted number:
2 1
3 Please input sorted number:
4 20
5 Please input sorted number:
6 5
7 [1, 5, 20]
View Code

6:题目:斐波那契数列。

程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。在数学上,费波那契数列是以递归的

方法来定义:

程序源代码:

方式一:

1 def fib(n):
2     a, b = 1, 1
3     for i in range(n - 1):
4         a, b = b, a + b
5     return a
6 
7 
8 # 输出了第10个斐波那契数列
9 print(fib(10))
View Code

方式二:

1 # 使用递归
2 def fib(n):
3     if n == 1 or n == 2:
4         return 1
5     return fib(n - 1) + fib(n - 2)
6 
7 
8 # 输出了第10个斐波那契数列
9 print(fib(10))
View Code

以上实例输出结果均为:

1 55
View Code

方式三:

 1 def fib(n):
 2     if n == 1:
 3         return [1]
 4     if n == 2:
 5         return [1, 1]
 6     fibs = [1, 1]
 7     for i in range(2, n):
 8         fibs.append(fibs[-1] + fibs[-2])
 9     return fibs
10 
11 # 输出前 10 个斐波那契数列
12 print(fib(10))
View Code

以上实例输出结果为:

1 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
View Code

7:题目:将一个列表的数据复制到另一个列表中。

程序分析:使用列表[:]。

程序源代码:

1 a = [1, 2, 3]
2 b = a[:]
3 print (b)
View Code

以上实例输出结果为:

1 [1, 2, 3]
View Code

8:题目:输出 9*9 乘法口诀表。

程序分析:分行与列考虑,共9行9列,i控制行,j控制列。

程序源代码:

1 for i in range(1, 10):
2     for j in range(1, i + 1):
3         mul = i * j;
4         if mul < 10:
5             print(str(j) + "x" + str(i) + "=" + str(mul), end="   ");
6         else:
7             print(str(j) + "x" + str(i) + "=" + str(mul), end="  ");
8     print();
View Code

以上实例输出结果为:

1 1x1=1   
2 1x2=2   2x2=4   
3 1x3=3   2x3=6   3x3=9   
4 1x4=4   2x4=8   3x4=12  4x4=16  
5 1x5=5   2x5=10  3x5=15  4x5=20  5x5=25  
6 1x6=6   2x6=12  3x6=18  4x6=24  5x6=30  6x6=36  
7 1x7=7   2x7=14  3x7=21  4x7=28  5x7=35  6x7=42  7x7=49  
8 1x8=8   2x8=16  3x8=24  4x8=32  5x8=40  6x8=48  7x8=56  8x8=64  
9 1x9=9   2x9=18  3x9=27  4x9=36  5x9=45  6x9=54  7x9=63  8x9=72  9x9=81  
View Code

9:题目:暂停一秒输出。

程序分析:使用 time 模块的 sleep() 函数。

程序源代码:

1 import time
2 
3 num_list = [1, 2, 3, 4, 5, 6]
4 for i in num_list:
5     print(i)
6     time.sleep(1)  # 暂停 1 秒
View Code

以上实例输出结果为:

 1 1
 2 #暂停1秒
 3 2
 4 #暂停1秒
 5 3
 6 #暂停1秒
 7 4
 8 #暂停1秒
 9 5
10 #暂停1秒
11 6
View Code

10:题目:暂停一秒输出,并格式化当前时间。

程序分析:无。

程序源代码:

1 import time
2 
3 print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
4 
5 # 暂停一秒
6 time.sleep(1)
7 
8 print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
View Code

以上实例输出结果为:

1 2019-03-23 11:16:07
2 #暂停1秒
3 2019-03-23 11:16:08
View Code

11:题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问

每个月的兔子总数为多少?

程序分析:兔子的规律为数列1,1,2,3,5,8,13,21....

程序源代码:

1 f1 = 1
2 f2 = 1
3 for i in range(1, 22):
4     print('%d %d' % (f1, f2))
5     if (i % 3) == 0:
6         print()
7     f1 = f1 + f2
8     f2 = f1 + f2
View Code

以上实例输出结果为:

 1 1 1
 2 2 3
 3 5 8
 4 
 5 13 21
 6 34 55
 7 89 144
 8 
 9 233 377
10 610 987
11 1597 2584
12 
13 4181 6765
14 10946 17711
15 28657 46368
16 
17 75025 121393
18 196418 317811
19 514229 832040
20 
21 1346269 2178309
22 3524578 5702887
23 9227465 14930352
24 
25 24157817 39088169
26 63245986 102334155
27 165580141 267914296
View Code

12:题目:判断101-200之间有多少个素数,并输出所有素数。

程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。      

程序源代码:

 1 h = 0
 2 leap = 1
 3 from math import sqrt
 4 from sys import stdout
 5 
 6 for m in range(101, 201):
 7     k = int(sqrt(m + 1))
 8     for i in range(2, k + 1):
 9         if m % i == 0:
10             leap = 0
11             break
12     if leap == 1:
13         print('%-4d' % m)
14         h += 1
15         if h % 10 == 0:
16             print()
17     leap = 1
18 print('The total is %d' % h)
View Code

以上实例输出结果为:

 1 101 
 2 103 
 3 107 
 4 109 
 5 113 
 6 127 
 7 131 
 8 137 
 9 139 
10 149 
11 
12 151 
13 157 
14 163 
15 167 
16 173 
17 179 
18 181 
19 191 
20 193 
21 197 
22 
23 199 
24 The total is 21
View Code

13:题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为

153=1的三次方+5的三次方+3的三次方。

程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

程序源代码:

1 for n in range(100, 1000):
2     i = n // 100
3     j = n // 10 % 10
4     k = n % 10
5     if n == i ** 3 + j ** 3 + k ** 3:
6         print(n)
View Code

以上实例输出结果为:

1 153
2 370
3 371
4 407
View Code

14:题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。

程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:

(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。

(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。

(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。

程序源代码:

 1 def reduceNum(n):
 2     print('{} = '.format(n),end="")
 3     if not isinstance(n, int) or n <= 0 :
 4         print('请输入一个正确的数字 !')
 5         exit(0)
 6     elif n in [1] :
 7         print('{}'.format(n))
 8     while n not in [1] : # 循环保证递归
 9         for index in range(2, n + 1) :
10             if n % index == 0:
11                 n //= index # n 等于 n//index
12                 if n == 1:
13                     print(index)
14                 else : # index 一定是素数
15                     print('{} * '.format(index),end="")
16                 break
17 reduceNum(90)
18 reduceNum(100)
View Code

以上实例输出结果为:

1 90 = 2 * 3 * 3 * 5
2 100 = 2 * 2 * 5 * 5
View Code

15:题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。

程序分析:程序分析:(a>b)?a:b这是条件运算符的基本例子。

程序源代码:

1 score = int(input('输入分数:\n'))
2 if score >= 90:
3     grade = '优秀'
4 elif score >= 60:
5     grade = '良好'
6 else:
7     grade = '差劲'
8 print('分数:%d 等级:%s' % (score, grade))
View Code

以上实例输出结果为:

1 输入分数:
2 98
3 分数:98 等级:优秀
View Code

16:题目:输出指定格式的日期。

程序分析:使用 datetime 模块。

程序源代码:

 1 import datetime
 2 
 3 if __name__ == '__main__':
 4     # 输出今日日期,格式为 dd-mm-yyyy。更多选项可以查看 strftime() 方法
 5     print(datetime.date.today().strftime('%d-%m-%Y'))
 6 
 7     # 创建日期对象
 8     date1 = datetime.date(1941, 1, 5)
 9 
10     print(date1.strftime('%d-%m-%Y'))
11 
12     # 日期算术运算
13     date2 = date1 + datetime.timedelta(days=1)
14 
15     print(date2.strftime('%d-%m-%Y'))
16 
17     # 日期替换
18     date3 = date1.replace(year=date1.year + 1)
19 
20     print(date3.strftime('%d-%m-%Y'))
View Code

以上实例输出结果为:

1 23-03-2019
2 05-01-1941
3 06-01-1941
4 05-01-1942
View Code

17:题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

程序分析:利用 while 或 for 语句,条件为输入的字符不为 '\n'。

程序源代码:

 1 import string
 2 
 3 s = input('请输入一个字符串:\n')
 4 letters = 0
 5 space = 0
 6 digit = 0
 7 others = 0
 8 i = 0
 9 while i < len(s):
10     c = s[i]
11     i += 1
12     if c.isalpha():
13         letters += 1
14     elif c.isspace():
15         space += 1
16     elif c.isdigit():
17         digit += 1
18     else:
19         others += 1
20 print('char = %d,space = %d,digit = %d,others = %d' % (letters, space, digit, others))
View Code

以上实例输出结果为:

1 请输入一个字符串:
2 qw12  3..?/
3 char = 2,space = 2,digit = 3,others = 4
View Code

18:题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制。

程序分析:关键是计算出每一项的值。

程序源代码:

 1 from functools import reduce
 2 Tn = 0
 3 Sn = []
 4 n = int(input('n = '))
 5 a = int(input('a = '))
 6 for count in range(n):
 7     Tn = Tn + a
 8     a = a * 10
 9     Sn.append(Tn)
10     print(Tn)
11 
12 Sn = reduce(lambda x, y: x + y, Sn)
13 print("计算和为:", Sn)
View Code

以上实例输出结果为:

1 n = 5
2 a = 2
3 2
4 22
5 222
6 2222
7 22222
8 计算和为: 24690
View Code

19:题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。

程序分析:

程序源代码:

 1 from sys import stdout
 2 
 3 for j in range(2, 1001):
 4     k = []
 5     n = -1
 6     s = j
 7     for i in range(1, j):
 8         if j % i == 0:
 9             n += 1
10             s -= i
11             k.append(i)
12 
13     if s == 0:
14         print(j)
15         for i in range(n):
16             stdout.write(str(k[i]))
17             stdout.write(' ')
18         print(k[n])
View Code

以上实例输出结果为:

1 6
2 1 2 3
3 28
4 1 2 4 7 14
5 496
6 1 2 4 8 16 31 62 124 248
View Code

20:题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?

程序分析:

程序源代码:

 1 tour = []
 2 height = []
 3 
 4 hei = 100.0  # 起始高度
 5 tim = 10  # 次数
 6 
 7 for i in range(1, tim + 1):
 8     # 从第二次开始,落地时的距离应该是反弹高度乘以2(弹到最高点再落下)
 9     if i == 1:
10         tour.append(hei)
11     else:
12         tour.append(2 * hei)
13     hei /= 2
14     height.append(hei)
15 
16 print('总高度:tour = {0}'.format(sum(tour)))
17 print('第10次反弹高度:height = {0}'.format(height[-1]))
View Code

以上实例输出结果为:

1 总高度:tour = 299.609375
2 第10次反弹高度:height = 0.09765625
View Code

21:题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前

一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。

程序分析:采取逆向思维的方法,从后往前推断。

程序源代码:

1 x2 = 1
2 for day in range(9, 0, -1):
3     x1 = (x2 + 1) * 2
4     x2 = x1
5 print(x1)
View Code

以上实例输出结果为:

1 1534
View Code

22:题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不

和x比,c说他不和x,z比,请编程序找出三队赛手的名单。

程序源代码:

1 for i in range(ord('x'), ord('z') + 1):
2     for j in range(ord('x'), ord('z') + 1):
3         if i != j:
4             for k in range(ord('x'), ord('z') + 1):
5                 if (i != k) and (j != k):
6                     if (i != ord('x')) and (k != ord('x')) and (k != ord('z')):
7                         print('order is a -- %s\t b -- %s\tc--%s' % (chr(i), chr(j), chr(k)))
View Code

以上实例输出结果为:

1 order is a -- z     b -- x    c--y
View Code

23:题目:打印出如下图案(菱形):

   *
  ***
 *****
*******
 *****
  ***
   *

程序源代码:

 1 from sys import stdout
 2 
 3 for i in range(4):
 4     for j in range(2 - i + 1):
 5         # stdout.write(' ')
 6         print(" ", end="")
 7     for k in range(2 * i + 1):
 8         # stdout.write('*')
 9         print("*", end="")
10     print()
11 
12 for i in range(3):
13     for j in range(i + 1):
14         # stdout.write(' ')
15         print(" ", end="")
16     for k in range(4 - 2 * i + 1):
17         # stdout.write('*')
18         print("*", end="")
19     print()
View Code

以上实例输出结果为:

1    *
2   ***
3  *****
4 *******
5  *****
6   ***
7    *
View Code

24:题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。

程序分析:请抓住分子与分母的变化规律。

程序源代码:

方法一:

1 a = 2.0
2 b = 1.0
3 s = 0
4 for n in range(1, 21):
5     s += a / b
6     t = a
7     a = a + b
8     b = t
9 print(s)
View Code

方法二:

1 a = 2.0
2 b = 1.0
3 s = 0.0
4 for n in range(1, 21):
5     s += a / b
6     b, a = a, a + b
7 print(s)
View Code

方法三:

 1 from functools import reduce
 2 
 3 a = 2.0
 4 b = 1.0
 5 l = []
 6 l.append(a / b)
 7 for n in range(1, 20):
 8     b, a = a, a + b
 9     l.append(a / b)
10 print(reduce(lambda x, y: x + y, l))
View Code

以上实例输出结果为:

1 32.66026079864164
View Code

25:题目:求1+2!+3!+...+20!的和。

程序分析:此程序只是把累加变成了累乘。

方法一:

1 n = 0
2 s = 0
3 t = 1
4 for n in range(1, 21):
5     t *= n
6     s += t
7 print('1! + 2! + 3! + ... + 20! = %d' % s)
View Code

方法二:

 1 s = 0
 2 l = range(1, 21)
 3 
 4 
 5 def op(x):
 6     r = 1
 7     for i in range(1, x + 1):
 8         r *= i
 9     return r
10 
11 
12 s = sum(map(op, l))
13 print('1! + 2! + 3! + ... + 20! = %d' % s)
View Code

以上实例输出结果为:

1 1! + 2! + 3! + ... + 20! = 2561327494111820313
View Code

26:题目:利用递归方法求5!。

程序分析:递归公式:fn=fn_1*4!

程序源代码:

1 def fact(j):
2     sum = 0
3     if j == 0:
4         sum = 1
5     else:
6         sum = j * fact(j - 1)
7     return sum
8 
9 print(fact(5))
View Code

以上实例输出结果为:

1 120
View Code

27:题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。

程序分析:无。

程序源代码:

 1 def output(s, l):
 2     if l == 0:
 3         return
 4     print(s[l - 1])
 5     output(s, l - 1)
 6 
 7 
 8 s = input('Input a string:')
 9 l = len(s)
10 output(s, l)
View Code

以上实例输出结果为:

1 Input a string:hello
2 o
3 l
4 l
5 e
6 h
View Code

28:题目:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两

岁。问第2个人,说比第一个

人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?

程序分析:利用递归的方法,递归分为回推和递推两个阶段。要想知道第五个人岁数,需知道第四人的岁数,依次类推,推到第一人(10岁),再往回推。

程序源代码:

1 def age(n):
2     if n == 1:
3         c = 10
4     else:
5         c = age(n - 1) + 2
6     return c
7 
8 
9 print(age(5))
View Code

以上实例输出结果为:

1 18
View Code

29:题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。

程序分析:学会分解出每一位数。

程序源代码:

 1 x = int(input("请输入一个数:\n"))
 2 a = x // 10000
 3 b = x % 10000 // 1000
 4 c = x % 1000 // 100
 5 d = x % 100 // 10
 6 e = x % 10
 7 
 8 if a != 0:
 9     print("5 位数:", e, d, c, b, a)
10 elif b != 0:
11     print("4 位数:", e, d, c, b)
12 elif c != 0:
13     print("3 位数:", e, d, c)
14 elif d != 0:
15     print("2 位数:", e, d)
16 else:
17     print( "1 位数:", e)
View Code

以上实例输出结果为:

1 请输入一个数:
2 789
3 3 位数: 9 8 7
View Code

30:题目:一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。

程序分析:无。

程序源代码:

 1 a = int(input("请输入一个数字:\n"))
 2 x = str(a)
 3 flag = True
 4 
 5 for i in range(len(x) // 2):
 6     if x[i] != x[-i - 1]:
 7         flag = False
 8         break
 9 if flag:
10     print("%d 是一个回文数!" % a)
11 else:
12     print("%d 不是一个回文数!" % a)
View Code

以上实例输出结果为:

1 请输入一个数字:
2 154222
3 154222 不是一个回文数!
View Code

31:题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。

程序分析:用情况语句比较好,如果第一个字母一样,则判断用情况语句或if语句判断第二个字母。

程序源代码:

 1 letter = input("please input:")
 2 # while letter  != 'Y':
 3 if letter == 'S':
 4     print('please input second letter:')
 5     letter = input("please input:")
 6     if letter == 'a':
 7         print('Saturday')
 8     elif letter == 'u':
 9         print('Sunday')
10     else:
11         print('data error')
12 
13 elif letter == 'F':
14     print('Friday')
15 
16 elif letter == 'M':
17     print('Monday')
18 
19 elif letter == 'T':
20     print('please input second letter')
21     letter = input("please input:")
22 
23     if letter == 'u':
24         print('Tuesday')
25     elif letter == 'h':
26         print('Thursday')
27     else:
28         print('data error')
29 
30 elif letter == 'W':
31     print('Wednesday')
32 else:
33     print('data error')
View Code

以上实例输出结果为:

1 please input:F
2 Friday
View Code

32:题目:按相反的顺序输出列表的值。

程序分析:无。

程序源代码:

1 a = ['one', 'two', 'three']
2 for i in a[::-1]:
3     print(i)
View Code

以上实例输出结果为:

1 three
2 two
3 one
View Code

33:题目:按逗号分隔列表。

程序分析:无。

程序源代码:

1 L = [1, 2, 3, 4, 5]
2 s1 = ','.join(str(n) for n in L)
3 print(s1)
View Code

以上实例输出结果为:

1 1,2,3,4,5
View Code

34:题目:练习函数调用。

程序分析:无。

程序源代码:

 1 def hello_world():
 2     print('hello world')
 3 
 4 
 5 def three_hellos():
 6     for i in range(3):
 7         hello_world()
 8 
 9 
10 if __name__ == '__main__':
11     three_hellos()
View Code

以上实例输出结果为:

1 hello world
2 hello world
3 hello world
View Code

35:题目:文本颜色设置。

程序分析:无。

程序源代码:

 1 class bcolors:
 2     HEADER = '\033[95m'
 3     OKBLUE = '\033[94m'
 4     OKGREEN = '\033[92m'
 5     WARNING = '\033[93m'
 6     FAIL = '\033[91m'
 7     ENDC = '\033[0m'
 8     BOLD = '\033[1m'
 9     UNDERLINE = '\033[4m'
10 
11 
12 print(bcolors.OKBLUE + "成功的颜色字体?" + bcolors.ENDC)
View Code

以上实例输出结果为:

1 成功的颜色字体?
View Code

36:题目:求100之内的素数。

程序分析:无。

程序源代码:

 1 # 输出指定范围内的素数
 2 
 3 # 用户输入数据
 4 lower = int(input("输入区间最小值: "))
 5 upper = int(input("输入区间最大值: "))
 6 
 7 for num in range(lower, upper + 1):
 8     # 素数大于 1
 9     if num > 1:
10         for i in range(2, num):
11             if (num % i) == 0:
12                 break
13         else:
14             print(num)
View Code

以上实例输出结果为:

 1 输入区间最小值: 1
 2 输入区间最大值: 100
 3 2
 4 3
 5 5
 6 7
 7 11
 8 13
 9 17
10 19
11 23
12 29
13 31
14 37
15 41
16 43
17 47
18 53
19 59
20 61
21 67
22 71
23 73
24 79
25 83
26 89
27 97
View Code

37:题目:对10个数进行排序。

程序分析:可以利用选择法,即从后9个比较过程中,选择一个最小的与第一个元素交换,下次类推,即用第二个元素与后8个进行比较,并进行交换。

程序源代码:

 1 if __name__ == "__main__":
 2     N = 10
 3     # input data
 4     print("请输入10个数字:")
 5 
 6     l = []
 7     for i in range(N):
 8         l.append(int(input('输入要排序的数字:')))
 9     print("排序之前:")
10     for i in range(N):
11         print(l[i],end=" ")
12     print()
13 
14     # 排列10个数字
15     for i in range(N - 1):
16         min = i
17         for j in range(i + 1, N):
18             if l[min] > l[j]: min = j
19         l[i], l[min] = l[min], l[i]
20     print('排列之后:')
21     for i in range(N):
22         print(l[i],end=" ")
View Code

以上实例输出结果为:

 1 请输入10个数字:
 2 输入要排序的数字:1
 3 输入要排序的数字:2
 4 输入要排序的数字:5
 5 输入要排序的数字:7
 6 输入要排序的数字:8
 7 输入要排序的数字:9
 8 输入要排序的数字:5
 9 输入要排序的数字:22
10 输入要排序的数字:3
11 输入要排序的数字:0
12 排序之前:
13 1 2 5 7 8 9 5 22 3 0 
14 排列之后:
15 0 1 2 3 5 5 7 8 9 22 
View Code

38:题目:求一个3*3矩阵主对角线元素之和。

程序分析:利用双重for循环控制输入二维数组,再将a[i][i]累加后输出。

程序源代码:

 1 if __name__ == '__main__':
 2     a = []
 3     sum = 0.0
 4     for i in range(3):
 5         a.append([])
 6         for j in range(3):
 7             a[i].append(float(input("input num:")))
 8     for i in range(3):
 9         sum += a[i][i]
10     print(sum)
View Code

以上实例输出结果为:

 1 input num:4
 2 input num:2
 3 input num:3
 4 input num:5
 5 input num:6
 6 input num:1
 7 input num:2
 8 input num:3
 9 input num:7
10 17.0
View Code

39:题目:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。

程序分析:首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,插入后此元素之后的数,依次后移一个位置。

程序源代码:

 1 if __name__ == '__main__':
 2     # 方法一 : 0 作为加入数字的占位符
 3     a = [1, 4, 6, 9, 13, 16, 19, 28, 40, 100, 0]
 4     print('原始列表:')
 5     for i in range(len(a)):
 6         print(a[i],end=" ")
 7     number = int(input("\n插入一个数字:"))
 8     end = a[9]
 9     if number > end:
10         a[10] = number
11     else:
12         for i in range(10):
13             if a[i] > number:
14                 temp1 = a[i]
15                 a[i] = number
16                 for j in range(i + 1, 11):
17                     temp2 = a[j]
18                     a[j] = temp1
19                     temp1 = temp2
20                 break
21     print('排序后列表:')
22     for i in range(11):
23         print(a[i],end=" ")
View Code

以上实例输出结果为:

1 原始列表:
2 1 4 6 9 13 16 19 28 40 100 0 
3 插入一个数字:5
4 排序后列表:
5 1 4 5 6 9 13 16 19 28 40 100 
View Code

40:题目:将一个数组逆序输出。

程序分析:用第一个与最后一个交换。

程序源代码:

1 if __name__ == '__main__':
2     a = [9, 6, 5, 4, 1]
3     N = len(a)
4     print(a)
5     for i in range(len(a) // 2):
6         a[i], a[N - i - 1] = a[N - i - 1], a[i]
7     print(a)
View Code

以上实例输出结果为:

1 [9, 6, 5, 4, 1]
2 [1, 4, 5, 6, 9]
View Code

41:题目:模仿静态变量的用法。

程序分析:无。

程序源代码:

 1 def varfunc():
 2     var = 0
 3     print('var = %d' % var)
 4     var += 1
 5 
 6 
 7 if __name__ == '__main__':
 8     for i in range(3):
 9         varfunc()
10 
11 
12 # 类的属性
13 # 作为类的一个属性吧
14 class Static:
15     StaticVar = 5
16 
17     def varfunc(self):
18         self.StaticVar += 1
19         print(self.StaticVar)
20 
21 
22 print(Static.StaticVar)
23 a = Static()
24 for i in range(3):
25     a.varfunc()
View Code

以上实例输出结果为:

1 var = 0
2 var = 0
3 var = 0
4 5
5 6
6 7
7 8
View Code

42:题目:学习使用auto定义变量的用法。

程序分析:没有auto关键字,使用变量作用域来举例吧。

程序源代码:

 1 num = 2
 2 
 3 
 4 def autofunc():
 5     num = 1
 6     print('internal block num = %d' % num)
 7     num += 1
 8 
 9 
10 for i in range(3):
11     print('The num = %d' % num)
12     num += 1
13     autofunc()
View Code

以上实例输出结果为:

1 The num = 2
2 internal block num = 1
3 The num = 3
4 internal block num = 1
5 The num = 4
6 internal block num = 1
View Code

43:题目:模仿静态变量(static)另一案例。

程序分析:演示一个python作用域使用方法

程序源代码:

 1 class Num:
 2     nNum = 1
 3 
 4     def inc(self):
 5         self.nNum += 1
 6         print('nNum = %d' % self.nNum)
 7 
 8 
 9 if __name__ == '__main__':
10     nNum = 2
11     inst = Num()
12     for i in range(3):
13         nNum += 1
14         print('The num = %d' % nNum)
15         inst.inc()
View Code

以上实例输出结果为:

1 The num = 3
2 nNum = 2
3 The num = 4
4 nNum = 3
5 The num = 5
6 nNum = 4
View Code

44:两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵:

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

程序分析:创建一个新的 3 行 3 列的矩阵,使用 for 迭代并取出 X 和 Y 矩阵中对应位置的值,相加后放到新矩阵的对应位置中。

程序源代码:

 1 X = [[12,7,3],
 2     [4 ,5,6],
 3     [7 ,8,9]]
 4  
 5 Y = [[5,8,1],
 6     [6,7,3],
 7     [4,5,9]]
 8  
 9 result = [[0,0,0],
10          [0,0,0],
11          [0,0,0]]
12  
13 # 迭代输出行
14 for i in range(len(X)):
15    # 迭代输出列
16    for j in range(len(X[0])):
17        result[i][j] = X[i][j] + Y[i][j]
18  
19 for r in result:
20    print(r)
View Code

以上实例输出结果为:

1 [17, 15, 4]
2 [10, 12, 9]
3 [11, 13, 18]
View Code

45:题目:统计 1 到 100 之和。

程序分析:

程序源代码:

1 tmp = 0
2 for i in range(1, 101):
3     tmp += i
4 print('The sum is %d' % tmp)
View Code

以上实例输出结果为:

1 The sum is 5050
View Code

46:题目:求输入数字的平方,如果平方运算后小于 50 则退出。

程序分析:

程序源代码:

 1 TRUE = 1
 2 FALSE = 0
 3 
 4 
 5 def SQ(x):
 6     return x * x
 7 
 8 
 9 print('如果输入的数字小于 50,程序将停止运行。')
10 again = 1
11 while again:
12     num = int(input('请输入一个数字:'))
13     print('运算结果为: %d' % (SQ(num)))
14     if SQ(num) >= 50:
15         again = TRUE
16     else:
17         again = FALSE
View Code

以上实例输出结果为:

1 如果输入的数字小于 50,程序将停止运行。
2 请输入一个数字:8
3 运算结果为: 64
4 请输入一个数字:2
5 运算结果为: 4
View Code

47:题目:两个变量值互换。

程序分析:

程序源代码:

 1 def exchange(a, b):
 2     a, b = b, a
 3     return (a, b)
 4 
 5 
 6 if __name__ == '__main__':
 7     x = 10
 8     y = 20
 9     print('x = %d,y = %d' % (x, y))
10     x, y = exchange(x, y)
11     print('x = %d,y = %d' % (x, y))
View Code

以上实例输出结果为:

1 x = 10,y = 20
2 x = 20,y = 10
View Code

48:题目:数字比较。

程序分析:

程序源代码:

 1 if __name__ == '__main__':
 2     i = 10
 3     j = 20
 4     if i > j:
 5         print('%d 大于 %d' % (i, j))
 6     elif i == j:
 7         print('%d 等于 %d' % (i, j))
 8     elif i < j:
 9         print('%d 小于 %d' % (i, j))
10     else:
11         print('未知')
View Code

以上实例输出结果为:

1 10 小于 20
View Code

49:题目:使用lambda来创建匿名函数。

程序分析:

程序源代码:

1 MAXIMUM = lambda x, y: (x > y) * x + (x < y) * y
2 MINIMUM = lambda x, y: (x > y) * y + (x < y) * x
3 
4 if __name__ == '__main__':
5     a = 10
6     b = 20
7     print('The largar one is %d' % MAXIMUM(a, b))
8     print('The lower one is %d' % MINIMUM(a, b))
View Code

以上实例输出结果为:

1 The largar one is 20
2 The lower one is 10
View Code

50:题目:输出一个随机数。

程序分析:使用 random 模块。

程序源代码:

1 import random
2 
3 # 生成 10 到 20 之间的随机数
4 print(random.randint(10, 20))
View Code

以上实例输出结果为:

1 19
View Code

51:题目:学习使用按位与 & 。

程序分析:0&0=0; 0&1=0; 1&0=0; 1&1=1。

程序源代码:

1 if __name__ == '__main__':
2     a = 8
3     b = a & 4
4     print('a & b = %d' % b)
5     b &= 2
6     print('a & b = %d' % b)
View Code

以上实例输出结果为:

1 a & b = 0
2 a & b = 0
View Code

52:题目:学习使用按位或 | 。

程序分析:0|0=0; 0|1=1; 1|0=1; 1|1=1

程序源代码:

1 if __name__ == '__main__':
2     a = 12
3     b = a | 3
4     print('a | b is %d' % b)
5     b |= 7
6     print('a | b is %d' % b)
View Code

以上实例输出结果为:

1 a | b is 15
2 a | b is 15
View Code

53:题目:学习使用按位异或 ^ 。

程序分析:0^0=0; 0^1=1; 1^0=1; 1^1=0

程序源代码:

1 if __name__ == '__main__':
2     a = 12
3     b = a ^ 3
4     print('The a ^ 3 = %d' % b)
5     b ^= 7
6     print('The a ^ b = %d' % b)
View Code

以上实例输出结果为:

1 The a ^ 3 = 15
2 The a ^ b = 8
View Code

54:题目:取一个整数a从右端开始的4〜7位。

程序分析:可以这样考虑:

(1)先使a右移4位。

(2)设置一个低4位全为1,其余全为0的数。可用~(~0<<4)

(3)将上面二者进行&运算。

程序源代码:

1 if __name__ == '__main__':
2     a = int(input('input a number:\n'))
3     b = a >> 4
4     c = ~(~0 << 4)
5     d = b & c
6     print('%o\t%o' % (a, d))
View Code

以上实例输出结果为:

1 input a number:
2 23
3 27    1
View Code

55:题目:学习使用按位取反~。

程序分析:~0=1; ~1=0;

(1)先使a右移4位。

(2)设置一个低4位全为1,其余全为0的数。可用~(~0<<4)

(3)将上面二者进行&运算。

程序源代码:

1 if __name__ == '__main__':
2     a = 234
3     b = ~a
4     print('The a\'s 1 complement is %d' % b)
5     a = ~a
6     print('The a\'s 2 complement is %d' % a)
View Code

以上实例输出结果为:

1 The a's 1 complement is -235
2 The a's 2 complement is -235
View Code

56:题目:画图,学用circle画圆形。   

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     from Tkinter import *
 3 
 4     canvas = Canvas(width=800, height=600, bg='yellow')
 5     canvas.pack(expand=YES, fill=BOTH)
 6     k = 1
 7     j = 1
 8     for i in range(0, 26):
 9         canvas.create_oval(310 - k, 250 - k, 310 + k, 250 + k, width=1)
10         k += j
11         j += 0.3
12 
13     mainloop()
View Code

57:题目:画图,学用line画直线。

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     from Tkinter import *
 3  
 4     canvas = Canvas(width=300, height=300, bg='green')   
 5     canvas.pack(expand=YES, fill=BOTH)                  
 6     x0 = 263
 7     y0 = 263
 8     y1 = 275
 9     x1 = 275
10     for i in range(19):
11         canvas.create_line(x0,y0,x0,y1, width=1, fill='red')
12         x0 = x0 - 5
13         y0 = y0 - 5
14         x1 = x1 + 5
15         y1 = y1 + 5
16  
17     x0 = 263
18     y1 = 275
19     y0 = 263
20     for i in range(21):
21         canvas.create_line(x0,y0,x0,y1,fill = 'red')
22         x0 += 5
23         y0 += 5
24         y1 += 5
25  
26     mainloop()
View Code

58:题目:画图,学用rectangle画方形。   

程序分析:rectangle(int left, int top, int right, int bottom)

 1 if __name__ == '__main__':
 2     from Tkinter import *
 3     root = Tk()
 4     root.title('Canvas')
 5     canvas = Canvas(root,width = 400,height = 400,bg = 'yellow')
 6     x0 = 263
 7     y0 = 263
 8     y1 = 275
 9     x1 = 275
10     for i in range(19):
11         canvas.create_rectangle(x0,y0,x1,y1)
12         x0 -= 5
13         y0 -= 5
14         x1 += 5
15         y1 += 5
16         
17     canvas.pack()
18     root.mainloop()
View Code

59:题目:画图,综合例子。  

程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

程序源代码:

 1 if __name__ == '__main__':
 2     from Tkinter import *
 3 
 4     canvas = Canvas(width=300, height=300, bg='green')
 5     canvas.pack(expand=YES, fill=BOTH)
 6     x0 = 150
 7     y0 = 100
 8     canvas.create_oval(x0 - 10, y0 - 10, x0 + 10, y0 + 10)
 9     canvas.create_oval(x0 - 20, y0 - 20, x0 + 20, y0 + 20)
10     canvas.create_oval(x0 - 50, y0 - 50, x0 + 50, y0 + 50)
11     import math
12 
13     B = 0.809
14     for i in range(16):
15         a = 2 * math.pi / 16 * i
16         x = math.ceil(x0 + 48 * math.cos(a))
17         y = math.ceil(y0 + 48 * math.sin(a) * B)
18         canvas.create_line(x0, y0, x, y, fill='red')
19     canvas.create_oval(x0 - 60, y0 - 60, x0 + 60, y0 + 60)
20 
21     for k in range(501):
22         for i in range(17):
23             a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k
24             x = math.ceil(x0 + 48 * math.cos(a))
25             y = math.ceil(y0 + 48 + math.sin(a) * B)
26             canvas.create_line(x0, y0, x, y, fill='red')
27         for j in range(51):
28             a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k - 1
29             x = math.ceil(x0 + 48 * math.cos(a))
30             y = math.ceil(y0 + 48 * math.sin(a) * B)
31             canvas.create_line(x0, y0, x, y, fill='red')
32     mainloop()
View Code

60:题目:计算字符串长度。  

程序分析:无。

程序源代码:

1 s = 'strlen'
2 print(len(s))
View Code

以上实例输出结果为:

1  6
View Code

61:题目:打印出杨辉三角形。  

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     a = []
 3     for i in range(10):
 4         a.append([])
 5         for j in range(10):
 6             a[i].append(0)
 7     for i in range(10):
 8         a[i][0] = 1
 9         a[i][i] = 1
10     for i in range(2, 10):
11         for j in range(1, i):
12             a[i][j] = a[i - 1][j - 1] + a[i - 1][j]
13     for i in range(10):
14         for j in range(i + 1):
15             print(str(a[i][j]), end=" ")
16         print()
View Code

以上实例输出结果为:

 1 1 
 2 1 1 
 3 1 2 1 
 4 1 3 3 1 
 5 1 4 6 4 1 
 6 1 5 10 10 5 1 
 7 1 6 15 20 15 6 1 
 8 1 7 21 35 35 21 7 1 
 9 1 8 28 56 70 56 28 8 1 
10 1 9 36 84 126 126 84 36 9 1 
View Code

62:题目:查找字符串。  

程序分析:无。

程序源代码:

1 sStr1 = 'abcdefg'
2 sStr2 = 'cde'
3 print(sStr1.find(sStr2))
View Code

以上实例输出结果为:

1  2
View Code

63:题目:画椭圆。 

程序分析:使用 Tkinter。

程序源代码:

 1 if __name__ == '__main__':
 2     from Tkinter import *
 3     x = 360
 4     y = 160
 5     top = y - 30
 6     bottom = y - 30
 7     
 8     canvas = Canvas(width = 400,height = 600,bg = 'white')
 9     for i in range(20):
10         canvas.create_oval(250 - top,250 - bottom,250 + top,250 + bottom)
11         top -= 5
12         bottom += 5
13     canvas.pack()
14     mainloop()
View Code

64:题目:利用ellipse 和 rectangle 画图。

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     from Tkinter import *
 3     canvas = Canvas(width = 400,height = 600,bg = 'white')
 4     left = 20
 5     right = 50
 6     top = 50
 7     num = 15
 8     for i in range(num):
 9         canvas.create_oval(250 - right,250 - left,250 + right,250 + left)
10         canvas.create_oval(250 - 20,250 - top,250 + 20,250 + top)
11         canvas.create_rectangle(20 - 2 * i,20 - 2 * i,10 * (i + 2),10 * ( i + 2))
12         right += 5
13         left += 5
14         top += 10
15 
16     canvas.pack()
17     mainloop()
View Code

65:题目:一个最优美的图案。  

程序分析:无。

程序源代码:

 1 import math
 2 class PTS:
 3     def __init__(self):
 4         self.x = 0
 5         self.y = 0
 6 points = []
 7 
 8 def LineToDemo():
 9     from Tkinter import *
10     screenx = 400
11     screeny = 400
12     canvas = Canvas(width = screenx,height = screeny,bg = 'white')
13 
14     AspectRatio = 0.85
15     MAXPTS = 15
16     h = screeny
17     w = screenx
18     xcenter = w / 2
19     ycenter = h / 2
20     radius = (h - 30) / (AspectRatio * 2) - 20
21     step = 360 / MAXPTS
22     angle = 0.0
23     for i in range(MAXPTS):
24         rads = angle * math.pi / 180.0
25         p = PTS()
26         p.x = xcenter + int(math.cos(rads) * radius)
27         p.y = ycenter - int(math.sin(rads) * radius * AspectRatio)
28         angle += step
29         points.append(p)
30     canvas.create_oval(xcenter - radius,ycenter - radius,
31                        xcenter + radius,ycenter + radius)
32     for i in range(MAXPTS):
33         for j in range(i,MAXPTS):
34             canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y)
35 
36     canvas.pack()
37     mainloop()
38 if __name__ == '__main__':
39     LineToDemo()
View Code

66:题目:输入3个数a,b,c,按大小顺序输出。   

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     n1 = int(input('n1 = :'))
 3     n2 = int(input('n2 = :'))
 4     n3 = int(input('n3 = :'))
 5 
 6 
 7     def swap(p1, p2):
 8         return p2, p1
 9 
10 
11     if n1 > n2: n1, n2 = swap(n1, n2)
12     if n1 > n3: n1, n3 = swap(n1, n3)
13     if n2 > n3: n2, n3 = swap(n2, n3)
14 
15     print(n1, n2, n3)
View Code

以上实例输出结果为:

1 n1 = :5
2 n2 = :6
3 n3 = :2
4 2 5 6
View Code

67:题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。

程序分析:无。

程序源代码:

 1 def inp(numbers):
 2     for i in range(6):
 3         numbers.append(int(input('输入一个数字:')))
 4 
 5 
 6 p = 0
 7 
 8 
 9 def arr_max(array):
10     max = 0
11     for i in range(1, len(array) - 1):
12         p = i
13         if array[p] > array[max]: max = p
14     k = max
15     array[0], array[k] = array[k], array[0]
16 
17 
18 def arr_min(array):
19     min = 0
20     for i in range(1, len(array) - 1):
21         p = i
22         if array[p] < array[min]: min = p
23     l = min
24     array[5], array[l] = array[l], array[5]
25 
26 
27 def outp(numbers):
28     for i in range(len(numbers)):
29         print(numbers[i])
30 
31 
32 if __name__ == '__main__':
33     array = []
34     inp(array)  # 输入 6 个数字并放入数组
35     arr_max(array)  # 获取最大元素并与第一个元素交换
36     arr_min(array)  # 获取最小元素并与最后一个元素交换
37     print('计算结果:')
38     outp(array)
View Code

以上实例输出结果为:

 1 输入一个数字:1
 2 输入一个数字:2
 3 输入一个数字:5
 4 输入一个数字:8
 5 输入一个数字:7
 6 输入一个数字:6
 7 计算结果:
 8 8
 9 2
10 5
11 6
12 7
13 1
View Code

68:题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     n = int(input('整数 n 为:\n'))
 3     m = int(input('向后移 m 个位置为:\n'))
 4 
 5 
 6     def move(array, n, m):
 7         array_end = array[n - 1]
 8         for i in range(n - 1, -1, - 1):
 9             array[i] = array[i - 1]
10         array[0] = array_end
11         m -= 1
12         if m > 0: move(array, n, m)
13 
14 
15     number = []
16     for i in range(n):
17         number.append(int(input('输入一个数字:\n')))
18     print('原始列表:', number)
19 
20     move(number, n, m)
21 
22     print('移动之后:', number)
View Code

以上实例输出结果为:

 1 整数 n 为:
 2 5
 3 向后移 m 个位置为:
 4 2
 5 输入一个数字:
 6 1
 7 输入一个数字:
 8 2
 9 输入一个数字:
10 3
11 输入一个数字:
12 4
13 输入一个数字:
14 5
15 原始列表: [1, 2, 3, 4, 5]
16 移动之后: [4, 5, 1, 2, 3]
View Code

 

 69:题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     nmax = 50
 3     n = int(input('请输入总人数:'))
 4     num = []
 5     for i in range(n):
 6         num.append(i + 1)
 7 
 8     i = 0
 9     k = 0
10     m = 0
11 
12     while m < n - 1:
13         if num[i] != 0: k += 1
14         if k == 3:
15             num[i] = 0
16             k = 0
17             m += 1
18         i += 1
19         if i == n: i = 0
20 
21     i = 0
22     while num[i] == 0: i += 1
23     print(num[i])
View Code

以上实例输出结果为:

1 请输入总人数:32
2 4
View Code

70:题目:写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     s = input('please input a string:\n')
3     print('the string has %d characters.' % len(s))
View Code

以上实例输出结果为:

1 please input a string:
2 1215sd4f5
3 the string has 9 characters.
View Code

71:题目:编写input()和output()函数输入,输出5个学生的数据记录。

程序分析:无。

程序源代码:

 1 N = 5
 2 # stu
 3 # num : string
 4 # name : string
 5 # score[4]: list
 6 student = []
 7 for i in range(5):
 8     student.append(['', '', []])
 9 
10 
11 def input_stu(stu):
12     for i in range(N):
13         stu[i][0] = input('input student num:')
14         stu[i][1] = input('input student name:')
15         for j in range(3):
16             stu[i][2].append(int(input('score:')))
17 
18 
19 def output_stu(stu):
20     for i in range(N):
21         print('%-6s%-10s' % (stu[i][0], stu[i][1]))
22         for j in range(3):
23             print('%-8d' % stu[i][2][j])
24 
25 
26 if __name__ == '__main__':
27     input_stu(student)
28     print(student)
29     output_stu(student)
View Code

以上实例输出结果为:

 1 input student num:1
 2 input student name:d
 3 score:3
 4 score:4
 5 score:65
 6 input student num:2
 7 input student name:e
 8 score:3
 9 score:54
10 score:7
11 input student num:3
12 input student name:fds
13 score:3
14 score:5
15 score:6
16 input student num:4
17 input student name:s
18 score:3
19 score:45
20 score:67
21 input student num:5
22 input student name:rs
23 score:3
24 score:4
25 score:6
26 [['1', 'd', [3, 4, 65]], ['2', 'e', [3, 54, 7]], ['3', 'fds', [3, 5, 6]], ['4', 's', [3, 45, 67]], ['5', 'rs', [3, 4, 6]]]
27 1     d         
28 3       
29 4       
30 65      
31 2     e         
32 3       
33 54      
34 7       
35 3     fds       
36 3       
37 5       
38 6       
39 4     s         
40 3       
41 45      
42 67      
43 5     rs        
44 3       
45 4       
46 6       
View Code

72:题目:创建一个链表。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     ptr = []
3     for i in range(5):
4         num = int(input('please input a number:'))
5         ptr.append(num)
6     print(ptr)
View Code

以上实例输出结果为:

1 please input a number:4
2 please input a number:1
3 please input a number:2
4 please input a number:3
5 please input a number:6
6 [4, 1, 2, 3, 6]
View Code

73:题目:反向输出一个链表。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     ptr = []
3     for i in range(5):
4         num = int(input('please input a number:'))
5         ptr.append(num)
6     print(ptr)
7     ptr.reverse()
8     print(ptr)
View Code

以上实例输出结果为:

1 please input a number:1
2 please input a number:2
3 please input a number:3
4 please input a number:4
5 please input a number:5
6 [1, 2, 3, 4, 5]
7 [5, 4, 3, 2, 1]
View Code

74:题目:列表排序及连接。

程序分析:排序可使用 sort() 方法,连接可以使用 + 号或 extend() 方法。

程序源代码:

 1 if __name__ == '__main__':
 2     a = [1, 3, 2]
 3     b = [3, 4, 5]
 4     a.sort()  # 对列表 a 进行排序
 5     print(a)
 6 
 7     # 连接列表 a 与 b
 8     print(a + b)
 9 
10     # 连接列表 a 与 b
11     a.extend(b)
12     print(a)
View Code

以上实例输出结果为:

1 [1, 2, 3]
2 [1, 2, 3, 3, 4, 5]
3 [1, 2, 3, 3, 4, 5]
View Code

75:题目:放松一下,算一道简单的题目。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     for i in range(5):
3         n = 0
4         if i != 1: n += 1
5         if i == 3: n += 1
6         if i == 4: n += 1
7         if i != 4: n += 1
8         if n == 3: print(64 + i)
View Code

以上实例输出结果为:

1 67
View Code

76:题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n

程序分析:无。

程序源代码:

 1 def peven(n):
 2     i = 0
 3     s = 0.0
 4     for i in range(2, n + 1, 2):
 5         s += 1.0 / i  # Python里,整数除整数,只能得出整数,所以需要使用 浮点数 1.0
 6     return s
 7 
 8 
 9 def podd(n):
10     s = 0.0
11     for i in range(1, n + 1, 2):
12         s += 1.0 / i  # Python里,整数除整数,只能得出整数,所以需要使用 浮点数 1.0
13     return s
14 
15 
16 def dcall(fp, n):
17     s = fp(n)
18     return s
19 
20 
21 if __name__ == '__main__':
22     n = int(input('input a number:\n'))
23     if n % 2 == 0:
24         sum = dcall(peven, n)
25     else:
26         sum = dcall(podd, n)
27     print(sum)
View Code

以上实例输出结果为:

1 input a number:
2 12
3 1.2249999999999999
View Code

77:题目:循环输出列表

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     s = ["man", "woman", "girl", "boy", "sister"]
3     for i in range(len(s)):
4         print(s[i])
View Code

以上实例输出结果为:

1 man
2 woman
3 girl
4 boy
5 sister
View Code

78:题目:找到年龄最大的人,并输出。请找出程序中有什么问题。

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     person = {"li": 18, "wang": 50, "zhang": 80, "sun": 22}
 3     m = 'li'
 4     for key in person.keys():
 5         if key != m:
 6             if person[m] < person[key]:
 7                 m = key
 8         else:
 9             continue
10 
11     print('%s,%d' % (m, person[m]))
View Code

以上实例输出结果为:

1 zhang,80
View Code

79:题目:字符串排序。

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     str1 = input('input string:')
 3     str2 = input('input string:')
 4     str3 = input('input string:')
 5     print(str1, str2, str3)
 6 
 7     if str1 > str2: str1, str2 = str2, str1
 8     if str1 > str3: str1, str3 = str3, str1
 9     if str2 > str3: str2, str3 = str3, str2
10 
11     print('after being sorted:',end=" ")
12     print(str1, str2, str3)
View Code

以上实例输出结果为:

1 input string:fasd
2 input string:fdse
3 input string:gbx
4 fasd fdse gbx
5 after being sorted: fasd fdse gbx
View Code

80:题目:海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二

只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原

来最少有多少个桃子?

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     i = 0
 3     j = 1
 4     x = 0
 5     while (i < 5):
 6         x = 4 * j
 7         for i in range(0, 5):
 8             if (x % 4 != 0):
 9                 break
10             else:
11                 i += 1
12             x = (x / 4) * 5 + 1
13         j += 1
14     print(x)
View Code

以上实例输出结果为:

1 3121.0
View Code

81:题目:809*??=800*??+9*?? 其中??代表的两位数, 809*??为四位数,8*??的结果为两位数,9*??的结果为3位数。求??代表的两位数,及809*

??后的结果。

程序分析:无。

程序源代码:

1 a = 809
2 for i in range(10, 100):
3     b = i * a
4     if b >= 1000 and b <= 10000 and 8 * i < 100 and 9 * i >= 100:
5         print(b, ' = 800 * ', i, ' + 9 * ', i)
View Code

以上实例输出结果为:

1 9708  = 800 *  12  + 9 *  12
View Code

82:题目:八进制转换为十进制

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     n = 0
3     p = input('input a octal number:\n')
4     for i in range(len(p)):
5         n = n * 8 + ord(p[i]) - ord('0')
6     print(n)
View Code

以上实例输出结果为:

1 input a octal number:
2 12
3 10
View Code

83:题目:求0—7所能组成的奇数个数。

程序分析:

组成1位数是4个。

组成2位数是7*4个。

组成3位数是7*8*4个。

组成4位数是7*8*8*4个。

......

程序源代码:

 1 if __name__ == '__main__':
 2     sum = 4
 3     s = 4
 4     for j in range(2, 9):
 5         print(sum)
 6         if j <= 2:
 7             s *= 7
 8         else:
 9             s *= 8
10         sum += s
11     print('sum = %d' % sum)
View Code

以上实例输出结果为:

1 4
2 32
3 256
4 2048
5 16384
6 131072
7 1048576
8 sum = 8388608
View Code

84:题目:输入一个奇数,然后判断最少几个 9 除于该数的结果为整数。

程序分析:999999 / 13 = 76923。

程序源代码:

 1 if __name__ == '__main__':
 2     zi = int(input('输入一个数字:\n'))
 3     n1 = 1
 4     c9 = 1
 5     m9 = 9
 6     sum = 9
 7     while n1 != 0:
 8         if sum % zi == 0:
 9             n1 = 0
10         else:
11             m9 *= 10
12             sum += m9
13             c9 += 1
14     print ('%d 个 9 可以被 %d 整除 : %d' % (c9,zi,sum))
15     r = sum / zi
16     print ('%d / %d = %d' % (sum,zi,r))
View Code

以上实例输出结果为:

1 输入一个数字:
2 7
3 6 个 9 可以被 7 整除 : 999999
4 999999 / 7 = 142857
View Code

85:题目:连接字符串。

程序分析:无。

程序源代码:

1 delimiter = ','
2 mylist = ['Brazil', 'Russia', 'India', 'China']
3 print(delimiter.join(mylist))
View Code

以上实例输出结果为:

1 Brazil,Russia,India,China
View Code

86:题目:两个字符串连接程序。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     a = "acegikm"
3     b = "bdfhjlnpq"
4     # 连接字符串
5     c = a + b
6     print(c)
View Code

以上实例输出结果为:

1 acegikmbdfhjlnpq
View Code

87:题目:回答结果(结构体变量传递)。

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     class student:
 3         x = 0
 4         c = 0
 5     def f(stu):
 6         stu.x = 20
 7         stu.c = 'c'
 8     a= student()
 9     a.x = 3
10     a.c = 'a'
11     f(a)
12     print (a.x,a.c)
View Code

以上实例输出结果为:

1 20 c
View Code

88:题目:读取7个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     n = 1
3     while n <= 7:
4         a = int(input('input a number:'))
5         while a < 1 or a > 50:
6             a = int(input('input a number:'))
7         print(a * '*')
8         n += 1
View Code

以上实例输出结果为:

 1 input a number:2
 2 **
 3 input a number:3
 4 ***
 5 input a number:5
 6 *****
 7 input a number:6
 8 ******
 9 input a number:4
10 ****
11 input a number:8
12 ********
13 input a number:7
14 *******
View Code

89:题目:某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用和除以10的余数代

替该数字,再将第一位和第四位交换,第二位和第三位交换。

程序分析:无。

程序源代码:

 1 from sys import stdout
 2 
 3 if __name__ == '__main__':
 4     a = int(input('输入四个数字:\n'))
 5     aa = []
 6     aa.append(a % 10)
 7     aa.append(a % 100 / 10)
 8     aa.append(a % 1000 / 100)
 9     aa.append(a / 1000)
10 
11     for i in range(4):
12         aa[i] += 5
13         aa[i] %= 10
14     for i in range(2):
15         aa[i], aa[3 - i] = aa[3 - i], aa[i]
16     for i in range(3, -1, -1):
17         stdout.write(str(aa[i]))
View Code

以上实例输出结果为:

1 输入四个数字:
2 1234
3 98.47.346.234
View Code

90:题目:列表使用实例。

程序分析:无。

程序源代码:

 1 # list
 2 # 新建列表
 3 testList = [10086, '中国移动', [1, 2, 4, 5]]
 4 
 5 # 访问列表长度
 6 print(len(testList))
 7 
 8 # 到列表结尾
 9 print(testList[1:])
10 
11 # 向列表添加元素
12 testList.append('i\'m new here!')
13 
14 print(len(testList))
15 
16 print(testList[-1])
17 
18 # 弹出列表的最后一个元素
19 print(testList.pop(1))
20 
21 print(len(testList))
22 
23 print(testList)
24 
25 # list comprehension
26 # 后面有介绍,暂时掠过
27 matrix = [[1, 2, 3],
28           [4, 5, 6],
29           [7, 8, 9]]
30 print(matrix)
31 
32 print(matrix[1])
33 
34 col2 = [row[1] for row in matrix]  # get a  column from a matrix
35 print(col2)
36 
37 col2even = [row[1] for row in matrix if row[1] % 2 == 0]  # filter odd item
38 print(col2even)
View Code

以上实例输出结果为:

 1 3
 2 ['中国移动', [1, 2, 4, 5]]
 3 4
 4 i'm new here!
 5 中国移动
 6 3
 7 [10086, [1, 2, 4, 5], "i'm new here!"]
 8 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 9 [4, 5, 6]
10 [2, 5, 8]
11 [2, 8]
View Code

91:题目:时间函数举例1。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     import time
3     print (time.ctime(time.time()))
4     print (time.asctime(time.localtime(time.time())))
5     print (time.asctime(time.gmtime(time.time())))
View Code

以上实例输出结果为:

1 Sat Mar 23 19:37:22 2019
2 Sat Mar 23 19:37:22 2019
3 Sat Mar 23 11:37:22 2019
View Code

92:题目:时间函数举例2。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     import time
3 
4     start = time.time()
5     for i in range(3000):
6         print(i)
7     end = time.time()
8 
9     print(end - start)
View Code

以上实例输出结果为:

 1 0
 2 1
 3 2
 4  5  6  7 2997
 8 2998
 9 2999
10 0.02006244659423828
View Code

93:题目:时间函数举例3。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     import time
3 
4     start = time.time()
5     for i in range(10000):
6         print(i)
7     end = time.time()
8     print('different is %6.3f' % (end - start))
View Code

以上实例输出结果为:

 1 0
 2 1
 3 2
 4 3
 5  6  7  8 9996
 9 9997
10 9998
11 9999
12 different is  0.059
View Code

94:题目:时间函数举例4,一个猜数游戏,判断一个人反应快慢。

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     import time
 3     import random
 4 
 5     play_it = input('do you want to play it.(\'y\' or \'n\')')
 6     while play_it == 'y':
 7         c = input('input a character:\n')
 8         i = random.randint(0, 2 ** 32) % 100
 9         print('please input number you guess:')
10         start = time.time()
11         a = time.time()
12         guess = int(input('input your guess:'))
13         while guess != i:
14             if guess > i:
15                 print('please input a little smaller')
16 
17                 guess = int(input('input your guess:'))
18             else:
19                 print('please input a little bigger')
20 
21                 guess = int(input('input your guess:'))
22         end = time.time()
23         b = time.time()
24         var = (end - start) / 18.2
25         print(var)
26 
27         # print 'It took you %6.3 seconds' % time.difftime(b,a))
28 
29         if var < 15:
30             print('you are very clever!')
31         elif var < 25:
32             print('you are normal!')
33 
34         else:
35             print('you are stupid!')
36 
37         print('Congradulations')
38 
39         print('The number you guess is %d' % i)
40 
41         play_it = input('do you want to play it.')
View Code

95:题目:字符串日期转换为易读的日期格式。

程序分析:无。

程序源代码:

1 from dateutil import parser
2 dt = parser.parse("Aug 28 2015 12:00AM")
3 print (dt)
View Code

96:题目:计算字符串中子串出现的次数。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     str1 = input('请输入一个字符串:')
3     str2 = input('请输入一个子字符串:')
4     ncount = str1.count(str2)
5     print(ncount)
View Code

以上实例输出结果为:

1 请输入一个字符串:qwery gdfdaabbbcccabc
2 请输入一个子字符串:a
3 3
View Code

97:题目:从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     filename = input('输入文件名:')
3     fp = open(filename,"w")
4     ch = input('输入字符串:')
5     while ch != '#':
6         fp.write(ch)
7         print(ch)
8         ch = input('')
9     fp.close()
View Code

98:题目:从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存。

程序分析:无。

程序源代码:

1 if __name__ == '__main__':
2     fp = open('test.txt','w')
3     string = input('please input a string:\n')
4     string = string.upper()
5     fp.write(string)
6     fp = open('test.txt','r')
7     print (fp.read())
8     fp.close()
View Code

99:题目:有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中。

程序分析:无。

程序源代码:

 1 if __name__ == '__main__':
 2     import string
 3 
 4     fp = open('text1.txt')
 5     a = fp.read()
 6     fp.close()
 7 
 8     fp = open('text2.txt')
 9     b = fp.read()
10     fp.close()
11 
12     fp = open('text3.txt', 'w')
13     l = list(a + b)
14     l.sort()
15     s = ''
16     s = s.join(l)
17     fp.write(s)
18     fp.close()
View Code

100:题目:列表转换为字典。

程序分析:无。

程序源代码:

1 i = ['a', 'b']
2 l = [1, 2]
3 print(dict([i, l]))
View Code

以上实例输出结果为:

1 {'a': 'b', 1: 2}
View Code

 

 

 

 

 

 

 

 

 

 

 

 

 



 

 

 



posted @ 2019-03-23 11:32  佛祖让我来巡山  阅读(27531)  评论(6编辑  收藏  举报

佛祖让我来巡山博客站 - 创建于 2018-08-15

开发工程师个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

Bootstrap中文网