第八章实例
实例01 创建计算BMI指数的模块
def fun_bmi(person,height,weight): """功能:根据身高和体重计算BMI指数 person:姓名 height:身高(米) weight:体重(千克) """ print(person+"的身高:"+str(height)+"米\t体重:"+str(weight)+"千克") bmi=weight/(height*height) print(person+"的BMI指数为:"+str(bmi)) if bmi<18.5: print("您的体重过轻~—~") if bmi>=18.5 and bmi<24.9: print("正常范围,继续保持ovo") if bmi>=24.9 and bmi<29.9: print("您的体重过重~—~") if bmi>=29.9: print("肥胖~—~")
运行结果:
实例02 导入两个包括同名函数的模块
def girth(width,height): """功能:计算周长 参数:width(宽度)、height(高) """ return (width+height)*2 def area(width,height): """功能:计算面积 参数:width(宽度)、height(高) """ return width*height if __name__=='__main__': print(area(10,20))
import math PI=math.pi def girth(r): """功能:计算周长 参数:r(半径) """ return round(2*PI*r,2) def area(r): """功能:计算面积 参数:r(半径) """ return round(PI*r*r,2) if __name__=='__main__': print(girth(10))
import rectangle as r import circular as c if __name__=='__main__': print("圆形的周长为:",c.girth(10)) print("矩形的周长为:",r.girth(10,20))
运行结果:
实例03 在指定包中创建通用的设置和获取尺寸的模块
_wodth=800 #定义保护类型的全局变量(宽度) _height=600 #(高度) def change(w,h): global _width #全局变量(宽度) _width=w global _height #全局变量(高度) _height=h def getWidth(): global _width return _width def getHeight(): global _height return _height
from settings.size import* if __name__=='__main__': change(1024,768) print("宽度:",getWidth()) print("高度:",getHeight())
运行结果:
实例04 生成由数字、字母组成的4位验证码
import random if __name__=='__main__': checkcode="" #保存验证码的变量 for i in range(4): #循环四次 index = random.randrange(0,4) if index != i and index+1 != i: checkcode +=chr(random.randint(97,122)) elif index +1 == i: checkcode += chr(random.randint(65,90)) else: checkcode += str(random.randint(1,9)) print("验证码:",checkcode)
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通