Programming LanguagesPythonTutorials

Python Variables

In Python programming, a variable is a named location in memory that is used to store data. You can think of it as a labeled box in which you can place a value. This allows you to store information that can be referenced and manipulated later in your program.

When you create a variable, you are allocating space in your computer’s RAM (Random Access Memory) to hold a specific value. This means that the variable acts as a pointer to that location in memory, making it easier to manage and utilize data throughout your code.

How to Declare a Variable

Simple Declaration

 
Declaring a variable in Python is simple. You assign a value to a variable name using the = operator.

Example of Variable Declaration

# Declaring a variable  
age = 25

 
In this example, we’ve created a variable named age and assigned it the value 25. This means that the computer reserves space in RAM for the variable age, which now holds the integer value 25.

Assignment

 
Assignment refers to the process of updating or changing the value of a variable. You can reassign a new value to the same variable at any time.

# Assigning a new value to the variable  
age = 30 # Now, age holds the value 30

Types of Variables

 
Variables in Python can store different types of data, and it’s important to understand these types. The type of a variable defines what kind of data it can hold and how it can be used. Here are the various variable types in Python:

Variable TypeDescriptionExample
IntegerWhole numbers without decimalsx = 10
FloatNumbers with decimalsy = 10.5
StringText data enclosed in quotesname = "Alice"
BooleanRepresents True or Falseis_active = True
ListOrdered collection of itemsitems = [1, 2, 3]
TupleImmutable ordered collectioncoordinates = (10, 20)
DictionaryKey-value pairsperson = {"name": "John", "age": 30}

Types of Variables


Variables in Python can store different types of data, and it’s important to understand these types. The type of a variable defines what kind of data it can hold and how it can be used. Here are the various variable types in Python:

  1. Data Management: Different types of variables can be used for different purposes, allowing for efficient data handling.
  2. Error Prevention: Knowing variable types helps prevent mistakes (e.g., trying to perform arithmetic operations on strings).
  3. Code Clarity: Clear types make your code easier to read and maintain.

Examples of Variable Types and Type Checking

 
Let’s declare variables with different types, use the type() function to check their types, and print both their values and types.

# Different types of variables  
age = 25 # Integer
height = 5.9 # Float
name = "Alice" # String
is_student = True # Boolean
hobbies = ["reading", "gaming"] # List
coordinates = (10, 20) # Tuple
profile = {"name": "Bob", "age": 22} # Dictionary

# Print value and type of each variable
print("Value:", age, "| Type:", type(age))
print("Value:", height, "| Type:", type(height))
print("Value:", name, "| Type:", type(name))
print("Value:", is_student, "| Type:", type(is_student))
print("Value:", hobbies, "| Type:", type(hobbies))
print("Value:", coordinates, "| Type:", type(coordinates))
print("Value:", profile, "| Type:", type(profile))

Expected Output:

Value: 25 | Type: <class 'int'>  
Value: 5.9 | Type: <class 'float'>
Value: Alice | Type: <class 'str'>
Value: True | Type: <class 'bool'>
Value: ['reading', 'gaming'] | Type: <class 'list'>
Value: (10, 20) | Type: <class 'tuple'>
Value: {'name': 'Bob', 'age': 22} | Type: <class 'dict'>

Naming Rules for Variables


When creating variables in Python, it’s important to follow some basic rules to avoid syntax errors and keep your code readable:

  • Start with a letter or an underscore (_)
    • Variable names cannot begin with a number.
  • Avoid using special characters or spaces
    • Use underscores (_) instead of spaces (e.g., student_age, not student age).
  • Be case-sensitive
    • Python treats Name, name, and NAME as three different variables.
  • Don’t use reserved words
    • Avoid naming your variables with Python keywords like class, if, or return.

Examples of valid variable names:

username = "john_doe"
_totalMarks = 88
isLoggedIn = True

# Print valid variables
print(username)       # Output: john_doe
print(_totalMarks)    # Output: 88
print(isLoggedIn)     # Output: True




Examples of invalid names:

2score = 95         # ✖️ Starts with a number
user name = "Ali"   # ✖️ Contains a space
def = "function"    # ✖️Uses a reserved keyword

Reassigning Variables in Python

In Python, variables are dynamic meaning you can reassign them at any time, even to a different type of value.

# Initial assignment
status = "active"  # String

# Reassigning a new value
status = False     # Now it's a Boolean

Deleting Variables

Sometimes, you may want to remove a variable entirely to free up memory or clean up your namespace. You can do this using the del statement.

score = 100
print(score)  # Output: 100

del score     # Deletes the variable

print(score)  # NameError: name 'score' is not defined

How It Works (Conceptual Understanding)

  1. Application Level: When you define a variable, you’re creating an identifier that refers to a specific piece of data.
  2. Python Interpreter: The interpreter allocates a section of memory in RAM for this variable and stores the value you’ve assigned to it.
  3. Binary/OS Level: At the lowest level, those values are stored in binary format in the allocated memory space, which the operating system uses to run your program efficiently.

Best Practices for Variables

  1. Use Descriptive Names: Choose variable names that indicate their purpose (e.g., student_ageheight_cm).
  2. Consistency: Follow a consistent naming convention, like snake_case or camelCase.
  3. Avoid Global Variables: Limit the use of global variables to make your code modular and easier to manage.

Practice Tasks

Task 1: Create Your Own Variables

  1. Define variables to store your favorite movie title (string), your age (integer), and whether you have a pet (boolean).
  2. Print out these variables along with their types using the type() function.

Task 2: Update Variable Values

  1. Start with a variable named books_read, initialized to 5.
  2. Change its value to 10 later in the code, and print the updated value along with its type.

Guidance

 
As you work on these tasks, focus on choosing meaningful names for your variables, and try to play around with different types. Observe how changing the type of a variable affects your program.

Motivation

 
Try the tasks and share your answers in the comments to get appreciated! Happy coding with variables!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button