Python Variable

In Python, a variable is a named storage location that holds a value. Unlike some statically-typed languages, Python is dynamically-typed meaning you don't need to declare the variable's type explicitly. The interpreter determines the type based on the assigned value.


# Variable declaration and assignment
x = 5
name = "John"


Here, x is a variable holding an integer value (5) and name is a variable holding a string ("John").

Naming Conventions

Following consistent naming conventions is essential for the writing clean and readable code. Python variables should adhere to the following guidelines:
  • Start with a letter (a-z, A-Z) or an underscore (_).
  • Subsequent characters can include letters, numbers and underscores.
  • Avoid using reserved keywords like if, else, for etc.
my_variable = 42

user_name = "Alice"

Data Types

Python supports various data types and variables can hold values of different types. Common data types include:
  1. int: Integer values (e.g. 42)
  2. float: Floating-point values (e.g. 3.14)
  3. str: String values (e.g. "Hello, World!")
  4. bool: Boolean values (True or False)
  5. list: Ordered collection of values
  6. tuple: Immutable ordered collection
  7. dict: Key-value pairs
  8. set: Unordered collection of unique values
# Examples of different data types
age = 25 # int
height = 5.9 # float
message = "Hello" # str
is_student = True # bool

my_list = [1, 2, 3] # list
my_tuple = (4, 5, 6) # tuple
my_dict = {"key": "value"} # dict
my_set = {1, 2, 3} # set

Scope of Variables

Understanding variable scope is crucial for preventing naming conflicts and ensuring the correct usage of variables. In Python, variables have either local or global scope.

Local Scope: The Variables defined within a function or block have local scope and are only accessible within that scope.

def my_function():
local_variable = "I am local"
print(local_variable)

my_function()
print(local_variable) # This will raise an error


Global Scope: The Variables defined outside any function or block have global scope and can be accessed throughout the program.

global_variable = "I am global"
def another_function():
print(global_variable)
another_function()
print(global_variable) # This will print "I am global"

Best Practices

To write clean and maintainable code consider the following best practices:
  • Use descriptive variable names for better readability.
  • Avoid using single-letter variables except in cases like loop counters (i, j).
  • Initialize variables before using them to avoid potential errors.
# Good practices
user_age = 30
total_users = 100

# Avoid single-letter variable names
a = 5 # Less readable