Python Variable Scope: Local vs Global

🐍 Global vs Local Variables in Python Functions 🌍 Understanding variable scope is very important in Python 👇 ✅ 1️⃣ Local Variable (Inside Function) A local variable is created inside a function It can only be used inside that function def greet(): message = "Hello" # Local variable print(message) greet() ✔️ Works inside the function ❌ Cannot be accessed outside print(message) # ❌ NameError ✅ 2️⃣ Global Variable (Outside Function) A global variable is created outside any function It can be accessed anywhere name = "Danial" # Global variable def greet(): print(name) greet() ✔️ Function can read global variable ⚠️ Modifying Global Variable Inside Function If you want to change a global variable inside a function, use global keyword 👇 count = 0 def increase(): global count count += 1 increase() print(count) # 1 Without global, Python gives an error ❌ 🔑 Simple Difference Local → Lives inside function Global → Lives outside function 💡 Best Practice: Use local variables whenever possible. Avoid too many globals — they make code harder to manage. 🚀 Understanding scope helps you write cleaner and bug-free programs 💻 #Python #Coding #Programming #LearnToCode #Developer

To view or add a comment, sign in

Explore content categories