Variables
A variable gives a name to a value, so you can use it later:
price = 2.5
quantity = 3
total = price * quantity # 7.5
Think of it as a label stuck on a value, not a box with the value inside. price = 3.0 moves the label to a new value. In most languages you can reassign a variable; many also let you declare one that can’t be reassigned, like const in JavaScript, or every plain let in Rust.
Types
Every value has a type, which decides what operations make sense.
| Type | Examples | Typical operations |
|---|---|---|
| Integer | 3, -42 |
Arithmetic, counting, indexing |
| Float | 2.5, 0.1 |
Arithmetic with fractions |
| String | "hello", "3" |
Joining, slicing, searching |
| Boolean | true, false |
and, or, not, deciding branches |
| List or array | [1, 2, 3] |
Indexing, looping; see arrays |
"3" and 3 are different values of different types. One is text that happens to show a digit; the other is a number. Text from a user, a file or a web form always arrives as a string, and has to be converted before you can do maths with it.
Converting between types
The example converts a quantity typed by a user into a number, multiplies it by a price, and rounds the result. Watch how each language handles text that isn’t a number.
def order_total(quantity_text, unit_price):
quantity = int(quantity_text) # the text "3" becomes the integer 3
total = quantity * unit_price # an int times a float gives a float
return round(total, 2) # floats aren't exact: 12 * 0.1 is 1.2000000000000002function orderTotal(quantityText, unitPrice) {
const quantity = Number(quantityText); // the text "3" becomes the number 3
if (quantityText.trim() === '' || !Number.isInteger(quantity)) {
throw new TypeError(`not a whole number: ${JSON.stringify(quantityText)}`);
}
const total = quantity * unitPrice; // JavaScript has one number type for both
return Math.round(total * 100) / 100; // 12 * 0.1 is 1.2000000000000002
}import (
"math"
"strconv"
)
func orderTotal(quantityText string, unitPrice float64) (float64, error) {
quantity, err := strconv.Atoi(quantityText) // the text "3" becomes the int 3
if err != nil {
return 0, err // "three" isn't a number, and Go makes you handle that
}
total := float64(quantity) * unitPrice // Go won't multiply an int by a float64 without converting
return math.Round(total*100) / 100, nil // 12 * 0.1 is 1.2000000000000002
}fn order_total(quantity_text: &str, unit_price: f64) -> Result<f64, std::num::ParseIntError> {
let quantity: i32 = quantity_text.parse()?; // the text "3" becomes the i32 3
let total = quantity as f64 * unit_price; // Rust needs an explicit conversion too
Ok((total * 100.0).round() / 100.0) // 12 * 0.1 is 1.2000000000000002
}- Python raises an error you can catch.
- JavaScript’s
Number("three")givesNaN(“not a number”) instead of failing, andNumber("")gives0, so the code checks explicitly. - Go returns an error value next to the result, and the compiler makes you deal with it.
- Rust returns a
Resultthat is either the number or the error, and the?passes the error on.
Static vs dynamic typing
| Static (Go, Rust, Java, TypeScript) | Dynamic (Python, JavaScript, Ruby) | |
|---|---|---|
| When types are checked | Before the program runs | While it runs |
| A type mistake shows up | As a compile error | As a crash, when that line runs |
| Variables | Have a fixed type | Can hold any type |
| Feels | Stricter, more upfront | Quicker to start |
Many dynamic languages now support optional type hints, like Python’s annotations and TypeScript for JavaScript, which get some of the safety without giving up the flexibility.
Why 0.1 + 0.2 isn’t 0.3
Floats are stored in binary, and most decimal fractions, like 0.1, have no exact binary form, just as 1/3 has no exact decimal form. Tiny rounding errors creep in: 12 * 0.1 is 1.2000000000000002. That’s why the example rounds, and why money is usually stored as whole cents, or in a decimal type, rather than as floats.
Common mistakes
- Adding text and numbers.
"3" + 1is"31"in JavaScript and an error in Python. Convert first. - Comparing floats with
==. Check whether the difference is tiny instead:abs(a - b) < 1e-9. - Integer overflow. In Go, Rust, Java and C, integers have a fixed size. Go past the maximum and the value wraps around, or the program stops. Python integers grow as needed.
Check yourself
Check yourself
In Python, what is the type of input() when the user types 42?
Input from a user always arrives as text. You need int(...) to turn "42" into the number 42.
Check yourself
Which kind of language reports a type mistake before the program runs?
A statically typed language checks types when it compiles, so a mismatch is an error before anything runs.
Sources
- David Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic,” ACM Computing Surveys 23, no. 1 (1991): 5–48.
- Benjamin C. Pierce, Types and Programming Languages (2002), chapter 1.
Finished this page?
Your list