Python正是(三)三、利用函数实现模块化总结

  目录(二)调用函数(三)函数参数三、利用函数实现模块化总结

  一、函数和模块概述(一)函数概述

  函数可以看成是语句的集合,通过函数调用来执行其包含的语句。函数可以返回一个计算结果,根据每次函数调用的参数,可以返回不同的计算结果。Python利用函数提高代码的重用率,减少了代码冗余。

  执行dir(__builtin__)可以查看Python所有内置对象

  <pre class="brush:py;">
["ArithmeticError",
"AssertionError",
"AttributeError",
"BaseException",
"BlockingIOError",
"BrokenPipeError",
"BufferError",
"BytesWarning",
"ChildProcessError",
"ConnectionAbortedError",
"ConnectionError",
"ConnectionRefusedError",
"ConnectionResetError",
"DeprecationWarning",
"EOFError",
"Ellipsis",
"EnvironmentError",
"Exception",
"False",
"FileExistsError",
"FileNotFoundError",
"FloatingPointError",
"FutureWarning",
"GeneratorExit",
"IOError",
"ImportError",
"ImportWarning",
"IndentationError",
"IndexError",
"InterruptedError",
"IsADirectoryError",
"KeyError",
"KeyboardInterrupt",
"LookupError",
"MemoryError",
"ModuleNotFoundError",
"NameError",
"None",
"NotADirectoryError",
"NotImplemented",
"NotImplementedError",
"OSError",
"OverflowError",
"PendingDeprecationWarning",
"PermissionError",
"ProcessLookupError",
"RecursionError",
"ReferenceError",
"ResourceWarning",
"RuntimeError",
"RuntimeWarning",
"StopAsyncIteration",
"StopIteration",
"SyntaxError",
"SyntaxWarning",
"SystemError",
"SystemExit",
"TabError",
"TimeoutError",
"True",
"TypeError",
"UnboundLocalError",
"UnicodeDecodeError",
"UnicodeEncodeError",
"UnicodeError",
"UnicodeTranslateError",
"UnicodeWarning",
"UserWarning",
"ValueError",
"Warning",
"WindowsError",
"ZeroDivisionError",
"__IPYTHON__",
"__build_class__",
"__debug__",
"__doc__",
"__import__",
"__loader__",
"__name__",
"__package__",
"__spec__",
"abs",
"all",
"any",
"ascii",
"bin",
"bool",
"breakpoint",
"bytearray",
"bytes",
"callable",
"cell_count",
"chr",
"classmethod",
"compile",
"complex",
"copyright",
"credits",
"debugcell",
"debugfile",
"delattr",
"dict",
"dir",
"display",
"divmod",
"enumerate",
"eval",
"exec",
"filter",
"float",
"format",
"frozenset",
"get_ipython",
"getattr",
"globals",
"hasattr",
"hash",
"help",
"hex",
"id",
"input",
"int",
"isinstance",
"issubclass",
"iter",
"len",
"license",
"list",
"locals",
"map",
"max",
"memoryview",
"min",
"next",
"object",
"oct",
"open",
"ord",
"pow",
"print",
"property",
"range",
"repr",
"reversed",
"round",
"runcell",
"runfile",
"set",
"setattr",
"slice",
"sorted",
"staticmethod",
"str",
"sum",
"super",
"tuple",
"type",
"vars",
"zip"]
</pre>

  演示Python内置函数

  在这里插入图片描述

  (二)模块概述

  模块是程序代码和数据的封装。模块中定义的变量、函数或类等可导入到其他文件中使用。Python正是通过模块提供各种功能js key多态赋值,例如,在前面用到的sys、os、math、random等都是模块。

  1、sys模块

  查看sys模块包含的对象(属性和方法)

  在这里插入图片描述

  使用sys模块的path

  在这里插入图片描述

  在这里插入图片描述

  2、os模块

  导入os模块

  在这里插入图片描述

  获取当前工作目录

  在这里插入图片描述

  3、math模块

  在这里插入图片描述

  4、random模块

  在这里插入图片描述

  二、函数(一)定义函数1、语法格式

  def: define

  <pre class="brush:py;">
def 函数名(参数表):

函数体(语句组)
return 返回值
e>

  如果我们定义一个函数,没有写return语句,系统会自动给它添加一个return None

  2、函数类型3、案例演示

  定义无参函数

  在这里插入图片描述

  定义单参函数(调用时可以用位置参数,也可以用键参数)

  在这里插入图片描述

  定义多参函数

  在这里插入图片描述

  说明:定义函数时的参数叫做形式参数(formal paramter),简称形参(虚参);调用函数时的参数叫做实际参数(actual parameter),简称实参。调用函数,就是将实参传递给形参,进行处理之后,得到返回值。

  定义有返回值的函数

  在这里插入图片描述

  (二)调用函数1、简要说明2、案例演示

  编写并调用阶乘函数 - factorial(n)

  在这里插入图片描述

  运行程序,查看结果

  在这里插入图片描述

  (三)函数参数

  在定义函数时,参数表中的各个参数称为形式参数,简称形参。调用函数时,参数表中提供的参数称为实际参数,简称实参。在Python中,变量保存的是对象的引用,类似C/C++中的指针。实参传递给形参就是将对象的引用赋值给形参。

  1、参数的多态性

  js 数组定义和赋值_js key多态赋值_js定义二维数组并赋值

  多态是面向对象的一个特点js key多态赋值,指多一个行为针对不同对象可能会得到不同的结果。Python中的变量无类型属性,变量可引用各种不同类型的对象。同一个函数,传递的实际参数类型不同时,可获得不同的结果,体现了多态性。

  2、参数赋值传递

  通常,函数调用时按参数的先后顺序,将实参传递给形参。例如:调用add(1, 2.5)时,1传递给a,2.5传递给b。Python允许以形参赋值的方式,指定将实参传递给形参。

  三、利用函数实现模块化1、创建多级菜单系统

  编写程序 - 多级菜单系统.py

  <pre class="brush:py;">

-- coding: utf-8 --

"""
功能:多级菜单系统
作者:华卫
日期:2021年1月4日
"""
def add_record():

print("添加记录功能尚待开发")

def query_record():

print("查询记录功能尚待开发")

def modify_record():

print("修改记录功能尚待开发")

def delete_record():

print("删除记录功能尚待开发")

def login():

while True:
    print("主菜单")
    print("=============")
    print("1. 增加记录")
    print("2. 查询记录")
    print("3. 修改记录")
    print("4. 删除记录")
    print("5. 返回上级菜单")
    print("==============")
    mc2 = int(input("输入菜单号:"))
    if mc2 == 1:
        add_record()
    elif mc2 == 2:
        query_record()
    elif mc2 == 3:
        modify_record()
    elif mc2 == 4:
        delete_record()
    else:
        break

while True:

print("============")
print("1. 登录")
print("2. 退出")
print("============")
mc1 = int(input("输入菜单号:"))
if mc1 == 1:
    login()
elif mc1 == 2:
    print("谢谢使用!")
    break
e>

  2、启动程序,查看效果

  在这里插入图片描述

  总结

  篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注云海天教程的更多内容!

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1772
0 评论
487

发表评论

!
在线咨询
在线咨询
以确保在用户需要帮助时能够及时提供解答和技术支持
您好,这里是小灯泡设计,请登录后咨询。