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

คำสั่ง return ใน Python

คำสั่ง return [expression] ออกจากฟังก์ชัน โดยอาจส่งค่ากลับ expression ให้ผู้เรียก คำสั่ง return โดยไม่มีอาร์กิวเมนต์เท่ากับ return None

ตัวอย่าง

ตัวอย่างข้างต้นทั้งหมดไม่ได้คืนค่าใดๆ คุณสามารถคืนค่าจากฟังก์ชันได้ดังนี้:

#!/usr/bin/python
# Function definition is here
def sum(arg1, arg2):
    # Add both the parameters and return them.
    total = arg1 + arg2
    print "Inside the function : ", total
    return total;
# Now you can call sum function
total = sum(10, 20);
print "Outside the function : ", total

ผลลัพธ์ (Output)

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

Inside the function : 30
Outside the function : 30