Python编程:函数与迭代的深入解析
1. 函数基础
在Python中,函数是一段具有特定功能的代码块。定义函数时,需要使用 def 关键字,并且函数定义完成后,会创建一个同名的变量。例如:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print(print_lyrics)
print(type(print_lyrics))
上述代码中, print_lyrics 是一个函数对象,其类型为 function 。调用函数的语法与内置函数相同,如下所示:
print_lyrics()
运行结果为:
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
函数定义后,还可以在其他函数中调用。例如,定义一个 repeat_lyrics 函数来重复调用 print_lyrics 函数:
def repeat_lyrics()
超级会员免费看
订阅专栏 解锁全文
18万+

被折叠的 条评论
为什么被折叠?



