📜  Python def 关键字

📅  最后修改于: 2022-05-13 01:55:02.521000             🧑  作者: Mango

Python def 关键字

Python def 关键字用于定义函数,它放在用户提供的函数名之前,以创建用户定义的函数。在Python,函数是代码的逻辑单元,包含使用“ def ”关键字给定的名称缩进的语句序列。在Pythondef关键字是最常用的关键字。

句法:

def function_name: 
    function definition statements...

def关键字的使用:

  • 对于类,def 关键字用于定义类的方法。
  • def 关键字也需要定义类的特殊成员函数,如 __init__()。

可能的实际应用是它提供了代码可重用的特性,而不是一遍又一遍地写一段代码,我们可以定义一个函数,并借助def关键字编写函数内部的代码。在下面给出的图示示例中将更加清楚。根据用例,def 可能有许多应用程序。

示例 1:使用 def 关键字。



在这个例子中,我们将使用 def 关键字创建一个用户定义的函数。

Python3
# Python3 code to demonstrate
# def keyword
  
# function for substraction of 2 numbers.
def subNumbers(x, y):
    return (x-y)
  
# main code
a = 90
b = 50
  
# finding substraction
result = subNumbers(a, b)
  
# print statement
print("substraction of ", a, " and ", b, " is = ", result)


Python3
# Python program to print first 10
# prime numbers
  
# A function name prime is defined
# using def
def prime(n):
    x = 1
    count = 0
    while count < n:
        for d in range(2, x, 1):
            if x % d == 0:
                x += 1
        else:
            print(x)
            x += 1
            count += 1
  
# Driver Code
n = 10
  
# print statement
print("First 10 prime numbers are:  ")
prime(n)


Python3
# Python program to find the
# factorial of a number
  
# Function name factorial is defined
def factorial(n):
    if n == 1:
        return n
    else:
        return n*factorial(n-1)
  
# Main code
num = 6
  
# check is the number is negative
if num < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    print("The factorial of", num, "is", factorial(num))


输出:

substraction of  90  and  50  is =  40

示例 2:用户定义一个具有前 10 个素数的函数。

蟒蛇3

# Python program to print first 10
# prime numbers
  
# A function name prime is defined
# using def
def prime(n):
    x = 1
    count = 0
    while count < n:
        for d in range(2, x, 1):
            if x % d == 0:
                x += 1
        else:
            print(x)
            x += 1
            count += 1
  
# Driver Code
n = 10
  
# print statement
print("First 10 prime numbers are:  ")
prime(n)

输出:

First 10 prime numbers are:  
1
2
3
5
7
11
13
17
19
23

示例 3:用户定义一个带有阶乘数的函数。

蟒蛇3

# Python program to find the
# factorial of a number
  
# Function name factorial is defined
def factorial(n):
    if n == 1:
        return n
    else:
        return n*factorial(n-1)
  
# Main code
num = 6
  
# check is the number is negative
if num < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    print("The factorial of", num, "is", factorial(num))

输出:

The factorial of 6 is 720