一、函数
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")