Python中函数的初体验

1、函数:
组织好的,可重复使用的,用来实现特定功能的代码段
2、使用函数的好处:

  • 将功能封装在函数内,可供随时随地重复利用
  • 提高代码的复用性,减少重复代码,提高开发效率
# 统计字符串的长度,不使用内置函数len()
str1 = "itheima"
str2 = "itcast"
str3 = "python"

# 定义一个计数的变量
conut = 0
for i in str1:
    conut += 1
print(f"字符串{str1}的长度是:{conut}")

conut = 0
for i in str2:
    conut += 1
print(f"字符串{str2}的长度是:{conut}")

conut = 0
for i in str2:
    conut += 1
print(f"字符串{str3}的长度是:{conut}")


# 使用函数,来优化过程:
def my_len(data):
    conut = 0
    for i in data:
        conut += 1
    print(f"字符串{data}的长度是:{conut}")
posted @ 2023-12-08 23:29  hugh2023  阅读(16)  评论(0)    收藏  举报