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

ขอบเขตของตัวแปร (Scope of Variables) ใน Python

ตัวแปรทั้งหมดในโปรแกรมอาจเข้าถึงไม่ได้ที่ทุกตำแหน่งในโปรแกรม นี่ขึ้นอยู่กับว่าคุณประกาศตัวแปรที่ไหน

ขอบเขตของตัวแปร (scope) กำหนดส่วนของโปรแกรมที่คุณสามารถเข้าถึง identifier เฉพาะได้ มีขอบเขตพื้นฐานสองแบบของตัวแปรใน Python:

  • Global variables
  • Local variables

Global vs. Local variables

ตัวแปรที่ถูกกำหนดภายใน body ของฟังก์ชันมี local scope และตัวแปรที่ถูกกำหนดภายนอกมี global scope

นี่หมายความว่าตัวแปร local สามารถเข้าถึงได้เฉพาะภายในฟังก์ชันที่ประกาศ ในขณะที่ตัวแปร global สามารถเข้าถึงได้ตลอดโปรแกรมโดยทุกฟังก์ชัน เมื่อคุณเรียกฟังก์ชัน ตัวแปรที่ประกาศภายในจะถูกนำเข้า scope

ตัวอย่าง

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

ผลลัพธ์ (Output)

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

Inside the function local total : 30
Outside the function global total : 0