Skip to content

Variables in Python

A variable in Python is a name that acts as a reference or label for a value stored in memory. Variables are used to store data that can be manipulated or referenced throughout a program.


1. Features of Variables in Python

  • Dynamic Typing: Variables in Python do not need a type declaration. The type is inferred from the value assigned.

x = 10        # Integer

y = “Python”  # String

  • Mutable and Immutable Types: Depending on the type of data, variables may be mutable (e.g., lists) or immutable (e.g., integers, strings).
  • No Explicit Declaration: Variables are created when a value is assigned.

2. Declaring and Assigning Variables

In Python, variables are declared and initialized by simply assigning a value using the = operator.

Syntax:

variable_name = value

Examples:

x = 10                 # Integer

name = “Alice”         # String

is_active = True       # Boolean

pi = 3.14159           # Float

fruits = [“apple”, “banana”]  # List


3. Variable Naming Rules

To create valid variable names in Python, follow these rules:

  1. Must Start with a Letter or Underscore:
    1. Valid: name, _value
    1. Invalid: 1name, @value
  2. Can Contain Letters, Numbers, and Underscores:
    1. Valid: user1, value_2
    1. Invalid: user-name, value$2
  3. Cannot Use Reserved Keywords:
    1. Keywords like if, for, True cannot be used as variable names.
    1. Example of keywords:

False, True, None, if, else, elif, while, for, def, return

  • Case-Sensitive:
    • Name and name are treated as different variables.

name = “Alice”

Name = “Bob”


4. Types of Variables

a. Global Variables

  • Declared outside any function or block.
  • Accessible throughout the program.

x = 10  # Global variable

def print_x():

    print(x)

print_x()  # Output: 10

b. Local Variables

  • Declared inside a function or block.
  • Accessible only within that scope.

def my_function():

    y = 5  # Local variable

    print(y)

my_function()  # Output: 5

# print(y)  # Error: ‘y’ is not defined outside the function

c. Nonlocal Variables

  • Used in nested functions to refer to a variable in the nearest enclosing scope.

def outer_function():

    x = “outer”

    def inner_function():

        nonlocal x

        x = “inner”

        print(x)  # Output: inner

    inner_function()

    print(x)  # Output: inner

outer_function()

d. Constants

  • Variables intended to remain unchanged throughout the program.
  • Conventionally written in uppercase.

PI = 3.14159

GRAVITY = 9.8


5. Variable Scope

The scope of a variable determines where it can be accessed in the program.

a. Local Scope:

  • Variables declared inside a function are local to that function.

b. Global Scope:

  • Variables declared outside all functions are global and accessible anywhere in the program.

c. Enclosed Scope:

  • Refers to variables in the enclosing (outer) function scope in nested functions.

d. Built-in Scope:

  • Refers to Python’s reserved keywords and functions, e.g., len, print.

6. Variable Types in Python

Python variables are dynamically typed, meaning they can hold different types of data at different times.

Examples of Variable Types:

a = 5          # Integer

b = 3.14       # Float

c = “Hello”    # String

d = True       # Boolean

e = [1, 2, 3]  # List

f = (4, 5)     # Tuple

g = {“name”: “Alice”, “age”: 25}  # Dictionary

Type Checking:

To check the type of a variable:

x = 10

print(type(x))  # Output: <class ‘int’>

Type Conversion:

Variables can be converted from one type to another.

x = “123”

y = int(x)  # Convert string to integer


7. Assigning Multiple Variables

Python supports multiple assignments in a single line.

a. Single Value to Multiple Variables:

x = y = z = 10

b. Multiple Values to Multiple Variables:

a, b, c = 1, 2, 3


8. Mutable and Immutable Variables

Immutable Variables:

  • Cannot be changed after assignment.
  • Examples: int, float, str, tuple.

x = 10

x = x + 1  # Creates a new object

Mutable Variables:

  • Can be modified after assignment.
  • Examples: list, dict, set.

my_list = [1, 2, 3]

my_list.append(4)  # Modifies the original list


9. Best Practices for Variables

  1. Use Descriptive Names:
    1. Bad: x, y
    1. Good: user_age, total_cost
  2. Follow Naming Conventions:
    1. Use snake_case for variables: total_cost, user_name.
  3. Avoid Using Keywords as Variables:

# Avoid this:

for = 10  # Error: ‘for’ is a reserved keyword

  • Use Constants for Fixed Values:
    • Use uppercase for constants: MAX_SIZE = 100.
  • Keep Scope Minimal:
    • Declare variables in the smallest possible scope.

Conclusion

Variables are a foundational concept in Python, enabling programmers to store, manipulate, and retrieve data efficiently. By adhering to Python’s rules and best practices for variable declaration and usage, developers can write clean, maintainable, and error-free code