Python Variables

What Are Variables in Python?

A variable in Python is like a container that holds data. The name of the variable represents the container, and the value stored in the container is the data.

Key Characteristics of Python Variables:

  1. Python variables are dynamically typed, meaning you don’t need to specify their data type when declaring them.
  2. Variables can store different types of data, such as numbers, strings, lists or even functions.
  3. Python allows variable reassignment, so you can change the value stored in a variable at any time.

How to Declare Variables in Python

Declaring a variable in Python is straightforward. Simply assign a value to a variable name using the assignment operator =.

Syntax:

variable_name = value

Example:

name = "Alice"        # A string variable
age = 25 # An integer variable
height = 5.7 # A floating-point variable
is_student = True # A boolean variable

Rules for Naming Variables

To avoid errors and ensure readability, follow these rules when naming variables:

  1. Use Letters, Numbers, and Underscores: Variable names can include letters, numbers, and underscores (_). However, they must begin with a letter or an underscore.
    • Valid: name, _age, student_1
    • Invalid: 1name, @student
  2. Avoid Reserved Keywords: Don’t use Python keywords like if, while, True or def as variable names.
  3. Be Case-Sensitive: Python treats uppercase and lowercase letters as different. For instance, name and Name are two separate variables.
  4. Use Descriptive Names: Choose meaningful names to make your code more readable.
    • Bad: x, y
    • Good: customer_name, order_total

Variable Reassignment in Python

In Python, you can reassign a variable to a new value, even if it’s a different data type.

Example:

x = 10          # Integer
x = "Python" # String
x = [1, 2, 3] # List
print(x) # Output: [1, 2, 3]

Multiple Assignments

Python allows you to assign multiple values to multiple variables in a single line.

Example:

a, b, c = 10, 20, 30
print(a, b, c) # Output: 10 20 30

You can also assign the same value to multiple variables:

x = y = z = 50
print(x, y, z) # Output: 50 50 50

Variable Types in Python

Variables in Python can store different types of data. Here are the most common types:

  1. Integer: Stores whole numbers.
    Example: age = 25
  2. Float: Stores decimal numbers.
    Example: height = 5.9
  3. String: Stores sequences of characters.
    Example: name = “Alice”
  4. Boolean: Stores True or False.
    Example: is_student = True
  5. List: Stores a collection of values in a single variable.
    Example: fruits = [“apple”, “banana”, “cherry”]
  6. Dictionary: Stores data in key-value pairs.
    Example: person = {“name”: “Alice”, “age”: 25}

Global and Local Variables

Python variables can have a global or local scope:

  1. Local Variables: Declared inside a function and can only be accessed within that function.

Example:

def greet():
name = "Alice" # Local variable
print("Hello, " + name)

greet()
# print(name) # This will raise an error because 'name' is local to the greet function.
  1. Global Variables: Declared outside any function and accessible throughout the program.

Example:

name = "Alice"  # Global variable

def greet():
print("Hello, " + name)

greet() # Output: Hello, Alice

To modify a global variable inside a function, use the global keyword:

count = 0  # Global variable

def increment():
global count
count += 1

increment()
print(count) # Output: 1

Best Practices for Using Variables in Python

  1. Use Descriptive Names: Names like customer_name are more meaningful than x or y.
  2. Follow the Snake Case Naming Convention: Use lowercase words separated by underscores (_).
    Example: total_cost, is_logged_in
  3. Avoid Changing Data Types Frequently: Keep the same data type for a variable wherever possible.
  4. Limit the Use of Global Variables: Excessive global variables can make debugging difficult.

Common Errors with Variables

Using Undeclared Variables:

print(name)  # Error: name is not defined

Variable Naming Errors:

1name = "Alice"  # SyntaxError: invalid syntax

Case Sensitivity Confusion:

name = "Alice"
print(Name) # Error: Name is not defined

Leave a Comment