Free

2: The Alphabet and Vocabulary of Programming

⏱️ 55-70 minutes
📊 intermediate

Review this chapter

Chapter 6: variables — cards

Spaced repetition cards for this chapter

Sign in to practice

Sign in to practice

Chapter 6: "Variables: Magic Memory Boxes"

Professor Bit brought several colorful boxes of different sizes and shapes into the room and placed them on the table in front of Alice.

— Today we'll talk about something very important in programming — variables, — the Professor began. — Imagine that a computer needs to remember information during program execution. How does it do this?

Alice thought:
— Probably writes it somewhere?

— Right! — the Professor nodded. — A computer stores information in special memory cells. And to make it convenient for programmers to work with these cells, variables were invented.

The Professor took a blue box and wrote "age" on it:
— A variable is like a box with a name. You can put some value in it and then use it by referring to the box's name.

He put a card with the number 12 in the box.

The “age” variable — a box with the number 12

— Look, I created a variable named "age" and assigned it the value 12. In programming, this is written like this:


age = 12

— So a variable is just a container for storing information? — Alice asked.

— Exactly! — the Professor was pleased. — And just as you can put different things in real boxes, you can write different information in variables.

Мама хочет, чтобы в доме было чисто,
Закатав повыше оба рукава,
В первый ящик собирает только числа,
Во второй — бросает буквы и слова.

Попадаются забавные предметы,
Суть которых сразу точно не поймёшь:
Там, где прячутся вопросы и ответы,
Где меняется то «Истина», то «Ложь».

Третий ящик оставляет пустоватым,
И сама не может вспомнить, для чего.
Но порой нужней, чем слитки и дукаты,
Неизвестность, пустота и «Ничего».

А четвёртый в дикой спешке пропустила,
Увлеклась и отложила все дела.
Ничего туда она не положила
И Значения ему не придала!

Дальше тащит мама ящик нестандартный,
В нём пустых коробок маленьких не счесть.
Разложила кольца, бусинки и карты,
И на каждой подписала, что в ней есть.

А потом, составив стопки аккуратно,
В тот МАССИВНЫЙ ящик хочет положить,
Чтобы всё вокруг смотрелось так опрятно,
И известно было: где и что лежит.

Наступила чистота и оживленье,
Беспорядок окончательно решён.
ПЕРЕМЕННЫЕ приносят наслажденье,
Каждый ящик новым смыслом наделён!

Byte took a red box and wrote "name" on it:
— In this box you can put text! — He put a card with the word "Alice" in the box.

— In programming, this looks like this, — the Professor explained:


name = "Alice"

— The quotes show that this is text, or, as programmers say, a string, — he added.

— What else can you store in variables? — Alice wondered.

— Almost everything! — The Professor began showing different boxes: — Numbers, text, lists, true or false, dates, even entire data structures.

Byte shows the variable “name” = “Alice” in a red box

Logic flew down to the table:
— In different programming languages, variables can behave differently. In some languages, a variable can only store a certain type of data — only numbers or only text. In other languages, the variable type can change.

— Why are variables needed? — Alice asked. — Why can't we just write values directly?

— Great question! — The Professor took several boxes. — Imagine we're writing a program to calculate the cost of a taxi ride. The base cost is 100 rubles, and each kilometer costs 20 rubles.

He wrote a formula on the board:


cost = basecost + distance * priceper_kilometer

— If we know that the distance is 5 kilometers, then:


cost = 100 + 5 * 20 = 200 rubles

— But what if the price per kilometer changes? — the Professor continued. — If we use variables, we only need to change one value:


base_cost = 100
priceperkilometer = 20
distance = 5
cost = basecost + distance * priceper_kilometer

— And if we wrote the formula without variables:


cost = 100 + 5 * 20

— then when the price changes, we'd have to rewrite the entire formula, which is prone to errors, — he finished.

— I see! — Alice exclaimed. — Variables make the program more flexible and understandable!

— Exactly! — the Professor confirmed. — In addition, variables allow:

1. Storing intermediate calculation results
2. Making code more readable and understandable
3. Saving time and space when the same value is used multiple times

Byte pulled out another box and put a card with the number 10 in it:
— Look, I created a variable "x" with the value 10. And now I can change its value!

He took out the card and put in a new one with the number 20:
— Now x = 20. This is the main difference between variables and constants — their value can change during program execution.

— In programming, this looks like this, — the Professor explained:


x = 10 # First x equals 10
print(x) # Will output: 10
x = 20 # Now x equals 20
print(x) # Will output: 20

— What do these # symbols mean? — Alice asked.

— These are comments, — the Professor replied. — They help explain code, but the computer ignores them when executing the program. It's like margin notes for programmers.

Logic pointed her wing at the taxi formula:
— Notice how variable names describe what's stored in them: "basecost", "priceper_kilometer". Good variable names make code clearer, just like good labels on boxes help find the right thing.

— What about bad names? — Alice wondered.

— For example, a = 100, b = 20, c = 5, d = a + c * b, — said the Professor. — Technically the code is correct, but it's completely unclear what these letters mean.

— Yes, it's much harder to understand what's happening, — Alice agreed.

— And now, — the Professor pulled out a few more boxes, — let's practice using variables.

Task

Imagine you're creating a program to track your pocket money. What variables will you need? Come up with and write down 5-7 variables with appropriate names and values. For example:


savings = 500
weeklypocketmoney = 100
icecreamprice = 50

Then come up with simple formulas with these variables, for example: "How many ice creams can I buy with my savings?"