Skip to main content

Python Variables

Introduction

Variables are one of the most fundamental concepts in any programming language. In Python, a variable is like a container that holds data which can be changed throughout the execution of a program. Think of variables as labeled boxes where you can store values that you want to use or manipulate later in your code.

Unlike some other programming languages, Python doesn't require you to declare a variable's type before using it. Python is dynamically typed, which means that the type of a variable is determined at runtime based on the value it is assigned.

Creating Variables in Python

In Python, you create a variable by assigning a value to it using the equal sign (=).

python
# Creating a variable
name = "John"
age = 25
height = 5.9
is_student = True

In this example, we've created four variables:

  • name: stores a string value
  • age: stores an integer value
  • height: stores a floating-point number
  • is_student: stores a Boolean value (True or False)

Variable Naming Rules and Conventions

When naming variables in Python, there are certain rules and conventions to follow:

Rules (must follow)

  1. Variable names can contain letters, numbers, and underscores (_)
  2. Variable names must start with a letter or an underscore
  3. Variable names cannot start with a number
  4. Variable names are case-sensitive (age and Age are different variables)
  5. Variable names cannot be Python keywords (like if, for, class, etc.)

Conventions (good practice)

  1. Use descriptive names that indicate what the variable contains
  2. Use lowercase letters for variable names
  3. Separate words with underscores (snake_case): user_name, total_price
  4. Avoid using single characters like a, b, x (except for counters or coordinates)
python
# Good variable names
user_name = "Alice"
total_price = 125.50
is_active = True

# Less ideal variable names
a = "Alice" # Not descriptive
userName = "Bob" # Not using snake_case
PRICE = 125.50 # Uppercase usually reserved for constants

Variable Assignment and Reassignment

One of the powerful features of variables is that their values can change during the execution of a program.

python
# Assigning and reassigning variables
counter = 1
print(counter) # Output: 1

counter = counter + 1
print(counter) # Output: 2

counter += 1 # Shorthand for counter = counter + 1
print(counter) # Output: 3

# You can also change the type of data stored in a variable
variable = 10
print(variable) # Output: 10
print(type(variable)) # Output: <class 'int'>

variable = "Hello"
print(variable) # Output: Hello
print(type(variable)) # Output: <class 'str'>

Multiple Assignment

Python allows you to assign values to multiple variables in one line:

python
# Multiple assignment
x, y, z = 1, 2, 3
print(x) # Output: 1
print(y) # Output: 2
print(z) # Output: 3

# Assigning the same value to multiple variables
a = b = c = 0
print(a, b, c) # Output: 0 0 0

Variable Scope

The scope of a variable refers to the portion of code where the variable is accessible. Python has two main types of variable scope:

  1. Local variables: Defined inside a function and can only be used inside that function
  2. Global variables: Defined outside of functions and can be accessed throughout the program
python
# Global variable
global_var = "I am global"

def my_function():
# Local variable
local_var = "I am local"
print(local_var) # Works fine
print(global_var) # Works fine - global variables can be accessed inside functions

my_function()
print(global_var) # Works fine
# print(local_var) # Would cause an error - local variables can't be accessed outside their function

To modify a global variable from within a function, you need to use the global keyword:

python
count = 0

def increment():
global count # Tell Python we want to use the global variable
count += 1
print(count)

increment() # Output: 1
increment() # Output: 2
print(count) # Output: 2

Constants

Python doesn't have built-in constant types, but by convention, variables that should not be changed are written in all uppercase:

python
PI = 3.14159
MAX_CONNECTIONS = 1000

# Later in the code
area = PI * radius * radius

Real-World Examples

Example 1: Shopping Cart Calculation

python
# Initialize variables
item1_price = 15.99
item2_price = 29.95
quantity1 = 2
quantity2 = 1
tax_rate = 0.08

# Calculate subtotal
subtotal = (item1_price * quantity1) + (item2_price * quantity2)

# Calculate tax
tax = subtotal * tax_rate

# Calculate total
total = subtotal + tax

# Display results
print(f"Subtotal: ${subtotal:.2f}") # Output: Subtotal: $61.93
print(f"Tax: ${tax:.2f}") # Output: Tax: $4.95
print(f"Total: ${total:.2f}") # Output: Total: $66.88

Example 2: User Profile Management

python
# User profile information
username = "jdoe"
full_name = "John Doe"
email = "[email protected]"
age = 28
is_active = True
account_balance = 125.50

# Update user information
age += 1 # User had a birthday
account_balance -= 25.50 # User made a purchase

# Display updated profile
print(f"Username: {username}")
print(f"Name: {full_name}")
print(f"Email: {email}")
print(f"Age: {age}")
print(f"Active account: {is_active}")
print(f"Account balance: ${account_balance:.2f}")

# Output:
# Username: jdoe
# Name: John Doe
# Email: [email protected]
# Age: 29
# Active account: True
# Account balance: $100.00

Summary

In this lesson, we covered:

  • What variables are and how they work in Python
  • How to create and name variables following Python's rules and conventions
  • Assigning and reassigning values to variables
  • Multiple variable assignment
  • Variable scope (local and global)
  • The concept of constants in Python
  • Real-world examples showing variables in action

Variables are essential building blocks for any Python program. They allow us to store, track, and manipulate data throughout our code. As you continue learning Python, you'll discover more ways to effectively use variables in your programs.

Exercises

  1. Create variables to store your name, age, and favorite programming language, then print them out in a sentence.

  2. Write a program that calculates the area and perimeter of a rectangle using variables for the length and width.

  3. Create a simple temperature converter that converts Celsius to Fahrenheit using the formula: F = C * 9/5 + 32.

  4. Write a program that swaps the values of two variables without using a third temporary variable.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)