熟悉函数
def define定义
函数可以做三样事情:
1. 它们给代码片段命名,就跟“变量”给字符串和数字命名一样。
2. 它们可以接受参数,就跟你的脚本接受 argv 一样。
3. 通过使用 #1 和 #2,它们可以让你创建“微型脚本”或者“小命令”。
练习
#this one is like your scripts with argv
#定义函数print_two,设定atgs(参数变量)
def print_two(*args):
#解包 定义两个参数变量
arg1, arg2 = args
#打印变量 使用格式化字符串
print ("arg1: %r arg2: %r" % (arg1, arg2))
#ok, that *args is actually pointless, we can just do this
#定义函数print_two_again,设定两个参数变量
def print_two_again(arg1, arg2):
#打印变量 使用格式化字符串
print ("arg1: %r, arg2: %r" % (arg1, arg2))
#this just takes one argument
#一个参数变量的情况
def print_one(arg1):
print ("arg1: %r" % arg1)
#this one takes no arguments
#没有参数变量的情况
def print_none():
print ("I got nothin'.")
#设置变量值
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
打印结果

本文介绍了Python中函数的定义和使用方法,包括如何定义接受不同数量参数的函数,并展示了通过调用这些函数来执行特定任务的例子。
187

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



