Free lesson · Module 1, lesson 6 of 8

Variables: labelled boxes for values

Store, read and update a value in a variable, trace a program that reassigns one, and choose names Python accepts and a reader understands.

The video for this lesson is being prepared

About 10 minutes, narrated in English, Hindi and Odia. The notes and the quiz below are open now.

Lesson notes

A variable is a labelled box

  • wallet = 500 stores 500 in a box named wallet
  • Read = as "store" or "becomes": Python works out the right side first, then fills the box on the left
  • Use the name to read the value: print(wallet) shows what the box holds now
  • Reading a name that was never stored gives a NameError

Updating a box

  • wallet = wallet - 120 reads the old value, subtracts 120 and stores the result
  • A box holds one value: a new value replaces the old one
  • A box holds a value, not a formula: bill = cups * price does not change when cups changes later

Names

  • Letters, digits and underscores only: total_marks, price2
  • No spaces, and never a digit first: total marks and 2nd_place are SyntaxErrors
  • Case matters: Total and total are two different boxes
  • Words that belong to Python cannot be names: class, for, if
  • Say what the box holds: total_marks, not t

Trace table

  • One column per box, one row per line
  • When a line stores a new value, cross out the old one in that column

The trap

  • = does not mean the two sides are equal; testing for equal is ==, in module 2
  • To swap two boxes, first copy one value into a third box

Code to try (Colab or Visual Studio Code)

wallet = 500
wallet = wallet - 120
wallet = wallet + 50
print(wallet) # 430

first_drink = "tea"
second_drink = "coffee"
first_drink = second_drink
second_drink = first_drink
print(first_drink, second_drink) # coffee coffee

cups = 2
price = 15
bill = cups * price
cups = cups + 1
print(bill) # 30

Lesson quiz

Checked in your browser. Nothing is sent or saved.

5 questions

Question 1 · easy

Arjun hits three sixes in an over. What does this program print?

print("6" * 3)

Question 2 · easy

Which of these is a Boolean value, the kind type() names bool?

Question 3 · medium

An auto charges ₹30 to start plus ₹12 a kilometre. Sameer's trip is 8 km, then he adds 5 km more. What does this program print?

km = 8
fare = 30 + km * 12
km = km + 5
print(km, fare)

Question 4 · medium

Asha wants her program to show her cricket score. What happens when it runs?

score = 46
print("Asha scored " + score)

Question 5 · hard

Arjun scores 48 runs in the first match and 35 in the second. He expects this program to print 83, but it prints 48. Why?

total_runs = 0
total_runs = total_runs + 48
Total_runs = total_runs + 35
print(total_runs)

Numbers, text and true or falseNext: Asking the user: input and conversion