Python函数和参数
时间:2020-02-23 14:42:43 来源:igfitidea点击:
在本教程中,我们将学习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 p
p = calculateP ( y , z )
#Now calculate result
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("\nSecond Person")
#See, the order of argument age and gender is different now
varFunc("Bob", 204, gender="male", age=21)
print("\nThird 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 >>>

