Lessons 22–23 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
22
Describing variables in Python
Textbook: pp. 54–57
GoalKnows the Python alphabet and the rules for identifiers and variable names, does not use keywords as names, and assigns and changes the value of a variable.
New words
variable: a named cell in computer memory that holds a value and may change it while the program runs · o‘zgaruvchiidentifier: the name of a variable, constant, function or module · identifikatorkeyword (reserved word): a word such as if, for, while that has a fixed meaning and cannot be used as a name · xizmatchi so‘zconstant: a name for a value that is meant not to change; written in capital letters · doimiy
Explanation
The Python alphabet consists of capital and small Latin letters, the digits 0 to 9, special signs (operations, brackets, punctuation) and keywords. A variable is a named cell in memory whose value can be replaced while the program runs; its name is called an identifier. An identifier starts with a letter or an underscore (_) and may contain letters, digits and underscores inside; spaces, hyphens (–), # and @ are not allowed, and words are joined with an underscore, for example yosh_1. Capital and small letters are different, so son, Son and SON are three different names; keywords (if, for, while, def, return and others) cannot be names. A value is given with the “=” sign: the name stands on the left and the value on the right, and this is an assignment, not an equation. When a new value is given the old one is lost; the line b = a copies the current value of a, and if a changes later, b stays the same. Values that must not change (constants) are usually written in capital letters only, for example PI = 3.14.
Worked examples
Changing the value of a variable: ball = 72 ⏎ print(ball) ⏎ ball = 85 ⏎ print(ball) First 72 appears on the screen, and then 85, because a new value was given.
Copying: x = 4 ⏎ y = x ⏎ x = 9 ⏎ print(x, y) y receives the value x had at that moment (4); even after x is given 9, y stays 4, so 9 4 is printed.
Class activity
“Name judge”: students write names on cards (yosh_1, 2son, my-age, class, Yosh, ism familiya). The group sorts each as “valid” or “invalid” and gives the reason.
Practice
1
Which of these names are valid identifiers: narx_1, 1narx, narx 1, narx-1, Narx?
narx_1 and Narx. The others are wrong: one starts with a digit, one has a space, one has a hyphen.
2
After a = 5, b = a, a = 7 are carried out, what is b equal to?
5
3
Create two variables: ism with the value “Ali” and yosh with the value 14. Print both.
ism = "Ali" ⏎ yosh = 14 ⏎ print(ism) ⏎ print(yosh)
4
Why are son and Son not the same variable?
Python tells capital and small letters apart, so these are two different names.