Python · Chapter 2 of 21
Python variables, input and numbers: int, float and bool
14 min study · Examples checked with Python 3.14 and 3.15 ·
Everything a Python program works with is an object: a number, a piece of text, a list, a function. Every object has a type, and the type decides what you can do with it. This chapter covers how names attach to objects, how to turn keyboard input into numbers, and the arithmetic rules that most often surprise people coming from other languages.
Names point at objects
An assignment binds a name to an object. The name has no type of its own; the object does.
lesson_count = 12
hours_per_week = 4.5
course = "Python basics"
is_published = True
mentor = None
print(type(lesson_count)) # <class 'int'>
print(type(hours_per_week)) # <class 'float'>
print(type(course)) # <class 'str'>
print(type(is_published)) # <class 'bool'>
print(type(mentor)) # <class 'NoneType'>
lesson_count = "twelve" # allowed: the name now points at a str
print(type(lesson_count)) # <class 'str'>
That last rebinding is legal, which is what “dynamically typed” means. It is also a good way to confuse readers, so keep one kind of value per name. Pick descriptive snake_case names such as hours_per_week, and avoid names that hide built-in functions: a variable called list, sum or input breaks every later use of that function in the same scope.
None is the object that means “no value”. It is different from 0, "" and False, which are real values that can mean something. A mentor of None means nobody is assigned; a score of 0 means the learner scored nothing.
Python has no constants enforced by the language. By convention, a name written in capitals, such as MAX_LEARNERS = 30, should not be reassigned.
Several assignments at once
Python can assign several names in one statement, and it evaluates the whole right-hand side before binding anything. That makes swapping two values a one-liner:
first, second = "draft", "published"
first, second = second, first
print(first, second) # published draft
start = end = 0 # both names point at the same int
total = 1_250_000 # "_" groups digits for readability
print(total) # 1250000
Two names can refer to the same object. With numbers and strings this never causes trouble, because those objects cannot change. With lists and dictionaries it matters, and chapter 4 shows how.
Turn input into numbers
input() shows a prompt, waits for a line of text and returns it as a str, even when the user typed digits. Convert explicitly, at the point where you need a number:
name = input("Your name: ").strip()
lessons = int(input("Lessons this week: "))
minutes_each = float(input("Minutes per lesson: "))
total_minutes = lessons * minutes_each
print(f"{name}, that is {total_minutes / 60:.1f} hours of study.")
Typing four makes int() raise a ValueError; chapter 9 shows how to catch that and ask again. A successful conversion is not the same as a valid value, either: int("-3") works, but a negative number of lessons should still be rejected by your own check.
The conversion functions are worth knowing precisely:
print(int("42"), float("2.5"), str(42)) # 42 2.5 42
print(int(2.9), int(-2.9)) # 2 -2 (truncates toward zero)
print(int("ff", 16), int("0b101", 0)) # 255 5
print("2" + "3", int("2") + int("3")) # 23 5
print(bool(0), bool(""), bool("0")) # False False True
int() with a float drops the fractional part rather than rounding. With a second argument it parses other bases; base 0 reads the prefix (0x, 0o, 0b) from the text. Note the last line: bool of any non-empty string is True, including the string "0".
Arithmetic and the two kinds of division
The operators are +, -, *, / (true division), // (floor division), % (remainder) and ** (power):
print(17 / 5) # 3.4
print(17 // 5) # 3
print(17 % 5) # 2
print(divmod(17, 5)) # (3, 2)
print(2 ** 10) # 1024
print(10 / 2) # 5.0 (true division always returns a float)
print(-17 // 5) # -4
print(-17 % 5) # 3
The last two lines are where people get caught. // rounds down, toward negative infinity, not toward zero, so -17 // 5 is -4. The remainder follows from the rule that always holds: a == (a // b) * b + a % b, so the remainder has the sign of the divisor. That makes % useful for wrapping around, for example (day + 3) % 7 for a weekday that never goes negative.
Precedence follows mathematics: ** binds tightest, then *, /, // and %, then + and -. One trap: -2 ** 2 is -4, because the power is evaluated before the minus sign. Parentheses cost nothing and remove doubt.
Augmented assignment updates a name using its current value: x += 1, x -= 1, x *= 2, and so on. A small but common use is breaking a duration into parts:
seconds = 7385
hours, rest = divmod(seconds, 3600)
minutes, seconds = divmod(rest, 60)
print(f"{hours}:{minutes:02}:{seconds:02}") # 2:03:05
Integers never overflow; floats are approximate
Python integers grow as large as memory allows. 2 ** 100 is exact, and there is no 32-bit or 64-bit limit to worry about. Floats are different: they are 64-bit binary floating-point numbers, so most decimal fractions are stored as the nearest binary value.
import math
print(2 ** 100) # 1267650600228229401496703205376
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(round(2.5), round(3.5)) # 2 4
print(round(2.675, 2)) # 2.67
print(f"{1 / 3:.3f}") # 0.333
Never compare computed floats with ==; use math.isclose or compare against a tolerance that makes sense for your data. round rounds exact halves to the nearest even number (so-called banker’s rounding), which avoids a systematic upward bias over many values. round(2.675, 2) gives 2.67 because the stored value is slightly below 2.675. Formatting with :.3f changes how a value is shown, not the value itself. When results must follow decimal rules exactly, as with money, use the decimal module from chapter 16.
Booleans are numbers too
True and False are the two values of type bool, and bool is a subclass of int: True == 1 and False == 0. That lets you count matches by adding booleans:
scores = [72, 45, 90, 38, 81]
passed = sum(score >= 50 for score in scores)
print(passed) # 3
print(True + True) # 2
print(isinstance(True, int)) # True
The expression inside sum produces one boolean per score; the loop syntax is explained in chapter 4. Comparison operators (==, !=, <, <=, >, >=) return booleans, and so do isinstance and the in operator.
Bitwise operators for flags
Integers also support bitwise operators: | (or), & (and), ^ (exclusive or), ~ (invert), and the shifts << and >>. They are the right tool when several yes/no flags are packed into one number, as in file permissions or protocol headers:
CAN_READ, CAN_EDIT, CAN_PUBLISH = 1, 2, 4
editor = CAN_READ | CAN_EDIT
print(bin(editor)) # 0b11
print(bool(editor & CAN_PUBLISH)) # False
editor |= CAN_PUBLISH # grant a flag
editor &= ~CAN_EDIT # remove a flag
print(bin(editor), 1 << 4) # 0b101 16
Do not confuse these with the logical operators and, or and not, which work on truth values. For permission sets in new code, the enum.Flag class gives the same operations with readable names.
Practice
Write a script that asks for a number of lessons and minutes per lesson, rejects negative numbers with a message, and prints the total as hours and minutes (for example 3 h 15 min). Before running anything, predict -9 // 4, -9 % 4, round(0.5) and int("7.0").
Answer check: -9 // 4 is -3 and -9 % 4 is 3. round(0.5) is 0, because halves round to even. int("7.0") raises ValueError, since int parses only whole-number text; int(float("7.0")) works. For the total, divmod(total_minutes, 60) gives hours and minutes in one call.
Summary
Names point at objects and can be rebound; objects carry the type. Input is text until you convert it, and conversion does not replace validation. // and % round toward negative infinity, integers are exact at any size, floats are approximations that you compare with a tolerance, and booleans count as 0 and 1.