发布于2019-09-11 15:46 阅读(1588) 评论(0) 点赞(19) 收藏(3)
自己按照书《Python编程从入门到实践》进行学习,一个小阶段后进行一点点整理,仅供参考。编译器为Geany。
函数的定义和使用(def)
def greet_user():
print("Hello")
greet_user()
def greet_user(username):
print("Hello, "+username.title()+"!")
greet_user('alice')
在传递实参的过程中有位置实参和关键字实参。位置实参的顺序很重要,它关系到传递时候各个参数对应的值是什么;而关键字实参因为有关键字进行限定所以不必考虑顺序问题
可以在定义函数的时候写定函数的默认值
#有默认值时,先写没有默认值的
def describe_pet(pet_name,animal_type='dog'):
print("\nI have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet('hamster','harry')
#关键字实参的顺序无关紧要
describe_pet(animal_type='hamster',pet_name='harry')
describe_pet(pet_name='harry',animal_type='hamster')
函数的返回值
函数可以返回任何类型包括字典等
def build_person(first_name,last_name,age=''):
person = {'first':first_name,'last':last_name}
if age:
person['age'] = age
return person
print(build_person('jimi','hendrix',27))
在函数中传递、列表的值
用切片表示法创建了列表的副本,这样做就不会修改原本列表的值
def print_models(unprinted_designs,completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
print("printing model:"+current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['a','b','c']
completed_models = []
print_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)
print(unprinted_designs)
运用*可以传递任意数量的实参
def make_pizza(size,*toppings):
print("\nMaking a "+str(size)+
"-inch pizza with the following toppings:")
for topping in toppings:
print(topping)
make_pizza(12,'mushrooms','green peppers')
使用**可以传字典
#**创建一个名为user_info的空字典,并将收到的所有名称_值对都封装到这个字典中,并返回这个字典
def build_profile(first,last,**user_info):
profile={}
profile['frst_name']=first
profile['last_name']=last
for key,value in user_info.items():
profile[key]=value
return profile
user_profile = build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
import关键字导入函数
import pizza;
pizza.make_pizza(12,'mashroom','green_pepper')
#module_name.function_name()
#导入特定的函数
from module_name import function_name
from module_name import fuction_0,function_1,function2
#显式调用时无需使用句点,只需指定其名称
#as 给函数或模块指定别名
#from pizza import* 导入模块中的所有函数 不建议使用
from pizza import make_pizza as mp
make_pizza(12,'mashroom')
mp(12,'mashroom')
作者:23dh
链接:https://www.pythonheidong.com/blog/article/107502/05bce11def730d666416/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!