Python return语句

Python return语句

在Python中,return语句是一个非常有用的语句,用于将程序的流程从函数返回给函数的调用者。关键字 return 用于编写return语句。

由于Python中的所有内容都是对象,返回值可以是任何对象,例如- 数值(int,float,double)或集合(list,tuple,dictionary)或用户定义的函数和类或包。

return语句具有以下特点-

  • return语句不能在函数外部使用。

  • 在return语句之后编写的任何代码都被称为死代码,因为它永远不会被执行。

  • return语句可以隐式或显式地传递任何值,如果没有给出值,则返回None。

语法

以下是Python中return语句的语法-

def some_function(parameters):
   return <expression>
print(some_function)

示例

下面是一个简单的return语句示例 –

def welcome(str):
   return str + " from TutorialsPoint"
print(welcome("Good morning"))

输出

以下是上述代码的输出 –

Good morning from TutorialsPoint

return语句在多种情况下都很有用,下面的部分将讨论return语句的不同用法以及示例。

在Python中使用return语句

函数是任何编程语言的核心,因为它们允许代码模块化,从而减少程序复杂性。函数可以在函数内部显示结果,但这会使程序复杂化,因此最好将所有函数的结果传递到一个统一的地方。

正是在这种情况下,return语句很有用,因为它终止当前正在执行的函数,并将程序的控制权传递给调用该函数的语句。

示例

在下面的代码中,sum_fibonacci函数用于计算斐波那契数列的前15个项的和。计算完和之后,它将和打印出来,并将和返回给sum_result变量。这是为了说明在函数内部打印和返回值会得到相同的输出。

# Defining function to calculate sum of Fibonacci series
def sum_fibonacci(terms):
   first_term = 0
   second_term = 1
   sum_series = 0

   # Finding the sum of first 15 terms of Fibonacci series
   for i in range(0, terms):
      sum_series = sum_series + first_term
      next_term = first_term + second_term
      first_term = second_term
      second_term = next_term

   # Printing the sum inside the function
   print("Sum of Fibonacci series inside the function is = {}".format(sum_series))

   # Returning the sum using return statement
   return sum_series

# Invoking the sum_fibonacci function
sum_result = sum_fibonacci(15)
print("Sum of Fibonacci series outside the function is = {}".format(sum_result))

输出

输出显示,使用打印语句从函数内部得到的求和结果,和使用返回语句从函数外部得到的求和结果是相等的。

Sum of Fibonacci series inside the function is = 986
Sum of Fibonacci series outside the function is = 986

使用return语句返回函数

在Python中,函数是一类对象,这意味着它们可以存储在变量中或作为参数传递给另一个函数。由于函数是对象,return语句可以用于从另一个函数中返回一个函数作为值。返回函数或将函数作为参数的函数被称为高阶函数。

示例

在这个示例中,finding_sum函数包含另一个函数add。首先调用finding_sum函数,并将第一个数字作为参数传递给它。add函数接收第二个数字作为参数,并将两个数字的和返回给finding_sum函数。finding_sum函数然后将add函数作为一个值返回给sum变量。

# Defining function to return sum of two numbers

# Function to get the first number
def finding_sum(num1):

   # Function to get the second number
   def add(num2):
      return num1 + num2 # return sum of numbers to add function
   return add # return value present in add function to finding_sum function
sum = finding_sum(5)
print("The sum of the two numbers is: {}".format(sum(10)))

输出

程序的输出结果是两个数字 5 和 10 的和。

The sum of the two numbers is: 15

使用return语句返回None

在Python中,函数总是返回一个值,即使没有显式地写出返回语句。因此,Python不像其他编程语言中的过程那样,没有返回语句的函数。如果返回语句不返回结果或者从函数中省略,则Python将隐式地返回None的默认值。

只有在程序中包含多个返回语句以让其他程序员知道函数的终止点时,才应考虑明确调用return None。

示例

下面的程序完美地演示了如何使用return None。在这个程序中,check_prime()函数用于检查一个列表是否包含任何质数。如果列表包含质数,则打印出列表中所有的质数。然而,如果列表中没有质数,则返回None,因为该程序包含多个返回语句,因此需要显式地调用None。

def check_prime(list):
   prime_list = []
   for i in list:
      counter = 0
      for j in range(1, i):
         if i % j == 0:
            counter = counter + 1
         if counter == 1:
            prime_list.append(i)
         if len(prime_list):
            return prime_list
         else:
            return None
list = [4, 6, 8, 10, 12]
print("The prime numbers in the list are: {}".format(check_prime(list)))

输出

输出为None,因为列表中没有质数。

The prime numbers in the list are: [4]

使用return语句返回多个值

在Python中,return语句也可以用于通过使用逗号来分隔值,从单个函数中返回多个值。这个特性在需要对相同的数据集进行多个计算,而不改变原始数据集时特别有用。返回语句的结果是一个值的元组。

示例

在这个示例中,使用统计库的内置函数来计算均值、中位数和众数,并使用单个return语句将它们返回,展示了如何从函数中返回多个值。

import statistics as stat
# Defining function to perform different statistical calculations
def finding_stats(data):
   return stat.mean(data), stat.median(data), stat.mode(data)

   # returning multiple values

list_numbers = [5, 7, 13, 17, 17, 19, 33, 47, 83, 89]
print("The mean, median and mode of the data is: {}".format(finding_stats(list_numbers)))

输出

输出结果以元组类型给出数据集的均值、中位数和众数。

The mean, median and mode of the data is: (33, 18.0, 17)

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程