Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

อาร์กิวเมนต์ค่าเริ่มต้น (Default arguments) ใน Python

Default argument คืออาร์กิวเมนต์ที่สมมติค่าเริ่มต้นหากไม่มีค่าถูกส่งในการเรียกฟังก์ชันสำหรับอาร์กิวเมนต์นั้น ตัวอย่างต่อไปให้แนวคิดเกี่ยวกับ default arguments มันพิมพ์ default age หากไม่ได้ส่งผ่าน:

ตัวอย่าง

#!/usr/bin/python
# Function definition is here
def printinfo(name, age=35):
    "This prints a passed info into this function"
    print "Name: ", name
    print "Age ", age
    return;
# Now you can call printinfo function
printinfo(age=50, name="miki")
printinfo(name="miki")

ผลลัพธ์ (Output)

เมื่อรันโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้:

Name: miki Age 50
Name: miki Age 35