函数
无参函数
-
代码
def hello(): print("hello");
-
结果
hello
带参函数
-
代码
def daican(width,height): print(width*height); daican(12*13)
-
结果
156
带参带返回值
-
代码
def daicanfanhui(width, height): return width * height a = daicanfanhui(12,13) print(a)
-
结果
156
默认值
-
代码
def morenzhi(width,height=0.2): print(width*height) morenzhi(1,2) morenzhi(1) morenzhi(width=6,height = 3)
-
结果
2 0.2 18
关键字实参
-
代码
def guanjianzhishichan(width,height): print(width*height) guanjianzhishichan(width=2,height=6)
-
结果
12
让实参变成可选的
-
代码
def shicankexuan(first_name,last_name,middle_name=''): if middle_name: full_name = first_name+' '+middle_name+' '+last_name else: full_name = first_name +' '+last_name print(full_name) shicankexuan("xiaoming",'xiaohuang') shicankexuan('xiaoming','xiaohuang','xiaoke')
-
结果
xiaoming xiaohuang xiaoming xiaoke xiaohuang
和java相似之处
-
代码
def xiugailiebiao(listone): listone[0]='hahah' listone = [1,'haha','shanshan'] print(listone) xiugailiebiao(listone) print(listone)
-
结果
[1, 'haha', 'shanshan'] ['hahah', 'haha', 'shanshan']
-
总结
- python和java一样,没有指针之说,在函数中加工数据直接可以用实参传。
无限接收参数
-
无限接收参数
-
代码
def jieshourenyicanshu(*listone): print(listone) def jieshourenwushuliangcanshu(nun,*str1): print(nun) print(str1) jieshourenyicanshu("xiaomi") jieshourenyicanshu("xiaomi","huawei","vivo","oppo") jieshourenwushuliangcanshu(1,"haha","ahaha","guagua","hehe")
-
结果
('xiaomi',) ('xiaomi', 'huawei', 'vivo', 'oppo') 1 ('haha', 'ahaha', 'guagua', 'hehe')
-
总结
- 有时候预先不知道接收多少个实参,可以利用元组统统将他们接收进来,然后在处理加工
- 固定数量类型的实参,和任意数量类型的实参,注意类型单一,多个类型的形参要放后面
-
-
无限接收键值对
-
代码
def jieshouerweijianzhidui(firstname,lastname,**user_info): print("firstname:"+firstname) print("lastname:"+lastname) for key ,value in user_info.items(): print("key:"+key) print("value: "+value) print(user_info) jieshouerweijianzhidui("albert","elinstan",xiaomi="xiaomi",vivo="vivo",huawei="huawei",oppo="oppo")
-
结果
firstname:albert lastname:elinstan key:xiaomi value: xiaomi key:vivo value: vivo key:huawei value: huawei key:oppo value: oppo {'xiaomi': 'xiaomi', 'vivo': 'vivo', 'huawei': 'huawei', 'oppo': 'oppo'}
-
导入模块
-
还可以将专门写进一个文件中,导入文件,然后调用,可以利用as制作一个名字
-
导入的时候先扫描文件,如果文件中有可以执行的语句,先执行,所以,模块函数文件尽量不要放测试语句
-
同一目录下,直接引用
-
例如
import hanshu hanshu.hello() hanshu.morenzhi(2,2)
-
-
不同目录下。添加目录,利用上面的语句加入进来
-
例如
import sys sys.path.append(r'E:\python_workspace')
-