foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Python
  • Understand what variables are and why we use them
  • Learn how to create and assign values to variables
  • Follow Python naming conventions and best practices
  • Master variable reassignment and multiple assignment techniques

Variables and Assignment

Variables are the foundation of every program. Think of a variable like a labeled box where you can store something - a number, text, or any other piece of information. You give the box a name so you can easily find and use what's inside later.

In Python, working with variables is straightforward. No complex declarations or type specifications needed - just name your variable and give it a value.


What is a Variable?

A variable is a named location in your computer's memory that stores a value. It's like a label attached to a piece of data.


                   Variable Concept                               

                                                                  
   VARIABLE NAME          VALUE                                  
        ↓                   ↓                                    
                                               
     age      25                                   
                                               
                                                                  
                                           
     name     "Alice"                              
                                           
                                                                  
                                               
    price    19.99                                 
                                               
                                                                  

Why Use Variables?

Reason Example
Store data for later Save a user's name to greet them later
Make code readable total_price is clearer than 19.99 * 3
Reuse values Use the same discount percentage everywhere
Change values easily Update one variable instead of many numbers

Creating Variables (Assignment)

In Python, you create a variable using the assignment operator (=):

# Basic assignment syntax
variable_name = value

# Examples
age = 25
name = "Alice"
price = 19.99
is_student = True

Key Point: The = sign in Python means "assign the value on the right to the variable on the left." It's not the same as mathematical equality!

Reading the Assignment Statement

x = 10

Read this as: "x gets the value 10" or "x is assigned 10"

NOT as: "x equals 10" (that's == in Python)


Variable Reassignment

Variables can change their values at any time – that's why they're called "variables"!

# Initial assignment
score = 0
print(score)  # Output: 0

# Reassignment
score = 10
print(score)  # Output: 10

# Reassign again
score = score + 5  # Add 5 to current score
print(score)  # Output: 15

Type Can Change Too!

Unlike some languages, Python allows you to change a variable's type:

x = 10        # x is an integer
print(x)      # 10

x = "hello"   # Now x is a string
print(x)      # hello

x = 3.14      # Now x is a float
print(x)      # 3.14

Note: While this flexibility is convenient, it's often better practice to keep variables consistent in their type for code clarity.


Variable Naming Rules

Python has specific rules about what makes a valid variable name:

The Rules

Rule Valid Examples Invalid Examples
Must start with letter or underscore name, _count, Age 1name, @data
Can contain letters, numbers, underscores user_1, total2024 my-var, user@name
Cannot be a Python keyword my_class, for_loop class, for, if
Case-sensitive Name ≠ name ≠ NAME —

Valid vs Invalid Examples

# VALID variable names
name = "Alice"
age2 = 25
_private = "secret"
firstName = "Bob"
CONSTANT = 3.14
user_email = "test@example.com"

# INVALID variable names
# 2name = "error"        # Can't start with number
# my-var = 10            # No hyphens allowed
# for = 5                # 'for' is a keyword
# user@email = "x"       # No @ allowed

Naming Conventions (Best Practices)

While Python allows many valid names, following conventions makes code more readable:


                   Python Naming Conventions                      

                                                                  
  Variables & Functions: snake_case                              
  user_name, total_price, calculate_tax                       
                                                                  
  Constants: UPPER_SNAKE_CASE                                    
  MAX_SIZE, PI, TAX_RATE                                      
                                                                  
  Classes: PascalCase                                            
  UserProfile, ShoppingCart                                   
                                                                  
  Private: Leading underscore                                    
  _internal_value, _helper_function                           
                                                                  

Good vs Bad Names

# BAD: Unclear
x = 100
n = "John"
t = 19.99

# GOOD: Descriptive
user_age = 100
customer_name = "John"
product_price = 19.99

# BAD: Too abbreviated
usr_nm = "Alice"
ttl_amt = 50

# GOOD: Readable
user_name = "Alice"
total_amount = 50

Multiple Assignment

Python offers elegant ways to assign multiple variables at once:

Assign Same Value to Multiple Variables

# All three variables get the value 0
a = b = c = 0

print(a)  # 0
print(b)  # 0
print(c)  # 0

Assign Different Values in One Line

# Assign multiple values at once
x, y, z = 1, 2, 3

print(x)  # 1
print(y)  # 2
print(z)  # 3

# Great for related data
name, age, city = "Alice", 25, "Paris"

Swap Variables

This is a Python specialty – no temporary variable needed!

# Traditional way (in other languages)
# temp = a
# a = b
# b = temp

# Python way - elegant!
a = 10
b = 20

a, b = b, a  # Swap!

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

Checking Variable Types

Use the type() function to see what type a variable holds:

age = 25
name = "Alice"
price = 19.99
is_active = True

print(type(age))       # <class 'int'>
print(type(name))      # <class 'str'>
print(type(price))     # <class 'float'>
print(type(is_active)) # <class 'bool'>

Practical Example: Building a Profile

Let's put it all together with a real example:

# User profile data
first_name = "Alice"
last_name = "Smith"
age = 28
email = "alice.smith@email.com"
is_premium_member = True
account_balance = 150.75

# Calculate full name
full_name = first_name + " " + last_name

# Display profile
print("=" * 40)
print("USER PROFILE")
print("=" * 40)
print("Name:", full_name)
print("Age:", age)
print("Email:", email)
print("Premium Member:", is_premium_member)
print("Balance: $", account_balance)
print("=" * 40)

Output:

========================================
USER PROFILE
========================================
Name: Alice Smith
Age: 28
Email: alice.smith@email.com
Premium Member: True
Balance: $ 150.75
========================================

Key Takeaways


                   Remember These Points                          

                                                                  
   Variables store data with a name                            
     age = 25                                                     
                                                                  
   Use = for assignment (not equality)                         
     x = 10  means "x gets 10"                                   
                                                                  
   Variables can be reassigned                                 
     x = 5  then  x = 10  is perfectly fine                      
                                                                  
   Follow naming rules and conventions                         
     • snake_case for variables                                  
     • Start with letter or underscore                           
     • No keywords or special characters                         
                                                                  
   Use descriptive names                                       
     user_age is better than x                                   
                                                                  

What's Next

Now that you understand variables, let's explore the different types of data you can store in them. In the next lesson, we'll dive into Python's data types – integers, floats, strings, booleans, and more!

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service