Variables
In the last lesson, the canteen bill typed the samosa price in two places. If the price changed, you would have to find and fix every copy. Programmers solve this with variables: names that hold values, so you write a value once and use its name everywhere.
In this lesson you will create variables in Python and JavaScript, change their values while the program runs, learn the rules for naming them, and see the mistakes that trip up almost every beginner.
What is a variable?
A variable is a name that refers to a value stored in the computer's memory. Think of the contacts on your phone: you do not remember ten-digit numbers, you tap "Papa" or "Meera" and the phone finds the number. A variable name works the same way: you use the name, and the computer finds the value.
Creating a variable and giving it a value is called assignment:
samosa_price = 15
chai_price = 12
samosas = 4
chais = 2
total = samosas * samosa_price + chais * chai_price
print("Total to pay:", total)Total to pay: 84
Read samosa_price = 15 as "store 15 under the name samosa_price". The = sign does not mean "is equal to" like in maths. It is an instruction: work out the value on the right, then store it under the name on the left.
Variables in JavaScript: let and const
JavaScript asks you to announce a new variable with a keyword. Use const for a value that will not change, and let for a value that will:
const samosaPrice = 15;
const chaiPrice = 12;
let samosas = 4;
let chais = 2;
const total = samosas * samosaPrice + chais * chaiPrice;
console.log("Total to pay:", total);Total to pay: 84
If you later try to change a const, JavaScript stops with TypeError: Assignment to constant variable. That error is helpful: it protects values that should stay fixed, such as a pass mark or a tax rate. Start with const and switch to let only when the value really needs to change.
Python has no const. By custom, Python programmers write fixed values in capital letters, such as PASS_MARK = 33, as a signal to other people: "please do not change this".
Changing a variable
A variable can be given a new value at any time. The old value is replaced. A common pattern is to use the variable's current value to work out its new value:
score = 0
print("Start:", score)
score = score + 4
print("After a four:", score)
score = score + 6
print("After a six:", score)
score = score + 1
print("After a single:", score)Start: 0 After a four: 4 After a six: 10 After a single: 11
score = score + 4 means: take the current score (0), add 4, and store the answer (4) back in score. In maths, "x = x + 4" would be impossible, which shows again that = in code means "store", not "equals".
The JavaScript version uses let, because score changes:
let score = 0;
console.log("Start:", score);
score = score + 4;
console.log("After a four:", score);
score = score + 6;
console.log("After a six:", score);Start: 0 After a four: 4 After a six: 10
Notice that let appears only once, when the variable is created. After that you just use the name.
Naming rules and good names
Every language has rules for names. In both Python and JavaScript, a name:
- can contain letters, digits and the underscore
_(JavaScript also allows$); - cannot start with a digit, so
2nd_placeis not allowed butsecond_placeis; - cannot contain spaces or symbols like
-or@; - cannot be a keyword, a word the language already uses, such as
if,fororwhile; - is case-sensitive:
marks,MarksandMARKSare three different names.
Beyond the rules, choose names that explain the value. The two languages also have different habits for joining words:
| Bad name | Good name in Python | Good name in JavaScript |
|---|---|---|
x | ticket_price | ticketPrice |
n | student_count | studentCount |
tmp2 | total_marks | totalMarks |
a1 | is_member | isMember |
Python style is snake_case (lower case words joined by underscores). JavaScript style is camelCase (each new word starts with a capital letter). Code with clear names is easier to read, and easier to fix six months later.
Advanced: swapping two values
Suppose Aarav and Priya swap seats. If you write left = right first, the old value of left is lost. The classic solution uses a third, temporary variable. Python and JavaScript also have a shortcut that swaps in one line:
left = "Aarav"
right = "Priya"
# the classic way, with a temporary variable
temp = left
left = right
right = temp
print("Left:", left, "| Right:", right)
# Python's one-line swap
left, right = right, left
print("Left:", left, "| Right:", right)Left: Priya | Right: Aarav Left: Aarav | Right: Priya
In JavaScript the one-line swap is written [left, right] = [right, left];. You will meet the brackets in this style again when you learn about lists and arrays.
Common mistakes
- Using a variable before creating it.
print(total)before anytotal = ...line fails withNameError: name 'total' is not defined. JavaScript saysReferenceError: total is not defined. - A typing mistake in the name. In Python,
totl = total + 5silently creates a new variable calledtotl, andtotalstays the same. Check spellings carefully. - Writing
letagain for the same name.let score = 0;thenlet score = 4;is an error in JavaScript. Useletonce, thenscore = 4;. - Changing a
const. If a value must change, create it withlet.
Key points
- A variable is a name for a value stored in memory; assignment with
=stores the value. =means "store the value on the right under the name on the left", not "equals".- In JavaScript, use
constfor values that never change andletfor values that do. - A variable can be updated using its own old value:
score = score + 4. - Names use letters, digits and
_, cannot start with a digit, and are case-sensitive. - Python prefers
snake_casenames; JavaScript preferscamelCasenames.
Exercise
Isha gets ₹500 pocket money a month. Create variables for her pocket money, the ₹120 she spends on a movie ticket and the ₹85 she spends on snacks. Work out how much is left and print it. Then she gets ₹100 from her grandmother: update the amount left using the variable's own value and print it again. Write it in Python and in JavaScript.
Show solution
pocket_money = 500
movie_ticket = 120
snacks = 85
money_left = pocket_money - movie_ticket - snacks
print("Money left:", money_left)
money_left = money_left + 100
print("After Nani's gift:", money_left)Money left: 295 After Nani's gift: 395
const pocketMoney = 500;
const movieTicket = 120;
const snacks = 85;
let moneyLeft = pocketMoney - movieTicket - snacks;
console.log("Money left:", moneyLeft);
moneyLeft = moneyLeft + 100;
console.log("After Nani's gift:", moneyLeft);moneyLeft changes, so JavaScript creates it with let; the other three values never change, so they use const.
Quick Quiz
1. What does marks = 72 do in Python?
A single = is assignment: it stores the value on the right under the name on the left.
2. After x = 10 and then x = x + 5, what is the value of x?
The right side is worked out first using the old value (10 + 5), then stored back in x.
3. Which is a valid variable name in both Python and JavaScript?
Names cannot start with a digit or contain spaces; underscores are allowed.
4. In JavaScript, which keyword should you use for a value that never changes?
const stops the value being reassigned by mistake; let is for values that change.
Learn Intro to Programming with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
