Python Variables: Your First Step in AI Programming

Master Python variables, the building blocks of AI & machine learning. Learn to create, print, delete, & use them effectively with practical examples for beginners.

1.1 Python Variables: A Comprehensive Guide

This guide covers the fundamental concept of variables in Python, essential for any beginner programmer. We'll explore what variables are, how Python handles them, how to create, print, and delete them, along with naming conventions, scope, and practical examples.

What Is a Variable in Python?

In Python, a variable is a name that refers to a memory location where a value is stored. Think of it as a labeled container for data like text, numbers, or more complex data structures. When you assign a value to a variable, Python automatically allocates memory to store that value.

fruit = "Apple"
quantity = 25

In this example, "Apple" (a string) and 25 (an integer) are stored in memory. The names fruit and quantity act as references or pointers to these memory locations.

How Python Stores Data

Each variable in Python points to an object stored in memory. The type of the object (e.g., string, integer, float) determines the amount of memory it occupies. You can inspect the memory address of an object using the built-in id() function:

print(id("Apple"))   # Displays the memory address of the string object "Apple"
print(id(25))        # Displays the memory address of the integer object 25

When you assign a value to a variable, the variable directly references the object containing that value:

fruit = "Apple"
quantity = 25

print(id(fruit))     # Will print the same memory address as id("Apple")
print(id(quantity))  # Will print the same memory address as id(25)

Creating Variables in Python

Creating variables in Python is straightforward: you simply assign a value to a name. Python is dynamically typed, meaning you don't need to declare the variable's type beforehand; Python infers the type at runtime.

count = 50            # Integer type inferred
temperature = 36.6    # Float type inferred
greeting = "Hello"    # String type inferred
is_active = True      # Boolean type inferred

Printing Variables in Python

To display the value stored in a variable, you use the print() function:

count = 50
temperature = 36.6
greeting = "Hello"

print(count)
print(temperature)
print(greeting)

Output:

50
36.6
Hello

You can also print multiple variables at once by separating them with commas:

name = "Alice"
age = 30

print("Name:", name, "Age:", age)

Output:

Name: Alice Age: 30

Deleting Variables in Python

You can remove a variable from memory using the del statement. Once a variable is deleted, attempting to access it will result in a NameError.

item = "Laptop"
print(item)

del item

# The line below will cause an error because 'item' no longer exists:
# print(item)

Output:

Laptop
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'item' is not defined

Checking the Type of a Variable

The type() function allows you to determine the data type of any variable:

a = "Data"
b = 42
c = 3.14
d = [1, 2, 3]

print(type(a))  # Output: <class 'str'>
print(type(b))  # Output: <class 'int'>
print(type(c))  # Output: <class 'float'>
print(type(d))  # Output: <class 'list'>

Python Variable Names Are Case-Sensitive

Python distinguishes between uppercase and lowercase letters in variable names. This means city and City are treated as two entirely different variables.

city = "Paris"
City = "London"
CITY = "Berlin"

print(city)   # Output: Paris
print(City)   # Output: London
print(CITY)   # Output: Berlin

Multiple Variable Assignment in Python

Python offers convenient ways to assign values to multiple variables:

Assigning the Same Value to Multiple Variables

You can assign a single value to several variables simultaneously:

a = b = c = 5
print(a, b, c)  # Output: 5 5 5

Assigning Different Values to Multiple Variables

You can also assign different values to different variables in a single line, provided the number of values matches the number of variables:

x, y, z = 1, 2, "Code"
print(x, y, z)  # Output: 1 2 Code

Valid and Invalid Variable Names

Variable names in Python must adhere to specific rules:

Valid Examples

  • Must start with a letter (a-z, A-Z) or an underscore (_).
  • Can contain letters, numbers (0-9), and underscores.
  • Are case-sensitive.
total_price = 100
userName = "Ava"
_count = 5
user_id_123 = "xyz789"

Invalid Examples

  • Cannot start with a digit: 1name
  • Cannot contain special characters (except underscore): user-name, user@name
  • Cannot be a reserved keyword: for, while, if, class, def, etc.
# Invalid names:
# 1name = 10          # Starts with a digit
# user-name = "Test"  # Contains a hyphen
# for = 123           # 'for' is a reserved keyword
# class = "Math"      # 'class' is a reserved keyword

Following naming conventions improves code readability and maintainability. The Python community generally follows the PEP 8 style guide:

  • snake_case: For variables and functions (e.g., total_price, calculate_average). This is the most common and recommended style for variables.
  • camelCase: Sometimes used for variables, especially when interfacing with code from other languages, but less common in pure Python. (e.g., pricePerItem).
  • PascalCase: Primarily used for class names (e.g., ClassName).

Example:

# Good practice (snake_case)
user_name = "Bob"
account_balance = 1500.75

# Less common but sometimes seen (camelCase)
# accountBalance = 1500.75

# PascalCase is for classes, not variables
# AccountBalance = 1500.75 # Incorrect for a variable

Important: Always avoid using Python's reserved keywords (like if, else, for, while, def, class, return, import, etc.) as variable names.

Practical Example: Area and Perimeter Calculator

Let's use variables to calculate the area and perimeter of a rectangle:

length = 15
breadth = 10

area = length * breadth
perimeter = 2 * (length + breadth)

print("Length:", length)
print("Breadth:", breadth)
print("Area:", area)
print("Perimeter:", perimeter)

Output:

Length: 15
Breadth: 10
Area: 150
Perimeter: 50

Local vs Global Variables in Python

Variables can have different scopes, determining where they can be accessed within a program.

Local Variables

A local variable is defined inside a function and is accessible only within that function's scope.

def greet():
    message = "Hello, User!"  # 'message' is a local variable
    print(message)

greet()  # Output: Hello, User!

# Attempting to access 'message' outside the function will cause an error:
# print(message)
# NameError: name 'message' is not defined

Global Variables

A global variable is declared outside any function and can be accessed and modified from anywhere in the program, both inside and outside functions.

x = 5  # 'x' is a global variable
y = 10 # 'y' is a global variable

def add_numbers():
    result = x + y  # Accessing global variables 'x' and 'y'
    print("Sum inside function:", result)

add_numbers()  # Output: Sum inside function: 15
print("Sum outside function:", x + y) # Output: Sum outside function: 15

Modifying Global Variables Inside Functions: To modify a global variable from within a function, you must explicitly declare it using the global keyword.

count = 0 # Global variable

def increment_count():
    global count # Declare intention to modify the global 'count'
    count += 1
    print("Count inside function:", count)

increment_count() # Output: Count inside function: 1
print("Count outside function:", count) # Output: Count outside function: 1

Constants in Python

Python does not have built-in support for true constants like some other languages (where a value cannot be changed after definition). However, by convention, constants are represented by uppercase variable names. This signals to other developers that the value is intended to remain unchanged.

PI_VALUE = 3.14159
MAX_USERS = 100
DEFAULT_TIMEOUT = 30

print(PI_VALUE)
# Although you *can* change it, you shouldn't according to convention:
# PI_VALUE = 3.14
# print(PI_VALUE)

Treating these uppercase variables as constants is a matter of programming discipline and convention.

Conclusion

Mastering Python variables is a crucial step in your programming journey. Their dynamic typing, flexible naming conventions, and straightforward assignment make them easy to learn and use. Understanding how variables store data, their scope, and how to manage them effectively will empower you to write cleaner, more efficient, and more readable Python code.


SEO Keywords: Python variables, Python variable naming conventions, Dynamic typing in Python, Global vs local variables Python, Constants in Python, Python variable assignment, Python variable deletion, Python variable types, Multiple variable assignment Python, Python variable scope.

Possible Interview Questions:

  • Explain what a variable is in Python.
  • How does Python handle memory allocation for variables?
  • What are the rules for naming variables in Python?
  • Differentiate between local and global variables in Python.
  • How do you delete a variable in Python?
  • Discuss the concept of dynamic typing in Python.
  • Can you assign multiple variables in a single line in Python? How?
  • What are constants in Python, and how are they typically defined?
  • Why is it important to avoid using Python’s reserved keywords as variable names?
  • Give an example of when you would use global variables in Python programming.
  • What are the advantages of using snake_case for variable names in Python?