亲爱的学习者,在本教程中,我们将学习Python函数和参数。之前我们了解到Python循环. 希望你喜欢学习。
Python函数和参数
基本上功能是用来做一些具体的工作。我们可以把一个大的任务分解成一些工作分配,然后分别进行,这样我们就可以很容易地调试程序了。Python函数的基本结构如下:
def function_name( arguments ) :
#perform tasks
Python函数参数可以是一个或多个。如果不止一个,它们必须用逗号隔开。例如,您要计算结果=x*(y+z).
让,p=y+x所以,结果=x*p
首先,我们要计算p,然后,将p我们得计算一下结果. 为此,我们将创建单独的函数。下面的代码将演示Python函数。
"""
create a function for adding two variables. It will be needed to calculate p=y+z
"""
def calculateP( y , z ) :
return int( y ) + int( z )
"""
create a function for multiplying two variables. It will be needed to calculate p=y+z
"""
def calculateResult( x, p ) :
return int( x ) * int( p )
#Now this is the beginning of main program
x = input("x: ")
y = input("y: ")
z = input("z: ")
#Now Calculate <strong>p</strong>
p = calculateP ( y , z )
#Now calculate <strong>result</strong>
result = calculateResult( x , p )
#Print the result
print(result)
以下代码的输出将是
================== RESTART: /home/imtiaz/Desktop/pyDef.py ==================
x: 2
y: 2
z: 3
10
>>>
传递可变数量的参数
如果您不知道必须在函数中传递多少个参数,则可以允许函数接受可变数量的参数。为此,您需要在参数名之前添加一个星号(*)。但是有一个条件,你的特殊参数必须是函数的最后一个参数,并且在一个函数中只允许有一个这样的参数。下面的示例将帮助您理解python函数中参数的可变数目。
def varFunc(name,*args):
print("This is the first argument "+str(name))
#This print will make you understand that the args is a list
print(args)
for item in args:
print(item)
print("First time:")
varFunc("of 1st function call",2, 3, 4, 5)
print("Second time:")
varFunc("of 2nd function call","asd","Bcd")
print("Third time:")
varFunc("and only argument of 3rd function call")
输出将是:
将键值对作为可选的Python函数参数传递
也可以通过关键字传递参数,这样发送参数的顺序就不重要了。为此,在定义函数时,必须在特殊参数之前添加两个星号(**)。下面的例子将阐明您的概念。
def varFunc(name, roll, **option):
print("Name: "+name)
print("Roll: "+str(roll))
if "age" in option :
print("Age: "+ str(option.get("age")))
if "gender" in option:
print("Gender: "+ str(option.get("gender")))
print("First Person")
varFunc("Alice", 234, age=18, gender="female")
print("
Second Person")
#See, the order of argument age and gender is different now
varFunc("Bob", 204, gender="male", age=21)
print("
Third Person")
#We will not pass age as and argument
varFunc("Trudy", 204, gender="male")
输出将是
================== RESTART: /home/imtiaz/Desktop/key_value_arg.py ==================
First Person
Name: Alice
Roll: 234
Age: 18
Gender: female
Second Person
Name: Bob
Roll: 204
Age: 21
Gender: male
Third Person
Name: Trudy
Roll: 204
Gender: male
>>>
这是关于Python函数和参数的。希望你能理解。对于任何查询,请使用下面的评论部分。保持你学习新事物的热情!
参考文献:官方文件