Quark's Outlines: Python Literals

Mike VincentMike Vincent
10 min read

Overview of Python Literals

What is a literal in Python?

Let’s say you want your program to display the word hello. You write:

print("hello")

The value "hello" is a literal. It is written directly in your code. You are not naming it. You are not calculating it. You are giving Python the value as-is.

When Python runs the code, it creates an object from that literal. In this case, it creates a string object with the value "hello".

You can also assign that object to a name. A name is sometimes called a variable. Assignment means binding a name to an object.

Python lets you assign literal values to names

count = 10
message = "hello"
is_ready = True
missing = None

A literal is what you write.
An object is what Python makes.
A name is what you assign to the object.

How do you write text (string) literals in Python?

In Python, you write string literals by enclosing text in quotes. You can use single quotes ('...') or double quotes ("...") to wrap the text. For example, 'Hello' and "Hello" both represent the string Hello. Using quotes tells Python that the characters inside are part of a string value, not code.

If you need to include special characters in a string, like a newline or a tab, you can use escape sequences. An escape sequence starts with a backslash \. For instance, "\n" represents a newline character, so "Hello\nWorld" is a string that spans two lines (“Hello” then a line break, then “World”).

Some common escape sequences are \n for newline, \t for a tab, \\ for a backslash character itself, and \" or \' to include quotes inside a string of the same quote type.

If you prefix a string literal with r or R, you get a raw string, which means escape sequences are not processed. For example, r"\n" literally represents a backslash and an n, not a newline.

Python also has triple-quoted strings using '''...''' or """...""". These can span multiple lines conveniently and are often used for long text like documentation.

Python lets you write a multi-line string using triple quotes

message = """Line1
Line2
Line3"""

This is a string literal that includes actual line breaks as typed.

Python also has bytes literals for binary data. You write them by prefixing the string with a b, like b"ABC", which represents a sequence of bytes (each character’s byte value in ASCII).

In summary, to write a string, put it in quotes. Choose the quoting style that fits what you need, and use escape sequences for special characters.

How do you write numeric literals in Python?

Python has three kinds of numeric literals: integers, floating-point numbers, and complex numbers.

An integer is a whole number. You write it using digits, like 0, 42, or 1000000. You can also use underscores to group digits. Python ignores the underscores, but they make large numbers easier to read. For example, 1_000_000 is the same as 1000000.

You can write integers in different number bases. Use 0b for binary, 0o for octal, and 0x for hexadecimal.

Python lets you write integers in decimal, binary, octal, or hex

a = 255
b = 0b11111111
c = 0o377
d = 0xff

A floating-point number has a decimal point. It can also use scientific notation with e or E to show powers of ten. You can add underscores to group digits here too.

Python lets you write floating-point numbers with or without exponents

e = 3.14
f = 1.0e-3
g = 2.997_924_58

A complex number includes a real part and an imaginary part. You use j or J to write the imaginary part. Python treats 4j as 0 plus 4 imaginary.

Python lets you write complex numbers using j

h = 3 + 4j
i = 4j

Each numeric literal gives Python a value of a specific number type: integer, float, or complex.

What are f-strings and how do they work as literals?

An f-string is a kind of string literal that includes Python expressions inside it. You write an f-string by adding the letter f before the quotes.

Inside the string, you use curly braces to show where Python should insert a value. This value is calculated when the code runs.

Python lets you create dynamic text with f-strings

name = "Ada"
greeting = f"Hello, {name}!"

Here, greeting becomes "Hello, Ada!" because Python replaces {name} with the value of name.

You can put any expression inside the braces. Python will run it and insert the result into the string.

Python lets you include expressions inside f-strings

f"{2 + 2}"          # gives "4"
f"{name.upper()}?"  # gives "ADA?" if name = "Ada"

You can also use colons and format codes to control how the value appears. For example, f"{pi:.2f}" shows a number with two decimal places.

Even though f-strings include changing parts, the whole thing is still a literal. It is written directly in your code and turns into a string at runtime.

Why use literals in code?

Literals give you a way to write fixed values in your code. They make your intent clear.

If your program needs to use 60 or "Game Over", you can just write those directly. There is no need to define them somewhere else.

Literals are simple. They help prevent mistakes. Python knows what value you mean the moment it reads your code.

Python lets you write fixed values directly as literals

seconds = 60
status = "Game Over"

These values are easy to read and fast to run. Literals form the base of your code. You use them with names and expressions to build the rest of your logic.


Timeline of Python Literals

Where do Python’s literal forms come from?

Python uses literal forms to represent fixed values like numbers, text, and logical states. These forms come from early computing, programming languages, and formal language design. As Python grew, new syntax was added carefully to improve clarity and avoid breaking older code. This timeline shows you how humans shaped Python’s literal system—by borrowing from the past, improving on old forms, and choosing what to keep.


Humans invent ways to write values

1958 —Literal base prefixes IBM 704 used prefixes like 0x to show numbers in different bases.
1960 —String and number constants ALGOL 60 used quotes for text and formats for numbers.
1972 —Case-sensitive string names C treated Name and name as different names in code.
1980 —Clear literals and indentation ABC used quotes for strings and spacing to group code.

Humans design Python

1989 —Core literal types Python began with strings, numbers, None, and Boolean values.
1991 —Triple-quoted strings and complex numbers Python 0.9.0 added long strings and j for complex values.
2001 —Boolean constants True and False Python 2.2 added True and False as fixed names.

Humans expand what literals can show

2007 —UTF-8 source encoding Python 3.0 made UTF-8 the default so strings could hold all text.
2015 —Formatted string literals (f-strings) PEP 498 added f"text {value}" for easier formatting.
2016 —Underscores in numeric literals PEP 515 let numbers use _ like 1_000_000 to group digits.
2017 —Uppercase J for complex values Python 3.6 allowed both j and J in complex numbers.
2019 —f-string debug syntax Python 3.8 let f"{var=}" print both a name and its value.
2023 —Literal type annotations Python 3.12 added Literal to typing for fixed-value hints.


Problems & Solutions with Python Literals

How do you use fixed values in Python the right way?

Python uses literal values to write things like text, numbers, or empty markers directly in code. These are called literals because the value appears exactly as written. Even though Python makes this simple, there are still common cases where the right use of a literal makes code easier to write and understand. Each example below shows a problem and a solution using Python's literal system.


Problem 1: Needing to include a fixed piece of text in a program

Problem: You are writing a greeting card. You want the card to show this message exactly:
Happy Birthday, "Alex"!
You want to include the quotes around Alex. But writing the quote marks inside code can confuse the computer. You also want the message to look right if it takes more than one line.

Solution: Python lets you include fixed text using string literals. You can write a string with either single quotes or double quotes. To include quote marks inside the string, you use escape codes or switch the outer quotes. You can also use triple quotes for longer blocks of text.

message = "Happy Birthday, \"Alex\"!"
print(message)

This prints:
Happy Birthday, "Alex"!

You can also use triple quotes to keep line breaks:

message = """Dear friend,
Happy Birthday!
Sincerely,
Your Pal"""
print(message)

This prints the full message with each line exactly as written.


Problem 2: Representing a large number clearly in code

Problem: You want to write the number one million in your code. If you write 1000000, it is correct, but it is hard to read. You might miscount the number of zeroes.

Solution: Python lets you use underscores in number literals to group digits. This helps you see the size of the number clearly.

population = 1_000_000
print(population)

Python treats 1_000_000 the same as 1000000. You can use this style in any large number, such as 10_000_000_000. The underscores make the number easier for you and others to read.


Problem 3: Combining text with dynamic values

Problem: You want to write a message like:
Hello, Carlos. You have 42 points.
But you want the name and number to change based on variables. Writing this with string addition is messy and easy to break.

Solution: Python has formatted string literals called f-strings. These let you put the variables right inside the string.

name = "Carlos"
score = 42
message = f"Hello, {name}. You have {score} points."
print(message)

Python replaces {name} with "Carlos" and {score} with 42. The result is:
Hello, Carlos. You have 42 points.
You do not need to convert anything or add extra spaces. The f-string handles it for you.


Problem 4: Writing special characters in strings

Problem: You want to print a short table that uses tabs and newlines. For example:

Item    List
1    Apple
2    Banana

But writing this with line breaks and tabs inside a string is confusing.

Solution: Python uses escape codes for special characters. The most common are \n for new lines and \t for tabs.

text = "Item\tList\n1\tApple\n2\tBanana"
print(text)

This prints:

Item    List
1    Apple
2    Banana

Each \t adds a tab space. Each \n moves to a new line. This lets you show clear structure in the output.


Problem 5: Needing a placeholder value that means “nothing”

Problem: You want to create a variable that means "no value yet". Using 0 or an empty string might be misleading, since those can be real values.

Solution: Python uses the literal None to mean no value. You can assign None to a variable that does not have a result yet.

result = None

Later, you can check if the value is still None:

if result is None:
    print("No result yet.")

This helps make it clear that the variable is empty on purpose. Functions also return None to show they found nothing.

def find_user(username):
    if username in users:
        return users[username]
    else:
        return None

The word None is a keyword and a literal. It stands for "no value" and helps you show intent clearly in your code.


Like, Comment, and Subscribe

Did you find this helpful? Let me know by clicking the like button below. I'd love to hear your thoughts in the comments, too! If you want to see more content like this, don't forget to subscribe to my channel. Thanks for reading!


Mike Vincent is an American software engineer and writer based in Los Angeles. Mike writes about technology leadership and holds degrees in Linguistics and Industrial Automation. More about Mike Vincent

0
Subscribe to my newsletter

Read articles from Mike Vincent directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mike Vincent
Mike Vincent

Mike Vincent is an American software engineer and writer based in Los Angeles.