Values and types¶
// ints are 64-bit and floats are IEEE 754 doubles
count = 3
price = 2.5
print(count * 2, price * 2.0)
// int division truncates toward zero
print(7 / 2, -7 / 2, 7.0 / 2.0)
// ints and floats never mix, so convert one side
total = price * float(count)
print(total, int(total))
// bools, strings, and none
ready = count > 2
name = "stone"
print(ready, not ready, name + "!", name.len())
print(none)
// floats print the way Python shows them
print(0.1 + 0.2, 1e16, 1.0 / 3.0)
prints
6 5.0
3 -3 3.5
7.5 7
true false stone! 5
none
0.30000000000000004 1e+16 0.3333333333333333
The types¶
type |
examples |
notes |
|---|---|---|
|
|
64-bit signed; overflow wraps, but dividing |
|
|
IEEE 754 double |
|
|
|
|
|
double quotes only, no escape sequences, cannot span lines |
|
|
what a function without |
|
|
see Lists |
You never write types down. The checker infers each variable’s type from what is assigned to
it, and a variable keeps that type: assigning "a" to a variable that holds an int is an
error.
Arithmetic¶
+, -, *, and / work on two ints or two floats, and + also joins two strings. stone
never converts between int and float on its own, so price * count with a float price and
an int count is an error. Convert explicitly with float(count) or int(price). int() drops
the fraction, so int(-2.5) is -2.
Division of ints truncates toward zero, as in C, so -7 / 2 is -3 rather than Python’s -4.
Dividing by zero, whether by 0 or 0.0, stops the program with division by zero.
There is no % operator yet; compute a % b as a - a / b * b.
Printing¶
print takes any number of values, prints them separated by spaces, and ends the line. Floats
print the way Python’s repr shows them: the shortest digits that read back as the same float,
which is why 0.1 + 0.2 prints as 0.30000000000000004.
Next, Control flow.