📦 Lesson 2.1: Variables and Constants
Teach your programs to remember things — how all three languages store, name, and protect data.
🎯 Learning Objectives
By the end of this lesson, you will be able to:
- Explain what a variable is and why programs need them
- Create variables in Python, JavaScript, and C#
- Understand the difference between
let,const,varin JavaScript - Create constants (values that don't change) in all three languages
- Follow naming conventions for each language
Estimated Time: 45 minutes
Project: A program that stores and displays personal info using variables
📑 In This Lesson
What Is a Variable?
A variable is a named container for a piece of data. Think of it like a labeled box: you give the box a name, put something inside it, and later you can look at or change what's inside by referring to the name.
Contains: 25"] C["name = 'Alex'"] --> D["📦 name
Contains: 'Alex'"] style B fill:#3b82f6,stroke:#1e40af,color:#fff,stroke-width:2px style D fill:#6366f1,stroke:#4338ca,color:#fff,stroke-width:2px
Without variables, programs couldn't remember anything between steps. You'd have to hard-code every value, and nothing could change while the program runs.
📖 Key Term
Variable: A named storage location in your program's memory. It has a name (how you refer to it), a value (what's stored), and a type (what kind of data it holds).
Creating Variables
Here's how you create (or declare) a variable in each language:
# Python: just assign a value — no keyword needed
name = "Alex"
age = 25
is_student = True
print(name) # Alex
print(age) # 25
print(is_student) # True
// JavaScript: use let or const to declare
let name = "Alex";
let age = 25;
let isStudent = true;
console.log(name); // Alex
console.log(age); // 25
console.log(isStudent); // true
// C#: declare the type before the name
string name = "Alex";
int age = 25;
bool isStudent = true;
Console.WriteLine(name); // Alex
Console.WriteLine(age); // 25
Console.WriteLine(isStudent); // True
Key Differences
| Feature | 🐍 Python | ⚡ JavaScript | 🔷 C# |
|---|---|---|---|
| Declaration keyword | None — just assign | let (or const) |
Type name (e.g., int) |
| Type specified? | No — Python infers it | No — JavaScript infers it | Yes — you must state it |
| Boolean values | True / False |
true / false |
true / false |
⚠️ Python's Capitalized Booleans
Python uses True and False with capital letters. JavaScript and C# use lowercase true and false. This is a common source of errors when switching between languages!
🎓 Instructor Note: Delivery Guidance
The biggest conceptual leap for true beginners is the idea that = means "assign" not "equals." Use the box/label analogy heavily. Demonstrate in the Python REPL (type python in terminal) — it's the fastest way to show live variable creation. Have students type along in their own REPL before moving to files.
Changing Values
Variables are called "variables" because their values can vary — you can change them after creation:
# Python: reassign freely — even change the type!
score = 0
print(score) # 0
score = 100
print(score) # 100
# Python even lets you change the type
score = "one hundred"
print(score) # one hundred (now it's a string!)
// JavaScript with let: reassign freely
let score = 0;
console.log(score); // 0
score = 100;
console.log(score); // 100
// JavaScript also lets you change the type
score = "one hundred";
console.log(score); // one hundred
// C#: reassign to same type only
int score = 0;
Console.WriteLine(score); // 0
score = 100;
Console.WriteLine(score); // 100
// This would cause an ERROR in C#:
// score = "one hundred";
// Cannot convert string to int!
💡 Key Insight: Python and JavaScript let you change a variable's type freely. C# locks the type at declaration — once anint, always anint. This is the core difference between dynamic and static typing.
Constants
A constant is like a variable that you're not allowed to change after it's set. Use constants for values that should stay fixed, like the speed of light or the number of days in a week.
# Python: no true constants — use ALL_CAPS by convention
# Other programmers know not to change these
MAX_SPEED = 299792458 # speed of light in m/s
PI = 3.14159
DAYS_IN_WEEK = 7
# Nothing stops you from changing it (Python trusts you)
# MAX_SPEED = 0 # technically works, but DON'T do this
print(f"Speed of light: {MAX_SPEED} m/s")
// JavaScript: use const instead of let
const MAX_SPEED = 299792458;
const PI = 3.14159;
const DAYS_IN_WEEK = 7;
// Trying to change a const causes an ERROR:
// MAX_SPEED = 0; // TypeError: Assignment to constant variable
console.log(`Speed of light: ${MAX_SPEED} m/s`);
// C#: use the const keyword before the type
const int MaxSpeed = 299792458;
const double Pi = 3.14159;
const int DaysInWeek = 7;
// Trying to change a const causes a COMPILE ERROR:
// MaxSpeed = 0; // Error: cannot assign to const
Console.WriteLine($"Speed of light: {MaxSpeed} m/s");
Constants Compared
| Feature | 🐍 Python | ⚡ JavaScript | 🔷 C# |
|---|---|---|---|
| Constant keyword | None (convention only) | const |
const |
| Enforced? | No — honor system | Yes — runtime error | Yes — compile error |
| Naming convention | ALL_CAPS |
ALL_CAPS or camelCase |
PascalCase |
✅ Best Practice: Use Constants Generously
If a value shouldn't change, make it a constant. In JavaScript, many developers use const by default and only switch to let when they need to reassign. This makes your code easier to understand and less prone to bugs.
Naming Rules and Conventions
Every language has rules about what variable names are allowed and conventions about what names are good practice.
Universal Rules (All Three Languages)
- Names can contain letters, numbers, and underscores
- Names cannot start with a number (
2fastis invalid;fast2is fine) - Names are case-sensitive (
age,Age, andAGEare three different variables) - Names cannot be reserved words (like
if,for,class)
Naming Conventions by Language
# Python uses snake_case for variables and functions
first_name = "Alex"
last_name = "Johnson"
birth_year = 1998
is_enrolled = True
# Constants use ALL_CAPS
MAX_RETRIES = 3
DATABASE_URL = "localhost:5432"
# Classes use PascalCase (you'll learn about these later)
# class StudentProfile:
// JavaScript uses camelCase for variables and functions
let firstName = "Alex";
let lastName = "Johnson";
let birthYear = 1998;
let isEnrolled = true;
// Constants often use ALL_CAPS (but camelCase is also fine)
const MAX_RETRIES = 3;
const databaseUrl = "localhost:5432"; // also acceptable
// Classes use PascalCase
// class StudentProfile {}
// C# uses camelCase for local variables
string firstName = "Alex";
string lastName = "Johnson";
int birthYear = 1998;
bool isEnrolled = true;
// Constants use PascalCase
const int MaxRetries = 3;
const string DatabaseUrl = "localhost:5432";
// Classes and public members use PascalCase
// class StudentProfile {}
💡 Good Variable Names
A good variable name tells you what the data represents. Compare:
x = 25— bad (what is x?)age = 25— good (clearly an age)student_age = 25— even better (whose age?)
Spend the extra seconds to choose clear names — you (and your teammates) will thank yourself later.
Dynamic vs. Static Typing
This is one of the most important differences between the three languages and one of the main reasons we included C# in this course:
🐍⚡ Dynamic Typing (Python & JavaScript)
You don't declare types. The language figures out the type from the value. You can change a variable's type at any time. Errors related to wrong types happen at runtime (when the program runs).
🔷 Static Typing (C#)
You declare the type of every variable. Once a variable has a type, it keeps it forever. Type errors are caught at compile time (before the program runs), which means fewer surprises.
# Python: check types at runtime with type()
value = 42
print(type(value)) # <class 'int'>
value = "hello"
print(type(value)) # <class 'str'>
# No error — Python is fine with this!
// JavaScript: check types at runtime with typeof
let value = 42;
console.log(typeof value); // "number"
value = "hello";
console.log(typeof value); // "string"
// No error — JavaScript is fine with this!
// C#: type is fixed at declaration
int value = 42;
Console.WriteLine(value.GetType()); // System.Int32
// This would NOT compile:
// value = "hello";
// Error: Cannot convert string to int
// C# also has 'var' for type inference:
var inferred = 42; // C# figures out it's an int
// But it's still locked as int after this!
✅ C#'s var Keyword
C# has a var keyword that lets the compiler infer the type from the value. But unlike Python/JavaScript, the type is still locked once inferred. var x = 42; means x is permanently an int. It's a convenience, not dynamic typing.
Exercises
🏋️ Exercise 1: Personal Info Card
Objective: Create variables that store your personal info and display them.
- Create variables for: your name, age, city, and whether you like coffee (boolean)
- Print all four values with descriptive labels
- Try it in all three languages
✅ Solution
name = "Alex"
age = 25
city = "Denver"
likes_coffee = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
print(f"Coffee lover: {likes_coffee}")
let name = "Alex";
let age = 25;
let city = "Denver";
let likesCoffee = true;
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`City: ${city}`);
console.log(`Coffee lover: ${likesCoffee}`);
string name = "Alex";
int age = 25;
string city = "Denver";
bool likesCoffee = true;
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"City: {city}");
Console.WriteLine($"Coffee lover: {likesCoffee}");
🏋️ Exercise 2: Swap Two Variables
Objective: Given two variables a and b, swap their values so a has what b had and vice versa.
- Start with
a = 10andb = 20 - After the swap,
ashould be 20 andbshould be 10 - Print both values before and after the swap
💡 Hint
In most languages, you need a temporary variable to hold one value while you swap. Python has a special shortcut!
✅ Solution
a = 10
b = 20
print(f"Before: a={a}, b={b}")
# Python shortcut — no temp variable needed!
a, b = b, a
print(f"After: a={a}, b={b}")
let a = 10;
let b = 20;
console.log(`Before: a=${a}, b=${b}`);
// Method 1: Classic swap with temp variable
let temp = a;
a = b;
b = temp;
// Method 2: Destructuring (modern JS)
// [a, b] = [b, a];
console.log(`After: a=${a}, b=${b}`);
int a = 10;
int b = 20;
Console.WriteLine($"Before: a={a}, b={b}");
// Classic swap with temp variable
int temp = a;
a = b;
b = temp;
// C# also supports tuple swap:
// (a, b) = (b, a);
Console.WriteLine($"After: a={a}, b={b}");
🎓 Instructor Note: Delivery Guidance
Exercise 1 is the must-do. The f-string/template literal syntax (the f"" / `${}` / $"" patterns) is important — students will use it constantly. Don't over-explain string interpolation here; just show it in action and tell them we'll cover it in depth in the next lesson. Exercise 2 is a classic puzzle that introduces the concept of sequential execution — order matters in code.
Summary
🎉 Key Takeaways
- Variables are named containers for data — you create them, use them, and change them
- Python: just assign (
x = 5). JavaScript: useletorconst. C#: declare the type (int x = 5;) - Constants are values that don't change — Python uses naming convention, JS/C# use
const - Python and JavaScript are dynamically typed (flexible types). C# is statically typed (fixed types)
- Python uses
snake_case, JavaScript usescamelCase, C# usescamelCasefor locals andPascalCasefor constants - Choose descriptive names — future you will appreciate it
🚀 What's Next?
You know how to store data — now let's explore what kinds of data you can store. In the next lesson, we'll dive into data types: numbers, strings, and booleans.
🎯 Quick Check
Question 1: In JavaScript, what's the difference between let and const?
Question 2: What happens if you try to assign a string to an int variable in C#?