Python函数和参数

Dear learners, in this tutorial we are going to learn Python Function and Arguments. Previously we learned about Python loop. Hope that you will enjoy learning.

亲爱的学习者,在本教程中,我们将学习Python函数和参数。 先前我们了解了Python循环 。 希望您会喜欢学习。

Python函数和参数 (Python Function and Arguments)

Basically function is used to do some specific work. We can split a large task to some work distribution and do them separately which will enable us to debug program easily. The basic structure of a Python function is given below:

基本上,功能用于完成一些特定的工作。 我们可以将大型任务划分为一些工作分配,然后分别进行处理,这使我们可以轻松地调试程序。 Python函数的基本结构如下:

def function_name( arguments ) :
        #perform tasks

Python function arguments can be one or more. If it is more than one, they has to be separated by comma. For example, you want to calculate result = x * ( y + z ).

Python函数参数可以是一个或多个。 如果不止一个,则必须用逗号分隔。 例如,您要计算result = x *(y + z)

Let, p = y + x
So, result = x * p

p = y + x
因此, 结果= x * p

First, we have to calculate p, and then, putting the value of p we have to calculate result. To do so, we will create separate functions. The following code will illustrate about Python function.

首先,我们必须计算p ,然后,将p的值放入我们必须计算result 。 为此,我们将创建单独的功能。 以下代码将说明有关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)

The output of the following code will be

以下代码的输出将是

================== RESTART: /home/imtiaz/Desktop/pyDef.py ==================
x: 2
y: 2
z: 3
10
>>>

传递可变数量的参数 (Passing Variable Number of Arguments)

If you don’t know how many arguments you have to pass in the function then you can allow the function to take variable number of arguments. To do this you need to add an asterisk(*) right before your argument name. But there is some condition, that your special argument has to be the last argument of the function and it is allowed to have only one argument of that kind in one function. The following example will help you to understand the variable number of arguments in python function.

如果您不知道必须在函数中传递多少个参数,则可以允许该函数采用可变数量的参数。 为此,您需要在参数名称之前添加一个星号(*)。 但是有一个条件,您的特殊参数必须是该函数的最后一个参数,并且在一个函数中只能有一个这种类型的参数。 以下示例将帮助您了解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")

The Output will be:

python function, python function arguments, python function variable arguments example

输出将是:

将键值对作为可选的Python函数参数传递 (Passing Key-Value pair as Optional Python Function Arguments)

You can also pass arguments by keywords, so that the order you send argument does not matter. To do so, you have to add two asterisks(**) right before the special argument when you define a function. The following example will clear your concept.

您还可以通过关键字传递参数,因此发送参数的顺序无关紧要。 为此,在定义函数时,必须在特殊参数之前添加两个星号(**)。 以下示例将清除您的概念。

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")

Output will be

输出将是

================== 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
>>>

This is all about Python Function and Arguments. Hope that you understood well. For any query feel free to use the comment section below.
Keep you enthusiasm always up for learning new things!

这一切都与Python函数和参数有关。 希望你能理解。 对于任何查询,请随时使用下面的评论部分。
始终保持学习新事物的热情!

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/14256/python-function-arguments

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值