Python Variables

Grasp the fundamental concept of Python variables: how they store data, follow naming conventions, and represent different data types. This understanding is essential for building any Python program, as variables act as containers for the information your code uses and manipulates.

Python-Variables
Table of Contents

What is a variable in Python?

In Python, variables act as named containers that store data. You can think of them like labeled boxes where you can keep information your program needs to use. Assigning a value to a variable creates a link between the variable name and the data it holds. Here’s the basic syntax for creating a variable:

Python Variables Syntax

variable_name = value

  • variable_name: This is the name you choose to identify your variable (must follow naming rules).
  • value: This is the data you want to store in the variable (can be numbers, text, or other types).

Python Variables Example

message = "Hello, world!"
print(message)

Explanation

  • Line 1: Creates a variable named message and assigns the string “Hello, world!” to it.
  • Line 2: Prints the value stored in the message variable, which outputs “Hello, world!“.

Understanding Memory Addresses of Variables

In Python, variables store data, but you don’t directly interact with the memory location of that data. While you don’t need to worry about the specific memory address, the id() function can be handy for understanding how Python manages variable assignments. It returns a unique identifier (integer) for each object in memory.

Example

message = "Hello, world!"
message_id = id(message)

print(f"The variable 'message' stores the value: {message}")
print(f"The memory address (id) of 'message' is: {message_id}")

Explanation

  • Line 1: Creates a variable message and assigns the string “Hello, world!” to it.
  • Line 2: Uses the id() function on the message variable and stores the returned integer (memory address identifier) in message_id.
  • Line 4: Prints the value stored in the message variable.
  • Line 5: Prints the memory address identifier (message_id) returned by the id() function. It’s important to note that this identifier can change across different Python sessions or if the variable is reassigned to a new value.

Python Naming Conventions

Here’s a breakdown of Python naming conventions, along with the official recommendations from PEP 8 (https://peps.python.org/pep-0008/):

Variables

  • Lowercase_with_underscores: This is the preferred convention for most variable names (e.g., total_count, user_input).
  • Single leading underscore: Indicates a “private” variable that shouldn’t be directly accessed outside of the class or module where it’s defined (e.g., _internal_data).

Functions

  • Lowercase_with_underscores: The same as the variable convention (e.g., calculate_average, open_file).

Classes

  • PascalCase (CapitalizedWords): Each word starts with a capital letter (e.g., ShoppingCart, RequestHandler).

Modules

  • lowercase_with_underscores: Similar to variables, but for longer module names (e.g., network_utils.py).

Constants

  • UPPERCASE_WITH_UNDERSCORES This signifies values that shouldn’t change during program execution (e.g., MAX_ITERATIONS, PI )

Key Points and Exceptions

  • Consistency: Aim for consistency within each project. If an existing codebase goes against some conventions here, it’s often better to follow its style.
  • Descriptive Names: Choose names that convey the meaning or purpose of the entity.
  • Built-in Names: Avoid using names that clash with built-in Python keywords or functions (e.g., list, str).

Case Sensitivity in Variable Names

Python uses naming conventions to help coders write readable and maintainable code. Here’s a breakdown of common case styles for variables:

Camel Case

Words within a variable name are joined without spaces, and each word after the first begins with a capital letter (e.g., numberOfStudents). Less common in Python but used in some libraries.

Pascal Case

Similar to the Camel Case, the first word also starts with a capital letter (e.g., ShoppingCart). Mainly used for class names in Python.

Snake Case

Words are separated by underscores and remain lowercase (e.g., user_name). This is Python’s most common and recommended convention for variables and functions.

Example

current_temperature = 23  # Snake case (recommended)
CustomerInfo = {}         # Pascal case (for class names)

Explanation

  • Line 1: Assigns the value 23 to the variable current_temperature using Snake case.
  • Line 2: Declares an empty dictionary named CustomerInfo using Pascal case, following the convention for class names in Python.

Declaration and Initialization

In Python, you declare a variable by simply assigning a value to it using its name. This assignment also initializes the variable, meaning it sets its initial value. It’s important to note that you can re-declare and reassign values to Python variables throughout your code. Python also supports assigning multiple variable values in a single line. You can print the value of a variable using the print() function.

Example

count = 0
name = "Alice"
count = count + 5
message, count = "Hello", 10
print(name)

Explanation

  • Line 1: Declares the variable count and initializes it with the integer value 0.
  • Line 2: Declares the variable name and initializes it with the string value “Alice”.
  • Line 3: Re-declares the variable count and assigns a new value calculated by adding 5 to the original value.
  • Line 4: Multiple assignments – the string “Hello” is assigned to message and the integer 10 is assigned to count.
  • Line 5: Prints the value stored in the name variable.

Understanding Object Reference and Object Identity of Python Variables

In Python, understanding object reference and object identity is essential for working with variables and data:

Object Reference

Think of an object reference as a label on a box. A variable with an object reference points to the location in memory where the actual object (the contents of the box) is stored. Multiple variables can refer to the same object in memory.

Object Identity

This is the unique identifier associated with each object in Python. You can find it using the id() function. Even if two objects have the same value, they will have different identities if they occupy different memory locations.

Example

message_1 = "Hello!"
message_2 = "Hello!"
message_3 = message_1  # Assign object reference

print(message_1 is message_2)
print(message_1 is message_3)

Explanation

  • Lines 1-2: Create two separate string objects, “Hello!” each with their place in memory.
  • Line 3: message_3 now refers to the same object in memory as message_1.
  • Line 5: message_1 and message_2 have the same value but are distinct objects existing in different memory locations, so the is operator will return False.
  • Line 6: message_1 and message_3 refer to the same object, so the is operator will return True.

Variable Scope in Python

In Python, variable scope determines where a variable can be accessed and modified in your code. Here’s a breakdown of the main concepts:

Local Scope

A variable declared inside a function has local scope – it can only be used within that function. Variables with the same name in different functions are separate.

Global Scope

A variable declared outside of any function has a global scope. It can be accessed from anywhere in the module. You’ll need to use the global keyword to modify a global variable inside a function.

Example

global_message = "Welcome"  # Global variable

def display_message():
local_message = "Hello from the function!"  # Local variable
print(local_message)
print(global_message)

display_message() 

Explanation

  • Line 1: Declares a global variable named global_message and assigns it a string value.
  • Line 3: Defines a function named display_message.
  • Line 4: Declares a local variable named local_message within the display_message function.
  • Lines 5-6: Print the values of local and global variables within the function.
  • Line 8: Calls the display_message() function.

Deleting Variables in Python

While Python manages memory automatically, you can explicitly delete variables using the del keyword. This removes the variable’s reference from memory, freeing it up for other uses. However, it’s important to note that deleting a variable doesn’t necessarily remove the underlying object it’s referencing if other variables still point to it.

Example

message = "Hello, world!"
print(message)  # Output: Hello, world!

del message

try:
    print(message)  # NameError: name 'message' is not defined
except NameError:
    print("Variable 'message' is deleted")

Explanation

  • Lines 1-2: Create a variable message and print its value.
  • Line 4: Delete the variable message using del.
  • Lines 6-7: Attempt to print message again. This will result in a NameError because the variable reference is gone. The try-except block catches this error and prints a message instead.

Immutable vs. Mutable Variable Types

In Python, a crucial concept is whether the value stored in a variable can change after its creation. This is the distinction between immutable and mutable types:

Immutable

The value of an immutable object cannot be modified after it’s created. Types like strings, numbers, and tuples are immutable. Any attempt to change them will create a new object.

Mutable

Mutable objects, such as lists, dictionaries, and sets, can have their contents modified in place. Changes affect the original object.

Example

my_string = "Hello"  # Immutable (string)
my_list = [1, 2, 3]  # Mutable (list)

try:
    my_string[0] = "J"  # TypeError - Attempt to change a string
except TypeError:
    print("Strings are immutable")

my_list.append(4)    # Modifying the list in place
print(my_list)       # Output: [1, 2, 3, 4] 

Explanation

  • Lines 1-2: Create my_string (immutable) and my_list (mutable).
  • Lines 4-5: Tries to change the first character of my_string, resulting in a TypeError because strings are immutable.
  • Lines 9: Successfully appends 4 to my_list, demonstrating mutable objects can change in place.

Type Conversion/Casting of Variables

In Python, you can convert between data types of variables using type casting functions. This is sometimes referred to as type conversion. These functions transform a variable’s value from one data type to another.

Example

message = "123"  # String type

converted_value = int(message)  # Convert to integer

print(f"Original value: {message} (type: {type(message)})")
print(f"Converted value: {converted_value} (type: {type(converted_value)})")

Explanation

  • Line 1: Assigns the string “123” to the variable message.
  • Line 3: Converts the value in message to an integer using the int() function and stores the result in converted_value.
  • Lines 5-6: Print the original value and type of message, then the converted value and its type (integer) after conversion using type().

Getting the Type of a Variable

In Python, determining the data type of a variable is straightforward using the built-in type() function. This function takes a variable as input and returns its corresponding data type as an output. Here’s an example:

Example

message = "Hello, world!"
message_type = type(message)

print(f"The variable 'message' stores the value: {message}")
print(f"The data type of 'message' is: {message_type}")

Explanation

  • Line 1: Assigns the string “Hello, world!” to the variable message.
  • Line 2: Uses the type() function on the message variable. The result (which is the data type) is stored in the message_type variable.
  • Lines 4-5: Prints the value stored in message and the data type stored in message_type. In this case, it will print “The variable ‘message’ stores the value: Hello, world!” and “The data type of ‘message’ is: <class ‘str’>” since 'str' represents a string data type.