Python Programming

python variables and its scope

Python Variables

What is a Variable?

A variable is a named storage location used to store data in memory.

Think of a variable as a labeled box that holds a value.

Example:

name = "John"
age = 25
salary = 50000

Here:

Variable Value
name John
age 25
salary 50000

Why Do We Need Variables?

Without variables:

print("John")
print("John")
print("John")

With variables:

name = "John"

print(name)
print(name)
print(name)

Variables make programs:

  • Easier to read
  • Easier to maintain
  • Reusable
  • Dynamic

Creating Variables

Python does not require declaring data types.

name = "Python"
age = 25
price = 99.99

Python automatically determines the type.


Checking Variable Type

name = "Python"

print(type(name))

Output:

<class 'str'>

Dynamic Typing

Python variables can change types.

data = 10

print(type(data))

data = "Hello"

print(type(data))

Output:

<class 'int'>
<class 'str'>

Variable Assignment

Single Assignment

name = "John"

Multiple Assignment

a, b, c = 10, 20, 30

print(a)
print(b)
print(c)

Output:

10
20
30

Same Value Assignment

x = y = z = 100

print(x)
print(y)
print(z)

Output:

100
100
100

Variable Naming Rules


Rule 1: Must Start With Letter or Underscore

✅ Correct

name = "John"
_age = 25

❌ Wrong

1name = "John"

Output:

SyntaxError

Rule 2: Cannot Contain Spaces

❌ Wrong

first name = "John"

Output:

SyntaxError

✅ Correct

first_name = "John"

Rule 3: Cannot Use Keywords

❌ Wrong

class = "Python"

Output:

SyntaxError

Rule 4: Case Sensitive

name = "John"

Name = "Alice"

print(name)
print(Name)

Output:

John
Alice

These are different variables.


Recommended Naming Conventions


student_name = "John"
total_marks = 500

Constants (Uppercase)

PI = 3.14159
MAX_USERS = 100

Avoid

a = 10
b = 20
c = a + b

Use meaningful names:

price = 10
quantity = 20

total_cost = price * quantity

Variables and Memory

x = 10

Python internally creates:

Variable x
    ↓
Value 10

Check Memory Address

x = 10

print(id(x))

Output:

Memory address (varies)

Reassigning Variables

x = 10

x = 20

print(x)

Output:

20

Old value is replaced.


Deleting Variables

name = "John"

del name

Trying to access:

print(name)

Output:

NameError

Variable Scope

Scope determines where a variable can be accessed.

Python provides:

  1. Local Scope
  2. Global Scope
  3. Enclosing Scope
  4. Built-in Scope

This is known as:

LEGB Rule

L → Local
E → Enclosing
G → Global
B → Built-in

Local Variables

Variables created inside a function.

Accessible only within that function.

Example:

def greet():
    name = "John"

    print(name)

greet()

Output:

John

Local Variable Error

❌ Wrong

def greet():
    name = "John"

greet()

print(name)

Output:

NameError

Reason:

Local variables exist only inside the function.


Global Variables

Variables created outside functions.

Accessible everywhere.

Example:

name = "John"

def greet():
    print(name)

greet()

Output:

John

Accessing Global Variables

company = "OpenAI"

def employee():
    print(company)

employee()

Output:

OpenAI

Modifying Global Variables

Consider:

count = 10

def update():
    count = 20

update()

print(count)

Output:

10

Why?

Because:

count = 20

creates a new local variable.


Using global Keyword

count = 10

def update():
    global count

    count = 20

update()

print(count)

Output:

20

Now the global variable changes.


Common Global Mistake

❌ Wrong

score = 100

def game():
    score += 10

game()

Output:

UnboundLocalError

Reason:

Python thinks score is local.


✅ Correct

score = 100

def game():
    global score

    score += 10

game()

print(score)

Output:

110

Enclosing Scope

Occurs in nested functions.

Example:

def outer():

    message = "Hello"

    def inner():
        print(message)

    inner()

outer()

Output:

Hello

Understanding Enclosing Scope

def outer():

    course = "Python"

    def inner():
        print(course)

    inner()

outer()

Output:

Python

Inner function can access outer function variables.


Modifying Enclosing Variables

Use:

nonlocal

Example:

def outer():

    count = 0

    def inner():

        nonlocal count

        count += 1

        print(count)

    inner()

outer()

Output:

1

Common nonlocal Mistake

❌ Wrong

def outer():

    count = 0

    def inner():

        count += 1

        print(count)

    inner()

Output:

UnboundLocalError

✅ Correct

nonlocal count

Built-in Scope

Python automatically provides built-in names.

Example:

print(len("Python"))

Output:

6

Here:

len()

comes from built-in scope.


LEGB Rule Explained

Example:

name = "Global"

def outer():

    name = "Outer"

    def inner():

        name = "Inner"

        print(name)

    inner()

outer()

Output:

Inner

Python searches:

1. Local
2. Enclosing
3. Global
4. Built-in

First match wins.


Variable Shadowing

A local variable can hide a global variable.

Example:

name = "Global"

def show():

    name = "Local"

    print(name)

show()

print(name)

Output:

Local
Global

Constants in Python

Python does not have true constants.

Convention:

PI = 3.14159
MAX_USERS = 100

Do not modify them.


Common Variable Mistakes


Mistake 1: Using Variable Before Creation

❌ Wrong

print(name)

name = "John"

Output:

NameError

Mistake 2: Misspelled Variable

❌ Wrong

student_name = "John"

print(student_nam)

Output:

NameError

Mistake 3: Confusing = and ==

❌ Wrong

if age = 18:

Output:

SyntaxError

✅ Correct

if age == 18:

Mistake 4: Expecting Local Variables Outside Function

❌ Wrong

def demo():
    value = 10

print(value)

Output:

NameError

Mistake 5: Forgetting global

❌ Wrong

counter = 0

def update():
    counter += 1

Output:

UnboundLocalError

Best Practices


Use Meaningful Names

❌ Avoid

a = 10
b = 20

✅ Better

price = 10
quantity = 20

Use Snake Case

student_name
total_marks
monthly_salary

Avoid Excessive Global Variables

global_data1
global_data2
global_data3
global_data4

Prefer function parameters.


Real World Example

Shopping Cart

cart_total = 0

def add_item(price):

    global cart_total

    cart_total += price

add_item(100)
add_item(200)

print(cart_total)

Output:

300

Homework 1

Create variables:

name
age
city

Store your own information and print them.


Solution

name = "Rahul"
age = 25
city = "Delhi"

print(name)
print(age)
print(city)

Homework 2

Assign:

10, 20, 30

to variables:

a, b, c

and print them.


Solution

a, b, c = 10, 20, 30

print(a)
print(b)
print(c)

Homework 3

Create a global variable:

company = "Google"

Print it inside a function.


Solution

company = "Google"

def show():
    print(company)

show()

Homework 4

Modify a global variable using:

global

Solution

counter = 0

def increment():

    global counter

    counter += 1

increment()

print(counter)

Output:

1

Homework 5

Create a nested function and access a variable from the outer function.


Solution

def outer():

    message = "Hello"

    def inner():
        print(message)

    inner()

outer()

Output:

Hello

Homework 6

Create a nested function and modify the outer variable using:

nonlocal

Solution

def outer():

    count = 0

    def inner():

        nonlocal count

        count += 1

        print(count)

    inner()

outer()

Output:

1

Quick Revision

Scope Type Accessible Where
Local Inside function only
Enclosing Inside nested function
Global Entire module
Built-in Everywhere

LEGB Rule

L → Local
E → Enclosing
G → Global
B → Built-in

Python searches variables in this exact order.


Summary

Concept Purpose
Variable Store data
Local Variable Exists inside function
Global Variable Exists throughout module
Enclosing Variable Exists in outer function
Built-in Variable Provided by Python
global Modify global variables
nonlocal Modify enclosing variables
id() Get memory address
del Delete variable

Master variables and scope before moving to:

  1. Conditional Statements (if, elif, else)
  2. Loops (for, while)
  3. Functions
  4. Modules
  5. Exception Handling
  6. File Handling
  7. Object-Oriented Programming

Filters

No filters available for this view.

Reset All