99个Python脚本实用实例

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

#!/usr/bin/python# -*- coding: UTF-8 -*-for i in range(1,5):    for j in range(1,5):        for k in range(1,5):            if( i != k ) and (i != j) and (j != k):                print (i,j,k)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-for i in range(1,85):    if 168 % i == 0:        j = 168 / i;        if i > j and (i + j) % 2 == 0 and (i - j) % 2 == 0 :            m = (i + j) / 2n = (i - j) / 2x = n * n - 100print(x)

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

#!/usr/bin/python3year = int(input('year:\n'))month = int(input('month:\n'))day = int(input('day:\n'))months = (0,31,59,90,120,151,181,212,243,273,304,334)if 0 < month <= 12:    sum = months[month - 1]else:    print ('data error')sum += dayleap = 0if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):    leap = 1if (leap == 1) and (month > 2):    sum += 1print ('it is the %dth day.' % sum)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-l = []for i in range(3):    x = int(raw_input('integer:\n'))l.append(x)l.sort()print l

**题目:斐波那契数列。**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-def fib(n):    a,b = 1,1for i in range(n-1):        a,b = b,a+breturn a# 输出了第10个斐波那契数列print (fib(10))

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

#!/usr/bin/python# -*- coding: UTF-8 -*-a = [1, 2, 3]b = a[:]print (b)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-for i in range(1, 10):    printfor j in range(1, i+1):        print "%d*%d=%d" % (i, j, i*j),

**题目:暂停一秒输出。**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-import timemyD = {1: 'a', 2: 'b'}for key, value in dict.items(myD):    print (key, value)time.sleep(1) # 暂停 1 秒

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

#!/usr/bin/python# -*- coding: UTF-8 -*-import timeprint (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))# 暂停一秒time.sleep(1)print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))

**题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-f1 = 1f2 = 1for i in range(1,22):    print '%12ld %12ld' % (f1,f2),    if (i % 3) == 0:        print ''f1 = f1 + f2f2 = f1 + f2

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

#!/usr/bin/python# -*- coding: UTF-8 -*-h = 0leap = 1from math import sqrtfrom sys import stdoutfor m in range(101,201):    k = int(sqrt(m + 1))for i in range(2,k + 1):        if m % i == 0:            leap = 0breakif leap == 1:        print ('%-4d' % m)h += 1if h % 10 == 0:            print ('')leap = 1print ('The total is %d' % h)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-for n in range(100,1000):    i = n / 100j = n / 10 % 10k = n % 10if n == i ** 3 + j ** 3 + k ** 3:        print n

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

#!/usr/bin/python# -*- coding: UTF-8 -*-def reduceNum(n):    print '{} = '.format(n),    if not isinstance(n, int) or n <= 0 :        print '请输入一个正确的数字 !'exit(0)elif n in [1] :        print '{}'.format(n)while n not in [1] : # 循环保证递归for index in xrange(2, n + 1) :            if n % index == 0:                n /= index # n 等于 n/indexif n == 1:                     print indexelse : # index 一定是素数print '{} *'.format(index),                breakreduceNum(90)reduceNum(100)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-score = int(raw_input('输入分数:\n'))if score >= 90:    grade = 'A'elif score >= 60:    grade = 'B'else:    grade = 'C'print '%d 属于 %s' % (score,grade)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-import datetimeif __name__ == '__main__':# 输出今日日期,格式为 dd/mm/yyyy。更多选项可以查看 strftime() 方法print(datetime.date.today().strftime('%d/%m/%Y'))# 创建日期对象miyazakiBirthDate = datetime.date(1941, 1, 5)print(miyazakiBirthDate.strftime('%d/%m/%Y'))# 日期算术运算miyazakiBirthNextDay = miyazakiBirthDate + datetime.timedelta(days=1)print(miyazakiBirthNextDay.strftime('%d/%m/%Y'))# 日期替换miyazakiFirstBirthday = miyazakiBirthDate.replace(year=miyazakiBirthDate.year + 1)print(miyazakiFirstBirthday.strftime('%d/%m/%Y'))

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

#!/usr/bin/python# -*- coding: UTF-8 -*-import strings = raw_input('请输入一个字符串:\n')letters = 0space = 0digit = 0others = 0i=0while i < len(s):    c = s[i]i += 1if c.isalpha():        letters += 1elif c.isspace():        space += 1elif c.isdigit():        digit += 1else:        others += 1print 'char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-Tn = 0Sn = []n = int(raw_input('n = '))a = int(raw_input('a = '))for count in range(n):    Tn = Tn + aa = a * 10Sn.append(Tn)print TnSn = reduce(lambda x,y : x + y,Sn)print "计算和为:",Sn

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

#!/usr/bin/python# -*- coding: UTF-8 -*-from sys import stdoutfor j in range(2,1001):    k = []n = -1s = jfor i in range(1,j):            if j % i == 0:                n += 1s -= ik.append(i)if s == 0:        print (j)for i in range(n):            stdout.write(str(k[i]))stdout.write(' ')print (k[n])

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

#!/usr/bin/python# -*- coding: UTF-8 -*-tour = []height = []hei = 100.0 # 起始高度tim = 10 # 次数for i in range(1, tim + 1):    # 从第二次开始,落地时的距离应该是反弹高度乘以2(弹到最高点再落下)if i == 1:        tour.append(hei)else:        tour.append(2*hei)hei /= 2height.append(hei)print('总高度:tour = {0}'.format(sum(tour)))print('第10次反弹高度:height = {0}'.format(height[-1]))

题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。

#!/usr/bin/python# -*- coding: UTF-8 -*-x2 = 1for day in range(9,0,-1):    x1 = (x2 + 1) * 2x2 = x1print (x1)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-for i in range(ord('x'),ord('z') + 1):    for j in range(ord('x'),ord('z') + 1):        if i != j:            for k in range(ord('x'),ord('z') + 1):                if (i != k) and (j != k):                    if (i != ord('x')) and (k != ord('x')) and (k != ord('z')):                        print ('order is a -- %s\t b -- %s\tc--%s' % (chr(i),chr(j),chr(k)))

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

#!/usr/bin/python# -*- coding: UTF-8 -*-from sys import stdoutfor i in range(4):    for j in range(2 - i + 1):        stdout.write(' ')for k in range(2 * i + 1):        stdout.write('*')print('')for i in range(3):    for j in range(i + 1):        stdout.write(' ')for k in range(4 - 2 * i + 1):        stdout.write('*')print('')

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

#!/usr/bin/python# -*- coding: UTF-8 -*-a = 2.0b = 1.0s = 0for n in range(1,21):    s += a / bt = aa = a + bb = tprint (s)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-n = 0s = 0t = 1for n in range(1,21):    t *= ns += tprint ('1! + 2! + 3! + ... + 20! = %d' % s)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-def fact(j):    sum = 0if j == 0:        sum = 1else:        sum = j * fact(j - 1)return sumprint (fact(5))

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

#!/usr/bin/python# -*- coding: UTF-8 -*-def output(s,l):    if l==0:       returnprint (s[l-1])output(s,l-1)s = raw_input('Input a string:')l = len(s)output(s,l)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-def age(n):    if n == 1: c = 10else: c = age(n - 1) + 2return cprint (age(5))

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

#!/usr/bin/python# -*- coding: UTF-8 -*-x = int(raw_input("请输入一个数:\n"))a = x / 10000b = x % 10000 / 1000c = x % 1000 / 100d = x % 100 / 10e = x % 10if a != 0:    print "5 位数:",e,d,c,b,aelif b != 0:    print "4 位数:",e,d,c,b,elif c != 0:    print "3 位数:",e,d,celif d != 0:    print "2 位数:",e,delse:    print "1 位数:",e

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

#!/usr/bin/python# -*- coding: UTF-8 -*-a = int(raw_input("请输入一个数字:\n"))x = str(a)flag = Truefor i in range(len(x)/2):    if x[i] != x[-i - 1]:        flag = Falsebreakif flag:    print "%d 是一个回文数!" % aelse:    print "%d 不是一个回文数!" % a

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

#!/usr/bin/python# -*- coding: UTF-8 -*-letter = raw_input("please input:")#while letter  != 'Y':if letter == 'S':    print ('please input second letter:')letter = raw_input("please input:")if letter == 'a':        print ('Saturday')elif letter  == 'u':        print ('Sunday')else:        print ('data error')elif letter == 'F':    print ('Friday')elif letter == 'M':    print ('Monday')elif letter == 'T':    print ('please input second letter')letter = raw_input("please input:")if letter  == 'u':        print ('Tuesday')elif letter  == 'h':        print ('Thursday')else:        print ('data error')elif letter == 'W':    print ('Wednesday')else:    print ('data error')

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

#!/usr/bin/python# -*- coding: UTF-8 -*-a = ['one', 'two', 'three']for i in a[::-1]:    print (i)

题目:按逗号分隔列表。

#!/usr/bin/python# -*- coding: UTF-8 -*-L = [1,2,3,4,5]s1 = ','.join(str(n) for n in L)print (s1)

题目:练习函数调用。

#!/usr/bin/python# -*- coding: UTF-8 -*-def hello_runoob():    print ('RUNOOB')def hello_runoobs():    for i in range(3):        hello_runoob()if __name__ == '__main__':    hello_runoobs()

题目:文本颜色设置。

#!/usr/bin/python# -*- coding: UTF-8 -*-class bcolors:    HEADER = '\033[95m'OKBLUE = '\033[94m'OKGREEN = '\033[92m'WARNING = '\033[93m'FAIL = '\033[91m'ENDC = '\033[0m'BOLD = '\033[1m'UNDERLINE = '\033[4m'print (bcolors.WARNING + "警告的颜色字体?" + bcolors.ENDC)

题目:求100之内的素数。

#!/usr/bin/python# -*- coding: UTF-8 -*-# 输出指定范围内的素数# 用户输入数据lower = int(input("输入区间最小值: "))upper = int(input("输入区间最大值: "))for num in range(lower,upper + 1):    # 素数大于 1if num > 1:        for i in range(2,num):            if (num % i) == 0:                breakelse:            print(num)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == "__main__":    N = 10# input dataprint ('请输入10个数字:\n')l = []for i in range(N):        l.append(int(input('输入一个数字:\n')))printfor i in range(N):        print (l[i])print# 排列10个数字for i in range(N - 1):        min = ifor j in range(i + 1,N):            if l[min] > l[j]:min = jl[i],l[min] = l[min],l[i]print ('排列之后:')for i in range(N):        print (l[i])

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    a = []sum = 0.0for i in range(3):        a.append([])for j in range(3):            a[i].append(float(input("input num:\n")))for i in range(3):        sum += a[i][i]print (sum)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    # 方法一 :0 作为加入数字的占位符a = [1,4,6,9,13,16,19,28,40,100,0]print ('原始列表:')for i in range(len(a)):        print (a[i])number = int(input("\n插入一个数字:\n"))end = a[9]if number > end:        a[10] = numberelse:        for i in range(10):            if a[i] > number:                temp1 = a[i]a[i] = numberfor j in range(i + 1,11):                    temp2 = a[j]a[j] = temp1temp1 = temp2breakprint ('排序后列表:')for i in range(11):        print (a[i])

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    a = [9,6,5,4,1]N = len(a)print (a)for i in range(len(a) // 2):        a[i],a[N - i - 1] = a[N - i - 1],a[i]print (a)

题目:统计 1 到 100 之和。

#!/usr/bin/python# -*- coding: UTF-8 -*-tmp = 0for i in range(1,101):    tmp += iprint ('The sum is %d' % tmp)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-TRUE = 1FALSE = 0def SQ(x):    return x * xprint ('如果输入的数字小于 50,程序将停止运行。')again = 1while again:    num = int(input('请输入一个数字:'))print ('运算结果为: %d' % (SQ(num)))if SQ(num) >= 50:        again = TRUEelse:        again = FALSE

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

#!/usr/bin/python# -*- coding: UTF-8 -*-MAXIMUM = lambda x,y :  (x > y) * x + (x < y) * yMINIMUM = lambda x,y :  (x > y) * y + (x < y) * xif __name__ == '__main__':    a = 10b = 20print ('The largar one is %d' % MAXIMUM(a,b))print ('The lower one is %d' % MINIMUM(a,b))

题目:输出一个随机数。

#!/usr/bin/python# -*- coding: UTF-8 -*-import random#生成 10 到 20 之间的随机数print (random.uniform(10, 20))

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    a = 0x77b = a & 3print ('a & b = %d' % b)b &= 7print ('a & b = %d' % b)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    a = 0o77b = a | 3print ('a | b is %d' % b)b |= 7print ('a | b is %d' % b)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    a = int(input('input a number:\n'))b = a >> 4c = ~(~0 << 4)d = b & cprint ('%o\t%o' %(a,d))

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    from Tkinter import *     canvas = Canvas(width=800, height=600, bg='yellow')canvas.pack(expand=YES, fill=BOTH)k = 1j = 1for i in range(0,26):        canvas.create_oval(310 - k,250 - k,310 + k,250 + k, width=1)k += jj += 0.3mainloop()

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    from Tkinter import *     canvas = Canvas(width=300, height=300, bg='green')canvas.pack(expand=YES, fill=BOTH)x0 = 263y0 = 263y1 = 275x1 = 275for i in range(19):        canvas.create_line(x0,y0,x0,y1, width=1, fill='red')x0 = x0 - 5y0 = y0 - 5x1 = x1 + 5y1 = y1 + 5x0 = 263y1 = 275y0 = 263for i in range(21):        canvas.create_line(x0,y0,x0,y1,fill = 'red')x0 += 5y0 += 5y1 += 5mainloop()

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    from Tkinter import *    root = Tk()root.title('Canvas')canvas = Canvas(root,width = 400,height = 400,bg = 'yellow')x0 = 263y0 = 263y1 = 275x1 = 275for i in range(19):        canvas.create_rectangle(x0,y0,x1,y1)x0 -= 5y0 -= 5x1 += 5y1 += 5canvas.pack()root.mainloop()

题目:计算字符串长度。

#!/usr/bin/python# -*- coding: UTF-8 -*-sStr1 = 'strlen'print len(sStr1)

题目:打印出杨辉三角形(要求打印出10行如下图)。

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    a = []for i in range(10):        a.append([])for j in range(10):            a[i].append(0)for i in range(10):        a[i][0] = 1a[i][i] = 1for i in range(2,10):        for j in range(1,i):            a[i][j] = a[i - 1][j-1] + a[i - 1][j]from sys import stdoutfor i in range(10):        for j in range(i + 1):            stdout.write(str(a[i][j]))stdout.write(' ')print

题目:画椭圆。

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    from Tkinter import *    x = 360y = 160top = y - 30bottom = y - 30canvas = Canvas(width = 400,height = 600,bg = 'white')for i in range(20):        canvas.create_oval(250 - top,250 - bottom,250 + top,250 + bottom)top -= 5bottom += 5canvas.pack()mainloop()

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    n1 = int(raw_input('n1 = :\n'))n2 = int(raw_input('n2 = :\n'))n3 = int(raw_input('n3 = :\n'))def swap(p1,p2):        return p2,p1if n1 > n2 : n1,n2 = swap(n1,n2)if n1 > n3 : n1,n3 = swap(n1,n3)if n2 > n3 : n2,n3 = swap(n2,n3)print n1,n2,n3

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

#!/usr/bin/python# -*- coding: UTF-8 -*-def inp(numbers):    for i in range(6):        numbers.append(int(raw_input('输入一个数字:\n')))p = 0def arr_max(array):    max = 0for i in range(1,len(array) - 1):        p = iif array[p] > array[max] : max = pk = maxarray[0],array[k] = array[k],array[0]def arr_min(array):    min = 0for i in range(1,len(array) - 1):        p = iif array[p] < array[min] : min = pl = minarray[5],array[l] = array[l],array[5]def outp(numbers):    for i in range(len(numbers)):        print numbers[i]if __name__ == '__main__':    array = []inp(array) # 输入 6 个数字并放入数组arr_max(array) # 获取最大元素并与第一个元素交换arr_min(array) # 获取最小元素并与最后一个元素交换print '计算结果:'outp(array)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    n = int(raw_input('整数 n 为:\n'))m = int(raw_input('向后移 m 个位置为:\n'))def move(array,n,m):        array_end = array[n - 1]for i in range(n - 1,-1,- 1):            array[i] = array[i - 1]array[0] = array_endm -= 1if m > 0:move(array,n,m)number = []for i in range(n):        number.append(int(raw_input('输入一个数字:\n')))print '原始列表:',numbermove(number,n,m)print '移动之后:',number

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    nmax = 50n = int(raw_input('请输入总人数:'))num = []for i in range(n):        num.append(i + 1)i = 0k = 0m = 0while m < n - 1:        if num[i] != 0 : k += 1if k == 3:            num[i] = 0k = 0m += 1i += 1if i == n : i = 0i = 0while num[i] == 0: i += 1print num[i]

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

#!/usr/bin/python# -*- coding: UTF-8 -*-N = 3#stu# num : string# name : string# score[4]: liststudent = []for i in range(5):    student.append(['','',[]])def input_stu(stu):    for i in range(N):        stu[i][0] = raw_input('input student num:\n')stu[i][1] = raw_input('input student name:\n')for j in range(3):            stu[i][2].append(int(raw_input('score:\n')))def output_stu(stu):    for i in range(N):        print '%-6s%-10s' % ( stu[i][0],stu[i][1] )for j in range(3):            print '%-8d' % stu[i][2][j]if __name__ == '__main__':    input_stu(student)print studentoutput_stu(student)

题目:创建一个链表。

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    ptr = []for i in range(5):        num = int(raw_input('please input a number:\n'))ptr.append(num)print ptr

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    ptr = []for i in range(5):        num = int(raw_input('please input a number:\n'))ptr.append(num)print ptrptr.reverse()print ptr

题目:列表排序及连接。

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    a = [1,3,2]b = [3,4,5]a.sort() # 对列表 a 进行排序print a# 连接列表 a 与 bprint a+b# 连接列表 a 与 ba.extend(b)print a

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    for i in range(5):        n = 0if i != 1: n += 1if i == 3: n += 1if i == 4: n += 1if i != 4: n += 1if n == 3: print 64 + i

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

#!/usr/bin/python# -*- coding: UTF-8 -*-def peven(n):    i = 0s = 0.0for i in range(2,n + 1,2):        s += 1.0 / i # Python里,整数除整数,只能得出整数,所以需要使用 浮点数 1.0return sdef podd(n):    s = 0.0for i in range(1, n + 1,2):        s += 1.0 / i # Python里,整数除整数,只能得出整数,所以需要使用 浮点数 1.0return sdef dcall(fp,n):    s = fp(n)return sif __name__ == '__main__':    n = int(raw_input('input a number:\n'))if n % 2 == 0:        sum = dcall(peven,n)else:        sum = dcall(podd,n)print sum

题目:循环输出列表​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*- if __name__ == '__main__':    s = ["man","woman","girl","boy","sister"]for i in range(len(s)):        print s[i]

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    person = {"li":18,"wang":50,"zhang":20,"sun":22}    m = 'li'for key in person.keys():        if person[m] < person[key]:            m = keyprint '%s,%d' % (m,person[m])

**题目:字符串排序。**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    str1 = raw_input('input string:\n')str2 = raw_input('input string:\n')str3 = raw_input('input string:\n')print str1,str2,str3if str1 > str2 : str1,str2 = str2,str1if str1 > str3 : str1,str3 = str3,str1if str2 > str3 : str2,str3 = str3,str2print 'after being sorted.'print str1,str2,str3

**题目:海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    i = 0j = 1x = 0while (i < 5) :        x = 4 * jfor i in range(0,5) :            if(x%4 != 0) :                breakelse :                i += 1x = (x/4) * 5 +1j += 1print x

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

#!/usr/bin/python# -*- coding: UTF-8 -*-a = 809for i in range(10,100):    b = i * aif b >= 1000 and b <= 10000 and 8 * i < 100 and 9 * i >= 100:        print b,' = 800 * ', i, ' + 9 * ', i

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    n = 0p = raw_input('input a octal number:\n')for i in range(len(p)):        n = n * 8 + ord(p[i]) - ord('0')print n

**题目:求0---7所能组成的奇数个数。**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    sum = 4s = 4for j in range(2,9):        print sumif j <= 2:            s *= 7else:            s *= 8sum += sprint 'sum = %d' % sum

**题目:连接字符串。**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-delimiter = ','mylist = ['Brazil', 'Russia', 'India', 'China']print delimiter.join(mylist)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    zi = int(raw_input('输入一个数字:\n'))n1 = 1c9 = 1m9 = 9sum = 9while n1 != 0:        if sum % zi == 0:            n1 = 0else:            m9 *= 10sum += m9c9 += 1print '%d 个 9 可以被 %d 整除 : %d' % (c9,zi,sum)r = sum / ziprint '%d / %d = %d' % (sum,zi,r)

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    a = "acegikm"b = "bdfhjlnpq"# 连接字符串c = a + bprint c

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    n = 1while n <= 7:        a = int(raw_input('input a number:\n'))while a < 1 or a > 50:            a = int(raw_input('input a number:\n'))print a * '*'n += 1

**题目:某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换。**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-from sys import stdoutif __name__ == '__main__':    a = int(raw_input('输入四个数字:\n'))aa = []aa.append(a % 10)aa.append(a % 100 / 10)aa.append(a % 1000 / 100)aa.append(a / 1000)for i in range(4):        aa[i] += 5aa[i] %= 10for i in range(2):        aa[i],aa[3 - i] = aa[3 - i],aa[i]for i in range(3,-1,-1):        stdout.write(str(aa[i]))

**题目:列表使用实例。**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-#list  #新建列表  testList=[10086,'中国移动',[1,2,4,5]]#访问列表长度  print len(testList)#到列表结尾  print testList[1:]#向列表添加元素  testList.append('i\'m new here!')print len(testList)print testList[-1]#弹出列表的最后一个元素  print testList.pop(1)print len(testList)print testList#list comprehension  #后面有介绍,暂时掠过  matrix = [[1, 2, 3],  [4, 5, 6],  [7, 8, 9]]print matrixprint matrix[1]col2 = [row[1] for row in matrix]#get a  column from a matrix  print col2col2even = [row[1] for row in matrix if row[1] % 2 == 0]#filter odd item  print col2even

**题目:时间函数举例2。**​​​​​​​

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    import timestart = time.time()for i in range(3000):        print iend = time.time()print end - start

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    import timeimport randomplay_it = raw_input('do you want to play it.(\'y\' or \'n\')')while play_it == 'y':        c = raw_input('input a character:\n')i = random.randint(0,2**32) % 100print 'please input number you guess:\n'start = time.clock()a = time.time()guess = int(raw_input('input your guess:\n'))while guess != i:            if guess > i:                print 'please input a little smaller'guess = int(raw_input('input your guess:\n'))else:                print 'please input a little bigger'guess = int(raw_input('input your guess:\n'))end = time.clock()b = time.time()var = (end - start) / 18.2print var# print 'It took you %6.3 seconds' % time.difftime(b,a))if var < 15:            print 'you are very clever!'elif var < 25:            print 'you are normal!'else:            print 'you are stupid!'print 'Congradulations'print 'The number you guess is %d' % iplay_it = raw_input('do you want to play it.')

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    str1 = raw_input('请输入一个字符串:\n')str2 = raw_input('请输入一个子字符串:\n')ncount = str1.count(str2)print ncount

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    from sys import stdoutfilename = raw_input('输入文件名:\n')fp = open(filename,"w")ch = raw_input('输入字符串:\n')while ch != '#':        fp.write(ch)stdout.write(ch)ch = raw_input('')fp.close()

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    fp = open('test.txt','w')string = raw_input('please input a string:\n')string = string.upper()fp.write(string)fp = open('test.txt','r')print fp.read()fp.close()

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

#!/usr/bin/python# -*- coding: UTF-8 -*-if __name__ == '__main__':    import stringfp = open('test1.txt')a = fp.read()fp.close()fp = open('test2.txt')b = fp.read()fp.close()fp = open('test3.txt','w')l = list(a + b)l.sort()s = ''s = s.join(l)fp.write(s)fp.close()

题目:列表转换为字典。

#!/usr/bin/python# -*- coding: UTF-8 -*-i = ['a', 'b']l = [1, 2]print dict([i,l])

题目:获取 100 以内的质数。

#!/usr/bin/python# -*- coding: UTF-8 -*-num=[];i=2for i in range(2,100):   j=2for j in range(2,i):      if(i%j==0):         breakelse:      num.append(i)print(num)
相关推荐
梧桐树042936 分钟前
python常用内建模块:collections
python
Dream_Snowar44 分钟前
速通Python 第三节
开发语言·python
XH华1 小时前
初识C语言之二维数组(下)
c语言·算法
南宫生1 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
不想当程序猿_2 小时前
【蓝桥杯每日一题】求和——前缀和
算法·前缀和·蓝桥杯
落魄君子2 小时前
GA-BP分类-遗传算法(Genetic Algorithm)和反向传播算法(Backpropagation)
算法·分类·数据挖掘
菜鸡中的奋斗鸡→挣扎鸡2 小时前
滑动窗口 + 算法复习
数据结构·算法
蓝天星空2 小时前
Python调用open ai接口
人工智能·python
Lenyiin2 小时前
第146场双周赛:统计符合条件长度为3的子数组数目、统计异或值为给定值的路径数目、判断网格图能否被切割成块、唯一中间众数子序列 Ⅰ
c++·算法·leetcode·周赛·lenyiin
jasmine s2 小时前
Pandas
开发语言·python