函数:是组织好的,可重复使用的,用来实现特定功能的代码段
什么是函数?
name="xiao"
lengh=len(name)
print(lengh)
输出如下
len()是python内置函数:是提前写好的,可以重复使用,实现统计长度这一特定功能
不用内置函数len()求字符串的长度
str1="xiao"
str2="da"
str3="python"
count=0
for i in str1:
count+=1
print(f"字符串{str1}的长度是:{count}")
count=0
for i in str2:
count+=1
print(f"字符串{str2}的长度是:{count}")
count=0
for i in str3:
count+=1
print(f"字符串{str3}的长度是:{count}")
输出如下
再用函数写上面代码(后面会学到)
str1="xiao"
str2="da"
str3="python"
def my_len(data):
count=0
for i in data:
count+=1
print(f"字符串{data}的长度是{count}")
my_len(str1)
my_len(str2)
my_len(str3)
输出如下
为什么学函数
为了得到一个针对特定需求,可供重复利用的代码段提高程序的复用性,减少重复的代码,提高开发效率