Naming rules and changing values
🌍 In real life. At a cricket match, the scoreboard shows the runs: 0, then 10, then 25. Each time, the old number is wiped off and the new one goes up. The board's label, "Runs", never changes; only the number under it does.
Variables work like that board. And just as a scoreboard needs a clear label, a variable needs a good name that follows Python's rules.
The idea in one sentence: a variable's name must follow Python's naming rules, and giving it a new value replaces the old one.
Its words:
- keyword: a word Python keeps for itself, like
for,iforTrue - case-sensitive: small and capital letters count as different, so
scoreandScoreare two boxes - reassign: put a new value into a box that already exists
The naming rules. A name can use letters, digits and _ (underscore), but:
- it can't start with a digit
- it can't contain spaces
- it can't be a keyword
✅ age, total_price, player2
❌ 2player, total price, for
The Python habit is small letters with _ between words: total_price.
Now watch a box being reassigned, like the scoreboard:
How Python does it. Each assignment throws the old value out of the box and puts the new one in. There's no history: after score = 25, the 0 and the 10 are gone.
Python always works out the right side of = first, and only then fills the box on the left. So a variable can use its own old value: in coins = coins + 3, Python reads coins (the old 5), adds 3 to get 8, and then puts 8 back into coins.
score = 0
print(score)
score = 10
print(score)
score = 25
print(score)coins = 5
coins = coins + 3
print(coins)score = 1
Score = 99
print(score)
print(Score)2player = "Rimi"Mistakes and edge cases.
- Starting with a digit.
2player = "Rimi"givesSyntaxError: invalid decimal literal(above). - A space in a name.
total price = 5givesSyntaxError: invalid syntax. Usetotal_price. - A keyword as a name.
for = 3givesSyntaxError: invalid syntax. - Reusing a name Python already uses.
print = 5is allowed, but thenprint("hi")givesTypeError: 'int' object is not callable: your box has covered up the realprint. - Names that say nothing.
xanda2work, butpriceandtotaltell the next reader what's inside.
Quiz
Which one is a valid variable name?
- my_score
- my score
- 3rd_place
- for
What does this print?
x = 1 x = 2 print(x)What does this print?
n = 10 n = n + 5 print(n)What does this print?
name = "Ali" Name = "Sara" print(name)Which line has a mistake?
total = 0 item price = 20 print(total)
Coding tasks
Fix the variable names so that the program runs and prints
Rimi 12.levelstarts at 1. On a new line, change it to 2 (don't edit line 1). Then printlevel.moneyholds 100, and you spend 30. Updatemoneyusing its own value, then print it.