python第十四篇------函数(一)

版权声明:未经本人同意不得转载 https://blog.csdn.net/object_oriented_/article/details/86595472

一 . 如何自定义和调用函数 

函数: 封装了功能的代码块, 具有独立的功能, 解决的代码的重用性

1.python中定义函数的格式 

def 函数名():
       函数封装的代码

# 1. def 是英⽂ define 的缩写
# 2. 函数名称最好见名知义
# 3. 符合标识符的命名规则, 不能以数字开头, 不能与关键字重名,可以由字母 下划线 和数字组成

2. 调用函数

可通过  函数名()  即可完成调用函数

注意1  函数只有被调用才会执行,不调用不执行, 函数在执行完成后, 会回到之前的程序中, 继续执行函数后面的代码
注意2 在调用函数前, 必须先定义
注意3 避免死循环 自己调用自己

案例:  函数的定义和 调用 

# 定义函数
def sayHello():
    print("Helloword")

# 调用函数
sayHello()

函数是如何执行的?
1. 当遇到def 一行时, 将函数名作为标识符保存到内存中 ,下面的代码 print("Helloword") 并不会执行 会继续往下执行
2. 当执行到 sayHello()  调用函数一行, 函数只有被调用时,才会执行内部的实现,  会在内存中查询对应的函数名 , 如果存在就执行函数内部的程序, 如果函数不存在就报错

二.  调用外部函数

1. 如果使用外部函数先导入外部的模块(外部文件名称)

       导包        import 文件名
       
调用函数       文件名.函数名() 
                    或者 
         
导包         import  pack.mode
     调用函数             pack.mode.function()
                    或者
          导包         from pack.mode import function 
       调用函数           function()

三. 内置函数

print函数
import builtins
builtins.print()

random函数
import random
random.randint(1,3)    # 包头不包尾 随机数只有可能是 1 2 

内置函数如下表
 

abs() divmod() input() open() staticmethod()
all() enumerate() int() ord() str()
any() eval() isinstance() pow() sum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bool() filter() len() range() type()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset() long() reload() vars()
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reverse() zip()
compile() hasattr() memoryview() round() __import__()
complex() hash() min() set()  
delattr() help() next() setattr()  
dict() hex() object() slice()  
dir() id() oct() sorted()













 

猜你喜欢

转载自blog.csdn.net/object_oriented_/article/details/86595472