美文网首页
初学python的各种例子

初学python的各种例子

作者: crabor | 来源:发表于2018-02-23 17:36 被阅读0次
    # 显示星期数
    
    def Convert(i):
        strWeek = "MonTueWedThuFriSatSun"
        j = (i-1)*3
        strDay = strWeek[j: j+3]
        return strDay
    
    
    def main():
        i = int(input("请输入1-7中的某个数字: "))
        strDay = Convert(i)
        print("对应的星期数为:",strDay)
    
    
    main()
    
    #九九乘法表
    
    for i in range(1,10):
        for j in range(1,i+1):
            print("%d*%d=%d "%(j,i,i*j),end="")
        print()
    
    #求一元二次方程的实数根
    import math
    
    def FindRoot(a,b,c):
        x1=0
        x2=0
        numOfRoots=0
        if a==0:
            #print("这不是一元二次方程")
            numOfRoots=-1
        else:
            delta=b**2-4*a*c
            if delta<0:
                #print("方程无实根")
                numOfRoots=0
            elif delta==0:
                numOfRoots=1
                x1=x2=-b/(2*a)
                #print("root1=root2=",root1)
            else:
                numOfRoots=2
                x1=(-b+math.sqrt(delta))/(2*a)
                x2=(-b-math.sqrt(delta))/(2*a)
                #print("root1=%g,root2=%g"%(root1,root2))
        return x1,x2,numOfRoots
    
    def main():
        a=eval(input("请输入系数a:"))
        b=eval(input("请输入系数b:"))
        c=eval(input("请输入系数c:"))
        x1,x2,numOfRoots=FindRoot(a,b,c)
        if numOfRoots==-1:
            print("这不是一元二次方程")
        elif numOfRoots==0:
            print("方程无实根")
        elif numOfRoots==1:
            print("x1=x2=",x1)
        else:
            print("x1=%g,x2=%g"%(x1,x2))
    
    main()
    
    #整型列表随机化
    import random
    
    array=[]
    for i in range(20):
        array.append(random.randint(0,15))
    print("随机化整型列表:",array)
    if 1 in array:
        print("列表中有%d个1"%array.count(1))
    
    #找出列表中的最大值
    import random
    
    array=[]
    for i in range(20):
        array.append(random.randint(0,100))
    print(array)
    maxItem=array[0]
    for item in array:
        if item >=maxItem:
            maxItem=item
    print("列表中的最大值是",maxItem)
    
    #冒泡排序法
    
    import random
    M=20
    array=[]
    for i in range(M):
        array.append(random.randint(0,100))
    print(array)
    for i in range(M-1):
        for j in range(M-1-i):
            if array[j]>array[j+1]:
                t=array[j]
                array[j]=array[j+1]
                array[j+1]=t
    print(array)
    
    #选择排序法
    
    import random
    
    M=20
    array=[]
    for i in range(M):
        array.append(random.randint(0,100))
    print(array)
    for i in range(M-1):
        index=0
        for j in range(M-i):
            if array[j]>array[index]:
                index=j
            t=array[index]
            array[index]=array[M-1-i]
            array[M-1-i]=t
    print(array)
    
    
    #斐波那契数列
    
    def Fibonacci(i):
        if i<=1:
            return 1
        else:
            return Fibonacci(i-1)+Fibonacci(i-2)
    
    array=[1,1]
    for i in range(2,40):
        print(i)
        #array.append(Fibonacci(i))
        array.append(array[i-1]+array[i-2])
    print(array)
    
    
    #求π.py
    
    from random import random
    from math import sqrt
    from time import clock
    dots=99999
    hits=0
    clock()
    for i in range(1,dots):
        #print(i)
        x,y=random(),random()
        distense=sqrt(x**2+y**2)
        if distense<=1:
            hits+=1
    pi=4*hits/dots
    print("pi的大小为",pi)
    
    #画python
    import turtle
    
    def drawSnake(rad,angle,len,neckrad):
        for i in range(len):
            turtle.circle(rad,angle)
            turtle.circle(-rad,angle)
        turtle.circle(rad,angle/2)
        turtle.fd(rad)
        turtle.circle(neckrad+1,180)
        ttrutle.fd(rad*2/3)
    
    def main():
        turtle.setup(1300,800,100,0)
        pythonsize=15
        turtle.pensize(pythonsize)
        turtle.pencolor("#3B9909")
        turtle.seth(-40)
        drawSnake(40,80,5,pythonsize/2)
    
    main()
    
    #字符串反转
    
    def reverse(str):
        if len(str)==1:
            return str
        else:
            return reverse(str[1:])+str[0]
    
    def main():
        str=input("请输入一个字符串:")
        print("反转后的字符串:"+reverse(str))
    
    main()
    
    
    # drawtree.py
    
    from turtle import Turtle, mainloop
    import time
    
    def tree(plist, l, a, f):
        """ plist is list of pens
        l is length of branch
        a is half of the angle between 2 branches
        f is factor by which branch is shortened
        from level to level."""
        if l > 5: #
            lst = []
            for p in plist:
                p.forward(l)#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed.
                q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
                p.left(a) #Turn turtle left by angle units
                q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
                lst.append(p)#将元素增加到列表的最后
                lst.append(q)
            tree(lst, l*f, a, f)
    
    def main():
        p = Turtle()
        p.color("green")
        p.pensize(5)
        #p.setundobuffer(None)
        p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
        #because hiding the turtle speeds up the drawing observably.
        #p.speed(10)
        #p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
        p.speed(10)
        #TurtleScreen methods can then be called for that object.
        p.left(90)# Turn turtle left by angle units. direction 调整画笔
    
        p.penup() #Pull the pen up – no drawing when moving.
        p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
        p.pendown()# Pull the pen down – drawing when moving. 这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
        #否则turtle一移动就会自动的把线画出来
    
        #t = tree([p], 200, 65, 0.6375)
        t = tree([p], 200, 65, 0.6375)
    
    main()
    time.sleep(10)
    
    #文件拷贝
    
    def CopyFile():
        file1=input("请输入需要被拷贝的文件名:")
        file2=input("请输入拷贝后的文件名:")
    
        inFile=open(file1,"r")
        outFile=open(file2,"w")
    
        countLines=countChars=0
    
        for line in inFile:
            countLines+=1
            countChars+=len(line)
            outFile.write(line)
        print(countLines,"lines and",countChars,"chars copied!")
    
        inFile.close()
        outFile.close()
    
    CopyFile()
    
    #计算器
    
    i=eval(input("请输入式子:"))
    print("结果为:",i)
    
    
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:初学python的各种例子

          本文链接:https://www.haomeiwen.com/subject/pjwxxftx.html