python编程入门经典学习小结3

一、函数

1、在交互窗口调用函数方法:python -i <文件名>

def in_fridge():

    try:

        count=fridge[wanted_food]

    except KeyError:

        count=0

    return count

将上述函数存储在char2.py文件中

在命令窗口调用

fridge={"apple":2,"orange":3}

wanted_food="apple"

in_fridge()


2、在函数中显示名称

使用_doc_访问这些属性

def in_fridge():

    '''This is a function to see if the fridge has a food'''

    try:

        count=fridge[wanted_food]

    except KeyError:

        count=0

    return count

print("%s"% in_fridge.__doc__)

3、不同位置使用相同的名称

编写函数时使用名称,不影响程序其他地方使用

list=["a","b","c"]

def new_list():

    list=["a","b"]

    return list

print(list)

new_list=new_list()

print(new_list)


4、调用带参数的函数

def in_fridge(some_fridge,desired_item):

    try:

        count=some_fridge[desired_item]

    except KeyError:

        count=0

    return count

fridge={"apple":2,"orange":3}

wanted_food="apple"

in_fridge(fridge,wanted_food)


in_fridge({"apple":5,"orange":3},"orange")


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容