Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · Python · Chapter 02 / 16

Programming learning path

Variables, data types & operators

Numbers, strings, booleans, None, arithmetic, comparisons and conversion.

Variables, assignment and naming rules

A variable is a name bound to an object; assignment never copies data, it just points a name at a value.

x = 5 does not put the number 5 "inside" a box named x; Python evaluates the expression on the right, then makes the name x point to the resulting integer object. A name must start with a letter (Unicode letters are allowed, not only ASCII) or underscore, may contain letters, digits and underscores, and cannot be a reserved keyword like class or for. Because assignment is just name-binding, y = x makes y point to the exact same object x points to, not a fresh copy — the practical consequences of that show up clearly once mutable objects like lists enter the picture.

Key points

  • Assignment binds a name to an object; it does not copy the object's data
  • Valid names: letters (including non-ASCII), digits, underscores, not starting with a digit, not a keyword
  • y = x makes both names refer to the same underlying object

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Rebinding score to a new integer object leaves player_two_score pointing at the original one.

Common pitfalls

  • Using a keyword as a name (class = "A") raises a SyntaxError
  • Assuming y = x creates an independent copy leads to real bugs once x is a mutable list

Practice exercise

Predict, then verify in a REPL: after a = [1, 2]; b = a; b.append(3), what does a equal? Explain why in one sentence using the word "object".

Numeric types: int, float and basic arithmetic

int has unlimited precision; float is a fixed-precision approximation — and that difference causes real bugs.

Python's int type has arbitrary precision — limited only by available memory, not a fixed bit width — so 2 ** 100 computes an exact integer with no overflow. On essentially every mainstream platform, float follows the IEEE-754 double-precision standard, which cannot represent most decimal fractions exactly, so 0.1 + 0.2 prints 0.30000000000000004 rather than 0.3; Python's own documentation describes this as what nearly all platforms use, not a guarantee written into the language itself. / always produces a float (true division), // produces a floored quotient, and % produces the remainder. Results of inexact floating-point calculations should generally be compared with math.isclose() rather than ==; exact == is still correct when the program genuinely needs exact binary equality. For exact decimal arithmetic — such as money — decimal.Decimal is a strong choice, though representing money as integer minor units (cents) is also a common, valid approach.

Key points

  • int has arbitrary precision, limited only by memory; float is a fixed-precision binary approximation (IEEE-754 on nearly all platforms)
  • / is true division (always float), // is floor division, % is remainder
  • Use math.isclose() for approximate float comparisons; use exact == only when exact equality is truly intended

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Integer versus float division, and why exact decimal comparisons need the decimal module.

Common pitfalls

  • if price == 19.99: often silently fails due to float imprecision
  • // with negative numbers floors toward negative infinity, not toward zero: -7 // 2 == -4

Practice exercise

Compare 0.1 + 0.2 with 0.3 using math.isclose(). Then experiment with its rel_tol and abs_tol arguments, and explain in one sentence why a single hard-coded absolute tolerance is not always enough.

Booleans, None and truthiness

bool is a subtype of int, None means "no value", and every object has an implicit truth value.

True and False are actually instances of bool, which is a subclass of int — True == 1 and False == 0 are both True, and True + True evaluates to 2, though relying on that in real code is poor style. None is Python's single "no value" object, commonly used as a default for "nothing provided yet", and is always tested with is None, never == None. Every object can be evaluated in a boolean context: None, False, 0, 0.0, and empty containers ("", [], {}) are falsy, and virtually everything else is truthy.

Key points

  • bool is a subclass of int; True == 1 and False == 0
  • Test for "no value" with is None, never == None
  • None, False, 0, 0.0 and empty containers are falsy; almost everything else is truthy

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Using None as a sentinel default, and showing that a list containing 0 is still truthy.

Common pitfalls

  • if value == None: works but is non-idiomatic and slower than is None
  • if my_list == []: works but if not my_list: is the idiomatic emptiness check

Practice exercise

Write is_empty(value) that returns True for None, an empty string, an empty list, or 0, using only truthiness — no explicit type checks.

Arithmetic, comparison and boolean operators

Operator precedence, chained comparisons, and how and/or actually return one of their operands.

Python follows standard mathematical precedence (** highest, then *//////%, then +/-, then comparisons, then not, and, or), and parentheses always override it for clarity. Comparisons can be chained (0 <= x < 10), which reads naturally and evaluates each part only once. and and or are not restricted to returning True/False: and returns its first falsy operand or its last operand, and or returns its first truthy operand or its last operand, both short-circuiting as soon as the result is determined — this is the basis of the common value = user_input or "default" idiom.

Key points

  • Precedence among these operators: * first, then / // %, then + -, then comparisons, then not/and/or
  • Chained comparisons like 0 <= x < 10 evaluate each part once, combined with and
  • and/or return one of their actual operands, not necessarily True/False

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

The or-default idiom, a chained range check, and precedence determining the arithmetic result.

Common pitfalls

  • value or default silently replaces 0, "", or [] too, not just None — use value if value is not None else default when 0/empty are valid
  • Forgetting binds tighter than unary minus: -2 2 is -4, not 4

Practice exercise

Without running it, predict the result of 10 - 2 * 3 ** 2 // 4, then verify in a REPL and explain the order of operations that produced it.

Type conversion and checking

Converting between int, float, str, and bool explicitly, and checking a value's type safely.

int(x), float(x), str(x) and bool(x) each convert a value using different rules. int(x) and float(x) parse or convert supported inputs and can raise ValueError for a malformed string like int("forty-two"), or TypeError for an object that offers no sensible conversion at all. str(x) asks for a textual representation and essentially never fails. bool(x) applies Python's truth-value rules rather than validating anything, so bool("nonsense") is simply True. int("3.5") raises ValueError because it does not parse a float string directly, but int(float("3.5")) works — and it is not just a parsing workaround: it genuinely truncates toward zero, so int(float("3.9")) is 3, not a rounded 4. type(x) returns an object's exact class, while isinstance(x, SomeType) checks whether an object is that type or any subclass of it, which is almost always the better choice for validation because it correctly handles inheritance.

Key points

  • int() and float() may raise ValueError or TypeError depending on the input; str() rarely fails; bool() applies truth-value rules rather than validating
  • int("3.5") fails directly; int(float("3.5")) works and truncates toward zero, e.g. int(float("3.9")) is 3
  • isinstance() respects inheritance and is generally preferred over type() == for checks

Code

raw = input("Enter a number: ")
try:
    value = int(raw)
except ValueError:
    print("Not a whole number")
else:
    print(isinstance(value, int))  # True

Safely converting user input with error handling instead of assuming the conversion succeeds.

Common pitfalls

  • int(" 42 ") works (whitespace is stripped), but int("42.0") does not
  • Comparing type(x) == list instead of isinstance(x, list) breaks for legitimate list subclasses

Practice exercise

Write parse_number(text) that returns an int if the text is a whole number, a float if it has a decimal point, or None if it is not a valid number at all.

Source registry

4 chapter references
The Python Tutorial

Baseline syntax, control flow, functions and module basics

Python Software Foundation · Official documentation
Source ↗
The Python Language Reference

Precise scoping, evaluation order and expression semantics

Python Software Foundation · Official reference
Source ↗
The Python Standard Library

Authoritative behavior for built-in types and standard library modules

Python Software Foundation · Official reference
Source ↗
Data model

Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols

Python Software Foundation · Official reference
Source ↗