Skip to content

Declaring Variables and Assigning Values in Python

Updated: at 03:45 AM

Variables are an essential component of any programming language. They allow developers to store data in memory for later use and manipulation. In Python, variables provide a way to label and reference data in your code.

This article will provide a comprehensive, step-by-step guide on declaring variables and assigning values in Python. We will cover the following topics:

Table of Contents

Open Table of Contents

Variable Names and Conventions

When declaring a variable in Python, you need to follow certain rules and conventions for naming them:

# Correct variable names
student_name = "James"
student_grade = 4.0
student_id = 10

# Incorrect variable names
007 = "James" # Starts with number
student.grade = 4.0 # Contains period
global = 4.0 # Reserved keyword

Following Python’s PEP 8 style guide for naming conventions will make your code easier to read and maintain.

Declaring and Initializing Variables

In Python, variables don’t need explicit declaration to reserve memory space. The variable is automatically created when you first assign it a value.

To declare a variable, simply assign it a value using the equals sign (=).

# Declare by assignment
count = 0
price = 49.95
website = "Wikipedia"

You can also initialize a variable during declaration by assigning its initial value.

# Initialize during declaration
count = 0
price = 49.95
rating = 4.5

Python is a dynamically typed language, so the data type of a variable is set by the value assigned to it.

In the above examples, count is initialized as an integer, price as a float, website as a string, and rating as a float. The variables can be reassigned to values of any type later on.

Variable Types in Python

The common data types that can be stored in variables include:

num = 10
print(type(num)) # <class 'int'>
pi_value = 3.14159
print(type(pi_value)) # <class 'float'>
text = "This is a string"
print(type(text)) # <class 'str'>
bool_val = True
print(type(bool_val)) # <class 'bool'>
empty = None
print(type(empty)) # <class 'NoneType'>

Additionally, Python has built-in types like lists, tuples, dictionaries that can also be assigned to variables. Custom classes can also be defined and instantiated as variables.

# Built-in types
nums_list = [1, 2, 3]
point_tuple = (10, 20)
employee_dict = {'name':'Mary', 'id':1}

# Custom class
class Employee:
  pass

emp_1 = Employee()

Reassigning Variables

The value and data type of a variable can be changed after initial assignment in Python. Simply assign a new value to the variable to reinitialize it.

# Initial declaration
count = 0

# Reassignment
count = 10
print(count) # 10

# Reassignment to new type
count = "ten"
print(count) # ten

The ability to reassign variables makes Python very flexible. Reusing variable names can help reduce overall memory usage compared to constantly creating new variables.

However, reusing variables for different purposes can make code difficult to understand. Use descriptive names and single responsibility principle to avoid misuse.

Multiple Assignment

Python allows assigning a single value to several variables simultaneously.

a = b = c = 10
print(a, b, c) # 10 10 10

x = y = z = "Hello"
print(x, y, z) # Hello Hello Hello

This is called multiple assignment and works by assigning the value to the first variable, then linking the rest to it. All variables refer to the same object in memory.

Multiple assignment can be used to swap two variables easily without needing a temporary variable.

# Swap a and b
a, b = 10, 20
print(a, b) # 10 20

a, b = b, a
print(a, b) # 20 10

Constants in Python

Python does not have built-in constant types like other languages. However, by convention capital letters are used to denote constants in Python.

MAX_SIZE = 100
PI = 3.14159

MAX_SIZE = 200 # This would go against conventions

To prevent reassignment of a variable, the constant module can be used:

from constant import ValueAsConstant

MAX_SIZE = ValueAsConstant(100)

MAX_SIZE = 200 # Raises TypeError

Constants make code more readable by defining immutable fixed values that have a clear purpose. Use them instead of hardcoding values throughout the code.

Best Practices for Using Variables

Follow these best practices when declaring and using variables in Python:

Properly naming and using variables makes programs easier to read and reduces chances of errors. It takes a bit more effort up front, but pays off in maintaining and extending code.

Conclusion

This guide covered key topics related to declaring variables and assigning values in Python, including:

Variables are the basic building blocks of any Python program. Using them judiciously and following Python’s style guide will lead to code that is more readable, maintainable, and less error-prone. The concepts covered here apply to all Python versions and provide a solid foundation to build programming skills.