python小练习--基本结构与函数控制语句

简介: python小练习--基本结构与函数控制语句

学习例子:


例子1:画奥运五环图形

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)

image.png


例子2:定义多点坐标_绘出折线_并计算起始点和终点距离

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)

image.png


例子3:列表的控制

  1. 将”to be or not to be”字符串倒序输出
  2. 将”sxtsxtsxtsxtsxt”字符串中所有的 s 输出


image.png

例子4:控制语句的编写

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))

image.png


例子5:象限判断

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))

image.png

改善:

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])


例子6:画同心圆

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()

image.png


例子7:画棋盘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()

image.png


例子8:局部变量和全局变量效率测试

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()

image.png


例子9:浅拷贝与深拷贝

#测试浅拷贝和深拷贝
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()


结果:

运行结果:
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]


原理图

  1. 浅拷贝

image.png

  1. 深拷贝

image.png


例子10:传递不可变对象包含的子对象是可变的情况

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)

image.png

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)

image.png

原理图

image.png


例子11:lambda表达式和匿名函数(函数也是一个对象)

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))

image.png


例子12:nonlocal和global关键字的测试

#测试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()

image.png


作业练习:


练习1:定义一个函数实现反响输出一个整数。比如:输入 3245,输出 5432.

def mathmethod(a):
    print("翻转后的结果",end = ':')
    b = str(a)[::-1]
    print(b)
p = int(input("输入一个数字:"))
mathmethod(p)

image.png


练习2:编写一个函数,计算下面的数列

image.png

def mathfuncion(n):
    if n == 1:
        return 1/2
    else:
        return n/(n+1)+mathfuncion(n-1)
a = int(input("请输入一个数字:"))
print(mathfuncion(a))

image.png


练习3:输入三角形三个顶点的坐标,若有效则计算三角形的面积;如坐标无效,则给出提示。

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)

image.png


练习4:输入一个毫秒数,将该数字换算成小时数,分钟数、秒数。

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))

image.png


练习5:使用海龟绘图。输入多个点,将这些点都两两相连。

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()

image.png


目录
相关文章
|
3月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
239 1
|
3月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
347 1
|
3月前
|
Java 数据处理 索引
(Pandas)Python做数据处理必选框架之一!(二):附带案例分析;刨析DataFrame结构和其属性;学会访问具体元素;判断元素是否存在;元素求和、求标准值、方差、去重、删除、排序...
DataFrame结构 每一列都属于Series类型,不同列之间数据类型可以不一样,但同一列的值类型必须一致。 DataFrame拥有一个总的 idx记录列,该列记录了每一行的索引 在DataFrame中,若列之间的元素个数不匹配,且使用Series填充时,在DataFrame里空值会显示为NaN;当列之间元素个数不匹配,并且不使用Series填充,会报错。在指定了index 属性显示情况下,会按照index的位置进行排序,默认是 [0,1,2,3,...] 从0索引开始正序排序行。
301 0
|
3月前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
202 0
|
4月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
288 101
|
4月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
238 99
|
4月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
208 98
|
4月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
5月前
|
Python
Python 函数定义
Python 函数定义
598 155
|
6月前
|
PHP Python
Python format()函数高级字符串格式化详解
在 Python 中,字符串格式化是一个重要的主题,format() 函数作为一种灵活且强大的字符串格式化方法,被广泛应用。format() 函数不仅能实现基本的插入变量,还支持更多高级的格式化功能,包括数字格式、对齐、填充、日期时间格式、嵌套字段等。 今天我们将深入解析 format() 函数的高级用法,帮助你在实际编程中更高效地处理字符串格式化。
607 0

推荐镜像

更多