Lesson · Language Fundamentals
Literals
57 min readLiterals
Literals are source-code syntax for creating common values. Learning their forms helps you read code accurately and choose clear representations for text, numbers, bytes, and collections.
Learning goals
- Write the same number as decimal, binary (
0b), octal (0o), and hexadecimal (0x) literals and show they create equalintvalues. - Use underscores and scientific notation to keep numeric literals readable without changing their values.
- Read and write string literals with escapes, raw and f prefixes, triple quotes, and adjacent-literal concatenation.
- Explain what
b"ABC"creates and how it differs from the string"ABC". - Build lists, tuples, sets, and dicts from bracketed literals, including the correct empty forms.
Mental model
Every literal is a small parser instruction that produces an object: the spelling decides both the type and the value, before any function call runs. The lesson walks one family at a time, numbers in four bases and in scientific notation, then text, bytes, and the bracketed collection forms, and the same two questions apply to each: which object does this token create, and what does its exact spelling allow?
Core idea
Literals are how source code names a value directly, and the parser turns each spelling into a finished object: 0x2A and 42 are the same int, r"\n" is two characters, and b"ABC" is bytes. Reading code the way the parser does means knowing what each prefix, quote, and bracket produces, and picking the spelling that matches the type you actually need.
Integer literals
Integer literals are digit sequences such as 42, optionally written in base 2 (0b101010), base 8 (0o52), or base 16 (0x2A), with underscores allowed between digits for readability (1_000_000). Every form produces an int; the base and underscores change only the spelling.
Binary / octal / hexadecimal literals
These are integer literals with a 0b, 0o, or 0x prefix selecting base 2, 8, or 16. The prefixes and hex digits accept either case, underscores may separate digits (0b1010_1010), and the resulting object is the same kind of int as its decimal spelling (0x2A == 42).
Float literals
A float literal contains a decimal point (3.5), an exponent (4.2e1), or both, and always creates a float, even when the value is whole like 42.0. The digits are parsed into the nearest binary double, and underscores may separate digits (1_000.5).
Scientific notation
A floating-point literal such as 1.5e3 means 1.5 × 10³. The exponent changes the literal's scale, not the fact that the result is a binary floating-point object.
Complex literals
A complex literal writes the imaginary part with a j suffix, as in 4j or 2 + 4j; the real and imaginary parts may be ints or floats and end up as floats inside the complex. complex(2, 4) builds the same value, and .real and .imag read the parts back.
String literals
String literals are text in single or double quotes, or triple quotes when the text spans lines, and they create str objects. Escape sequences (\n, \t, \") are processed unless an r prefix disables that, and adjacent string literals join into one at parse time.
Raw strings
A raw string prefix suppresses most backslash escape processing in the literal, which is useful for regular expressions and Windows-style paths. A raw string still cannot end with an odd number of backslashes.
Bytes literals
A b prefix creates a bytes object, an immutable sequence of integers from 0 to 255, as in b"ABC". The content must be ASCII or use escapes such as \x41; bytes never mix with str in operations, and text conversion goes through .decode() and .encode().
Boolean literals
True and False are the two bool instances, spelled as keywords so they cannot be reassigned or shadowed. They are also int values of 1 and 0, but code should use them as answers to yes-or-no questions.
None
None is the single instance of NoneType, written as its own keyword, and it means "no value". It is falsy, functions without a return hand it back, and the identity test is None is the intended comparison.
Collection literals
Bracketed literals build collections directly: [1, 2] is a list, (1, 2) a tuple, {1, 2} a set, and {1: "one"} a dict. {} is an empty dict, so an empty set needs set(), and the literal creates the object at the moment the statement runs.
Walkthrough
42,0b101010, and0x2Aare three spellings of one value: the0band0xprefixes change how the digits are read, not theintthat results, so the first print shows42 42 42 42.0.4.2e1is a float literal even though it looks whole; thee1multiplies by ten, producing thefloat42.0.r"C:\new\test"keeps backslashes as typed: therprefix stops escape processing, so\nand\tare two-character sequences here instead of a newline and a tab.b"ABC"builds abytesobject, a different type from"ABC"; the second print showsb'ABC', with the prefix included in itsrepr.- Predict before running: why the first line prints
42three times and42.0once, and whatraw_pathwould show without ther.
Experiments to try
- Print
1_000_000,0b1010_1010, and0x2anext to1000000,0b10101010, and42; confirm underscores and letter case are decoration. - Compare
len("C:\new\test")(9) withlen(raw_path)(11) and explain which characters the plain string lost. - Concatenate two adjacent string literals (
"Py" "thon") and an f-string with an expression; state which join happens at parse time and which at run time. - Build
[1, 2],(1, 2),{1, 2},{1: "one"},{}, andset(), and printtypeand content for each; explain why{}is not an empty set.
Common mistakes
- Reading
0b,0o, and0xas decoration: they change the base only, so0x2A,0b101010, and42are the same value, and old leading-zero spellings such as042are rejected by Python 3's parser. - Expecting a whole-looking float literal to be an int:
4.2e1and42.0are floats, so they are approximate for values binary cannot store exactly, unlike the equal int42. - Dropping the
rprefix on a Windows path:"C:\new"reads\nas a newline and the string silently loses the backslash;r"C:\new"or"C:\\new"preserves it. - Treating
b"ABC"and"ABC"as interchangeable: bytes index to integers from 0 to 255, concatenate only with bytes, and need.decode()before working as text; mixing the two raisesTypeError.
Practice: Easy
- In the REPL, evaluate
42,0b101010,0o52, and0x2Aand print each withrepr. State in one sentence why all four are equal. - Write one string literal with single quotes, one with double quotes, and one f-string; print all three and note where the quote choice actually matters.
- Convert the worked example's
raw_pathto a non-raw literal by doubling each backslash; print both and confirm they are identical with==.
Practice: Medium
- Encode
"Caf\u00e9"to UTF-8, print the bytes object, and explain why itsreprshows escape sequences; decode it back and compare with the original. - Split a long message across two adjacent string literals on two source lines and prove the runtime result is one string; compare with
+and explain parse time versus run time. - In one script, create a list, a tuple, a set, a dict,
{}, andset(); printtypeand content for each and explain what{}alone means.
Practice: Hard
- Pick six literals, one per base plus scientific, raw, and bytes; predict the exact
printoutput for each, then run and annotate any surprise. - Show why
int("0x2A")fails whileint("0x2A", 16)succeeds, and connect the answer to the difference between literal syntax andint()parsing. - Write a six-line cheat sheet for a teammate: one example each of an integer literal, a float literal, a complex literal, a raw string, an f-string, and a bytes literal, each with the type it creates.
Lesson checklist
- I can write the same integer in decimal, binary, octal, and hexadecimal and prove they are equal.
- I can say which literal forms create
floatandbytesand why theirreprshows prefixes. - I can use raw strings, escapes, and adjacent-literal concatenation without confusing parse-time and run-time behavior.
- I can build a list, tuple, set, and dict from bracketed literals, including the empty forms.
Remember
Literals are the parser's vocabulary for values: number bases and exponents for numbers, prefixes and quotes for text and bytes, and brackets for collections. Learn each spelling as a type decision, check it with `repr` and `type`, and the literal you write will create exactly the object you meant.
Interview angles
What is the main purpose of **Integer literals**?+
Integer literals are digit sequences with optional base prefixes (0b, 0o, 0x) and underscores for readability, and they always create an int. Literal parsing happens before any function call, so 1_000_000 and 0x2A are as direct as 42.
What should you pay attention to when using **Binary / octal / hexadecimal literals**?+
The prefixes 0b, 0o, and 0x change only how the digits are interpreted: base 2, 8, or 16, all producing an int. Prefix letters and hex digits accept either case, and underscores may separate digits.
How does **Float literals** fit into this lesson?+
A float literal contains a decimal point or an exponent, or both, so 3.5 and 4.2e1 create float objects. The exponent form aeb means a times 10 to the power b, and the value is stored as a binary approximation of that decimal number.
What exactly does `"C:\new\test"` contain, and what does `r"C:\new\test"` contain instead?+
The first string processes escapes: \n becomes a newline and \t becomes a tab, so it is 9 characters with no literal backslashes. The raw version suppresses escape processing and keeps both backslashes as literal characters, making it 11 characters that match a Windows path as typed.