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 example for creating a variable:

Python Variables Example

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

Code 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!“.

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 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 )

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)

Code 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

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)

Code 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.

Variable Scope 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()

Code 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-7: Print the values of local and global variables within the function.
  • Line 9: Calls the display_message() function.

Type Conversion/Casting of Variables

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)})")

Code 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

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}")

Code 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.