📜  元组作为Python中的函数参数

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

元组作为Python中的函数参数

元组在Python编程的所有领域都有很多应用。它们是不可变的,因此是确保只读访问或将元素保持更长时间的重要容器。通常,它们可用于传递给函数并且可以具有不同类型的行为。可能会出现不同的情况。

下面的代码演示了所有情况的工作:

Python3
# Python3 code to demonstrate working of 
# Tuple as function arguments
  
# function with default arguments 
def fnc(a=None, b=None):
    print("Value of a : " + str(a))
    print("Value of b : " + str(b))
  
# Driver code
if __name__ == "__main__" :
    
  # initializing a And b
  a = 4
  b = 7
  
  # Tuple as function arguments
  # Case 1 - passing as integers
  print("The result of Case 1 : ")
  fnc(a, b)
  
  # Tuple as function arguments
  # Case 2 - Passing as tuple
  print("The result of Case 2 : ")
  fnc((a, b))
  
  # Tuple as function arguments
  # Case 3 - passing as pack/unpack 
  # operator, as integer
  print("The result of Case 3 : ")
  fnc(*(a, b))


输出 :

The result of Case 1 : 
Value of a : 4
Value of b : 7
The result of Case 2 : 
Value of a : (4, 7)
Value of b : None
The result of Case 3 : 
Value of a : 4
Value of b : 7