beginner

Variable Assignment

Learn to store and manipulate data using Python variables

Variables are fundamental to programmingβ€”they act as labeled containers that store data values in your computer's memory. In Python, variables are created the moment you first assign a value to them.

πŸ“š Concepts & Theory

A variable in Python is created using the assignment operator (=). The variable name goes on the left, and the value goes on the right.

Variable Naming Rules

    • Must start with a letter or underscore (_)
    • Can contain letters, numbers, and underscores
    • Case-sensitive (name β‰  Name β‰  NAME)
    • Cannot be Python keywords (if, for, class, etc.)

Naming Conventions (PEP 8)

    • Use lowercase with underscores: user_name, total_count
    • Be descriptive: age instead of a
    • Constants in ALL_CAPS: MAX_SIZE, PI

Data Types

name = "Alice"      # String (str)
age = 25            # Integer (int)
height = 5.6        # Float (float)
is_student = True   # Boolean (bool)

Multiple Assignment

x = y = z = 0           # Same value to multiple variables
a, b, c = 1, 2, 3       # Multiple values at once
name, age = "Bob", 30   # Mixed types

Dynamic Typing

Python figures out the type automatically. You can even change a variable's type:

x = 10      # x is an integer
x = "ten"   # x is now a string

🎯 Your Challenge

Create two variables: one called "name" containing a string, and one called "age" containing an integer. Then print both values using a single print() statement.

πŸ“ Starter Code

Python
name = ""
age = 0
print(name, age)
  • Use = for assignment (variable = value)
  • Strings need quotes, numbers don't
  • print() can display multiple values separated by commas

Solution

Python
name = "Alice"
age = 25
print(name, age)

Explanation

This solution creates two variables: name stores a string (text in quotes), age stores an integer (whole number). The print() function accepts multiple arguments separated by commas.

⚠️ Common Mistakes to Avoid

  • Putting numbers in quotes ("25" instead of 25)
  • Using spaces in variable names (my name instead of my_name)
  • Starting variable names with numbers
  • Forgetting quotes around strings

❓ Frequently Asked Questions

A variable is a named container that stores a data value in memory. You create variables using the assignment operator (=), and you can change their values throughout your program.
No, Python uses dynamic typing. The interpreter automatically determines the type based on the value you assign.
Strings are text enclosed in quotes ("hello"), while integers are whole numbers without quotes (42). Strings are for text; integers are for counting and arithmetic.

πŸ”— Related Concepts