Programming Fundamentals

Variables and Data Types

**Puzzle:** A program runs `x = 5`, then `x = x + 1`. What is x now? Answering "6" means the brain has already shifted into programmer mode. Reacting with "that is nonsense, x cannot equal x+1" means there is still some unlearning to do.

In mathematics, `x = x + 1` is a contradiction. In programming, it is a routine operation. The trick: `=` here does not mean "equals", it means **"assign"**.

Цели урока

  • Understand what a variable is and how it works
  • Learn the basic data types: numbers, strings, booleans
  • Learn how to create and modify variables
  • Understand the difference between = in math and in programming

Предварительные знания

  • What is programming (lesson 1)
  • An installed development environment (lesson 2)

Instagram stores 2 billion followers_count counters. Spotify holds is_premium for 600 million users. TikTok updates view_count millions of times per second. All of it lives in variables. Without them, a program is a calculator with no memory.

  • **Instagram**: the variable `followers_count` stores the follower count, updated on every follow
  • **Games**: `player_health = 100`, `player_score = 0` - player state in every frame
  • **Banks**: `balance = 15000.50` - account balance, float type matters for precision
  • **Spotify**: `is_premium = True` - one bool controls access to 80 million tracks

John Backus, IBM, and the named variable

Before 1957, programmers worked at the metal. Each value sat at a numeric memory address (octal 04217, decimal 2191), and the code juggled those addresses by hand. In 1957, IBM shipped Fortran (Formula Translation), built by John Backus and his team over three years. Fortran let people write `VELOCITY = DISTANCE / TIME` instead of LOAD-STORE machine sequences. The compiler picked the memory address and tracked it. The skeptics did not believe a compiler could match a human assembler programmer, so Fortran shipped with side-by-side benchmarks. The compiled code matched, and sometimes beat, hand-written assembly. By 1960 the named variable was the default everywhere. ALGOL 60 added scope and block structure, C inherited types from BCPL, Python (1991) inferred them. The mechanism Backus introduced (a name pointing to a memory slot holding a value) has not changed in 70 years.

What Is a Variable?

**A variable** is a named memory cell. Picture a labeled box: the label is the name, the contents are the value. Python stores every variable as a heap object with a reference counter - a simple `x = 5` creates an int object and binds the name to its address.

Creating a variable

Assignment syntax

```python # Create a variable age with the value 25 age = 25 # Create a variable name with the value "Alice" name = "Alice" # Print the values print(age) # 25 print(name) # Alice ```

The **`=` operator** in programming is NOT equality - it is **assignment**. Read `x = 5` as "put 5 into the box named x" or "x becomes 5".

Changing a variable

Values can change

```python score = 0 # Starting score print(score) # 0 score = 10 # Earned 10 points print(score) # 10 score = score + 5 # Added 5 more print(score) # 15 ``` The last line: take the old value (10), add 5, and put the result back (15).

What will the code print: `x = 10; x = x * 2; print(x)`?

Naming Rules

A variable name carries weight like a function name in a public API. A bad one becomes years of technical debt. Google Style Guide, PEP 8, Airbnb JavaScript Style all dedicate full sections to naming. Reason: readability beats every other optimization.

Naming rules in Python

What's allowed and what's not

**Allowed:** - Letters (a-z, A-Z), digits (0-9), underscores (_) - Start with a letter or underscore - Any length **Not allowed:** - Starting with a digit: `2name` ❌ - Spaces: `my name` ❌ - Special characters: `my-name`, `my@name` ❌ - Reserved keywords: `if`, `for`, `class` ❌

Good vs bad names

Style matters

```python # Bad - unclear what these represent x = 25 a = "Alice" temp = 100 # Good - immediately obvious user_age = 25 user_name = "Alice" max_score = 100 ```

In Python the convention is **snake_case**: words separated by underscores, all lowercase. Examples: `player_score`, `is_logged_in`, `total_price`. JavaScript prefers camelCase - different languages, different conventions.

Which variable name is INVALID?

Data Types

Data shows up in different shapes: numbers, text, true/false. Python infers the **type** from the value automatically. A type is more than a label. A Python int weighs 28 bytes, a float 24, and bool inherits from int. TypeScript bolted static typing onto JavaScript for one reason: runtime type errors are expensive.

TypeNameExamples
intInteger42, -7, 0, 1000000
floatFloating-point number3.14, -0.5, 2.0
strString (text)"Hello", 'World', "123"
boolBooleanTrue, False

Type examples

How Python distinguishes types

```python age = 25 # int (integer) price = 99.99 # float (decimal) name = "Alice" # str (string) is_student = True # bool (boolean) # Check the type with the type() function print(type(age)) # <class 'int'> print(type(price)) # <class 'float'> print(type(name)) # <class 'str'> print(type(is_student)) # <class 'bool'> ```

**"25" and 25 are not the same!** The first is a string (text), the second is a number. Mixing them fails: `"25" + 5` raises TypeError. Stripe would bleed money if Python converted types silently.

Python automatically converts "5" + 5 to 10

Python does NOT convert types automatically - a TypeError will be raised

Python is strict about types. To add the string "5" to the number 5, explicit conversion is needed: int("5") + 5 = 10 or "5" + str(5) = "55".

What type is the value "3.14"?

Type Conversion

Sometimes a string has to become a number, or the other way around. Conversion functions handle that. Python's `input()` always returns a string - even when the user types "42". A deliberate design call: the input layer cannot guess the intent, so it hands back text.

Conversion functions

From one type to another

```python # String -> Number text = "42" number = int(text) # 42 (integer) decimal = float(text) # 42.0 (float) # Number -> String age = 25 age_text = str(age) # "25" # Number -> Boolean bool(0) # False bool(42) # True (any non-zero) bool("") # False (empty string) bool("Hi") # True (non-empty string) ```

Why does this matter?

A practical example

```python # The user enters their age (input always returns a string!) age_input = input("How old? ") # "25" # To calculate a birth year, a number is needed age = int(age_input) birth_year = 2024 - age print("Born in", birth_year) ```

Not every string can be converted to a number! `int("hello")` raises ValueError. The string must contain only digits.

What will print("Score: " + str(100)) output?

Where this lesson sits in the curriculum

Variables are the storage atom. The next lessons add operations and structure on top:

  • Operators — Once values are stored, arithmetic and logical operators act on them
  • Strings — str is one of the four basic types from this lesson, with its own toolset
  • Conditionals — bool variables drive if/else branching
  • Arrays — When one variable is not enough, arrays group many of them under one name

Key Takeaways

  • **Variable** - a named memory cell for storing data
  • **`=`** - the assignment operator, not equality: puts a value into the box
  • **Types**: int (integer), float (decimal), str (string), bool (boolean)
  • **Type conversion**: int(), float(), str(), bool() - explicit, never automatic
  • **snake_case** - Python naming convention: `user_age`, `is_premium`
  • A variable name is an API: a bad name becomes technical debt

Вопросы для размышления

  • A banking app stores a user's account balance. Which type should a developer choose - int or float? What happens when the wrong type is used in financial calculations?

Связанные уроки

  • se-01 — Variables are the foundation; SE explains how to organize them in modules
  • alg-01-big-o — Algorithm analysis requires understanding types and their memory cost
  • ds-03-stacks — The call stack is a vivid example of variables in different scopes
  • ct-01 — Logical thinking helps grasp assignment vs equality
  • arch-01-binary
Variables and Data Types

0

1

Sign In