Python small exercises-basic structure and function control statements

Learning example:

Example 1: Draw the Olympic rings
import turtle
turtle.showturtle()
turtle.width(10)

turtle.penup()
turtle.goto(-70,0)
turtle.pendown()
turtle.color("blue")
turtle.circle(40)

turtle.penup()
turtle.goto(-10,0)
turtle.pendown()
turtle.color("black")
turtle.circle(40)

turtle.penup()
turtle.goto(50,0)
turtle.pendown()
turtle.color("red")
turtle.circle(40)

turtle.penup()
turtle.goto(-45,-60)
turtle.pendown()
turtle.color("yellow")
turtle.circle(40)

turtle.penup()
turtle.goto(20,-60)
turtle.pendown()
turtle.color("green")
turtle.circle(40)

Insert picture description here

Example 2: Define multi-point coordinates _ draw a polyline _ and calculate the distance between the start point and the end point
import turtle
import math

x1,y1 = 0,73
x2,y2 = 40,-40
x3,y3 = 10,14
x4,y4 = -83,-34
x5,y5 = 0,0

turtle.width(5)
turtle.goto(x1,y1)
turtle.goto(x2,y2)
turtle.goto(x3,y3)
turtle.goto(x4,y4)
turtle.goto(x5,y5)

distance = math.sqrt((x2-x4)**2+(y2-y4)**2)
turtle.write(distance)

Insert picture description here

Example 3: List control
  1. Output the "to be or not to be" string in reverse order
  2. Output all s in the "sxtsxtsxtsxtsxt" string
    Insert picture description here
Example 4: Preparation of control statements
print("请输入一个学生的成绩:")

score = int(input())
mark = ""

if score < 60:
    mark = "不及格"
elif score < 80:
    mark = "及格"
elif score < 90:
    mark = "良好"
else:
    mark = "优秀"

print("该学会的成绩是:",score,"评价为:",mark)

print("该学会的成绩是:{0},其评价为:{1}".format(score,mark))

print("该学会的成绩是:{grade},其评价为:{part}".format(grade = score,part = mark))

Insert picture description here

Example 5: Quadrant judgment
print("请输入x的值:")
x = int(input())
print("请输入y的值:")
y = int(input())

point = ""

if x>0 and y>0:
    point = "第一象限"
elif x<0 and y>0:
    point = "第二象限"
elif x<0 and y<0:
    point = "第三象限"
else:
    point = "第四象限"

print("x = {0},y = {1},位于的象限是{2}".format(x,y,point))

Insert picture description here
improve:

score = int(input(" " 请输入一个在 0 0-100 之间的数字:" "))
degree = "ABCDE"
num = 0
f if score>100 r or score<0:
score = int(input(" " 输入错误!请重新输入一个在 0 0-100 之间的数字:" "))
else:
num = score//10
f if num<6:num=5
print(" " 分数是 {0}, 等级是 {1}".format(score,degree[9-num])
Example 6: Draw concentric circles
import turtle
color = ["blue","white","red","pink","green","purple","yellow","brown"]

i = turtle.Pen()
i.speed(15)
i.width(5)

for c in range(100):
    i.penup()
    i.goto(0,-10*c)
    i.pendown()
    i.color(color[c%len(color)])
    i.circle(0+10*c)

turtle.done()

Insert picture description here
Example 7: Draw a chessboard 18*18

import turtle

pen = turtle.Pen()
pen.speed(10)

for row in range(18):
    pen.penup()
    pen.goto(0,170-row*10)
    pen.pendown()
    pen.goto(170,170-row*10)

for column in range(18):
    pen.penup()
    pen.goto(column*10,170)
    pen.pendown()
    pen.goto(column*10,0)

turtle.done()

Insert picture description here

Example 8: Efficiency test of local variables and global variables
import math
import time

def test01():
    start = time.time()
    for i in range(100000000):
        math.sqrt(30)
    end = time.time()
    print("耗时{0}".format(end-start))

def test02():
    b = math.sqrt
    start = time.time()
    for i in range(100000000):
        b(30)
    end = time.time()
    print("耗时{0}".format(end-start))

test01()
test02()

Insert picture description here

Example 9: Shallow copy and deep copy
#测试浅拷贝和深拷贝
t import copy
f def testCopy():
'''测试浅拷贝'''
a = [10, 20, [5, 6]]
b = copy.copy(a)
print( "a", a)
print( "b", b)
b.append(30)
b[2].append(7)
print(" " 浅拷贝 ......")
print( "a", a)
print( "b", b)

f def testDeepCopy():
'''测试深拷贝'''
a = [10, 20, [5, 6]]
b = copy.deepcopy(a)
print( "a", a)
print( "b", b)
b.append(30)
b[2].append(7)
print(" " 深拷贝 ......")
print( "a", a)
print( "b", b)
testCopy()
print( "*************")
testDeepCopy()

result:

运行结果:
a [10, 20, [5, 6]]
b [10, 20, [5, 6]]
浅拷贝......
a [10, 20, [5, 6, 7]]
b [10, 20, [5, 6, 7], 30]
*************

a [10, 20, [5, 6]]
b [10, 20, [5, 6]]
深拷贝......
a [10, 20, [5, 6]]
b [10, 20, [5, 6, 7], 30]
Schematic diagram
    1. Shallow copy
      Insert picture description here
    1. Deep copy
      Insert picture description here
Example 10: Passing an immutable object contains a mutable child object
a = (10,20,[5,6])
print("a:",id(a))

def test(m):
    print("m:",id(m))
    m[0] = 100		#会报错,因为元组是不可以改变的
    print(m)

test(a)
print(a)

Insert picture description here

a = (10,20,[5,6])
print("a:",id(a))

def test(m):
    print("m:",id(m))
    m[2][0] = 500		#不回报错
    print(m)

test(a)
print(a)

Insert picture description here

Schematic diagram

Insert picture description here

Example 11: lambda expression and anonymous function (function is also an object)
f = lambda a,b,c,d:a*b+c*d
ff = [lambda Clichong:Clichong*2,lambda Text:Text*Text ]

def p(a,b,c):
    return a*b*c

hh = [p,p]
qq = [ff,hh,f]

print("qq[0][1](9):",qq[0][1](9),"qq[0][0](9)",qq[0][0](9))
print("qq[1][0]:",qq[1][0](2,3,4),"qq[1][0]:",qq[1][1](3,4,5))
print("qq[2]:",qq[2](1,2,3,4))

Insert picture description here

Example 12: Testing of nonlocal and global keywords
#测试nonlocal关键字的用法

def outer():
    b = 10

    def inner():
        nonlocal b
        print("inner:",b)
        b = 20

    inner()

outer()

#测试全局变量的用法
gl = 100

def outer1():
    global gl
    gl = 1
    print("gl:",gl)

    def inner1():
        print("gl+100:",gl+100)
    inner1()

print(gl)
outer1()

Insert picture description here

Homework exercises:

Exercise 1: Define a function to output an integer in response. For example: input 3245, output 5432.
def mathmethod(a):
    print("翻转后的结果",end = ':')
    b = str(a)[::-1]
    print(b)

p = int(input("输入一个数字:"))
mathmethod(p)

Insert picture description here

Exercise 2: Write a function to calculate the following sequence

Insert picture description here

def mathfuncion(n):
    if n == 1:
        return 1/2
    else:
        return n/(n+1)+mathfuncion(n-1)

a = int(input("请输入一个数字:"))
print(mathfuncion(a))

Insert picture description here

Exercise 3: Enter the coordinates of the three vertices of the triangle. If valid, calculate the area of ​​the triangle; if the coordinates are invalid, a prompt will be given.
import math

x = [0,0,0]
y = [0,0,0]

for i in range(3):
    x[i] = int(input("输入第{0}点的x坐标:".format(i+1)))
    y[i] = int(input("输入第{0}点的y坐标:".format(i+1)))

print("三点坐标为:({0},{1})、({2},{3})、({4},{5})".format(x[0],y[0],x[1],y[1],x[2],y[2]))

p1 = (x[0],y[0])
p2 = (x[1],y[1])
p3 = (x[2],y[2])

def getsquare(a,b,c):
    if (a[0] == b[0] == c[0]) or (a[1] == b[1] == c[1]):
        print("此三点不构成三角形")
    else:

        def getland(t1,t2):
            return math.sqrt((t1[0]-t2[0])**2+(t1[1]-t2[1])**2)

        l1 = getland(p1,p2)
        l2 = getland(p2,p3)
        l3 = getland(p1,p3)
        l = (l1+l2+l3)/2
        sq = math.sqrt(l*(l-l1)*(l-l2)*(l-l3))
        print("三边长分别为:{0}、{1}、{2}".format(l1,l2,l3))
        print("面积为:{0}".format(sq))

getsquare(p1,p2,p3)

Insert picture description here

Exercise 4: Enter a number of milliseconds and convert the number to hours, minutes, and seconds.
import time
start = int(time.time())

sec = int(start/1000)
min = int(sec/60)
hou = int(min/24)
print("hour:{0},minute:{1},second:{2}".format(hou,min,sec))

Insert picture description here

Exercise 5: Use turtle drawing. Enter multiple points and connect them in pairs.
import turtle

pen = turtle.Pen()

for i in range(4):
    x1 = int(input("x1:"))
    y1 = int(input("y1:"))
    x2 = int(input("x2:"))
    y2 = int(input("y2:"))

    pen.penup()
    pen.goto(x1,y1)
    pen.pendown()
    pen.goto(x2,y2)

turtle.done()

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44751294/article/details/109384200