# Python 中的可選引數

Sahil Bhosale 2023年1月30日

## Python 中有多個可選引數的函式

### 使用*args(非關鍵字引數)

# Function Defination
def myfunction(first_name, last_name, *args):
print(first_name)
print(last_name)
for argument in args:
print(argument)

# Calling the Function
myfunction("Tim", "White", 999888999, 30)

Tim
White
999888999
30

### 使用**kargs(關鍵字引數)

def myFunction(**kwargs):
# printing all values which are passed in as an argument
for key, value in kwargs.items():
print("%s = %s" % (key, value))

# Calling the Function
myFunction(first_name="Tim", last_name="White", mob=99999999, age="30")

first_name = Tim
last_name = White
mob = 99999999
age = 30

*args**kargs 都是可變長度的引數，用於向函式傳遞可變數量的引數。

## 在 Python 中讓引數成為可選項

# Function Defination
def personalDetails(name, number, age):
print("This function takes 3 parameters as input")

def personalDetails(name, number, age):
print("This function takes 3 parameters as input")
print("Name: ", name)
print("Number: ", number)
print("Age: ", age)

# Calling the function

This function takes 3 parameters as input
Number: 987654321
Age: 18

def personalDetails(name, number, age=0):
print("Age is now an optional argument.")
print("Age is: ", age)

# Calling the function
personalDetails("Sam", 123456789)

Age is now an optional argument.
Age is: 0

def personalDetails(name, number, age=0):
print("Age is now an optional argument.")
print("Age is: ", age)

# Calling the function
personalDetails("Sam", 123456789, 25)

Age is now an optional argument.
Age is: 25

## まとめ

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.