South Plantation High School logo
South Plantation High School · Procedural Programming with Python

Literals & Variables

Literal types · Binary, octal, decimal & hex · Naming variables with PEP 8 · Lesson review

Review the lesson slides, then complete the assignment at the bottom of this page. Your assignment work is saved in this browser on this computer. When you check a task, your name, period, and which tasks are complete are shared with your teacher (your code is not). When you finish, print it or save it as a PDF to turn in.
1 / 18
Lesson Review

Literals & Variables

423.14"hi"True0b10100xFFsnake_case

The values you type into your code, the number systems behind them, and how to name the variables that hold them.

By the end of this lesson you will be able to:

  • Tell the difference between boolean, integer, float, and string literals, and check them with type().
  • Explain the binary, octal, decimal, and hexadecimal number systems.
  • Write integer literals in all four systems using 0b, 0o, and 0x, and convert between them.
  • Declare variables and name them with snake_case, following PEP 8, Python's official style guide.
How to use this page: Use Next and Back (or the arrow keys). Flip bits, sort literals, convert numbers, test variable names, and type real Python at the >>> prompts. Use Step in the editors to watch Python run one line at a time.

How the three ideas fit together

  1. Literals are the values you type: 15, "Ava", True.
  2. Number systems explain how the computer actually stores those values inside memory: as binary 1s and 0s.
  3. Variables are the names you give values so you can use them again later: age = 15.

Every program you write this year uses all three, usually on the very first line.

  • Three big ideas: literal types, number systems, naming variables.
  • Literals are values, number systems are how they are stored, variables are names for them.

Every program is built from values and names. Today we look at the values you type directly into your code, called literals, the four number systems Python understands, and the rules and style for naming the variables that store those values.

Literals

What is a literal?

A literal is a value written directly in your code. What you type is literally the value. The Python documentation puts it this way:

"Literals are notations for constant values of some built-in types."
(The Python Language Reference, Lexical analysis)

A variable is a name that refers to a value. The value can come from a literal, from math, from input(), and so on.

In score = 100It is a...
scorevariable (a name)
=assignment operator ("store in")
100integer literal (a value)
name = "Ava"       # "Ava" is a string literal
age = 15           # 15 is an integer literal
gpa = 3.8          # 3.8 is a float literal
on_team = True     # True is a boolean literal
age = age + 1      # no literal on the left side
Quick test: if you can read the value straight off the screen without running anything, it is a literal. 15 is a literal. age + 1 is an expression: Python has to calculate it.

A literal can never be changed

The word constant in the definition means the value is fixed. 5 always means five. You can change what a variable holds, but you can never change a literal:

age = 15     # fine: the variable age now holds 15
age = 16     # fine: age now holds 16 instead
5 = 6        # error: you cannot store into a literal

Python answers that last line with SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

Literal or expression?

CodeLiteral?Why
3.5YesThe value is written right there.
7 / 2NoAn expression made from two literals. Python must calculate it to get 3.5.
"7 / 2"YesThe quotes make it a string literal. It is just text; no math happens.
gpaNoA variable name. Python looks up the value it refers to.
  • Literal = a value typed directly in code.
  • Variable = a name that refers to a value.
  • A literal is fixed; a variable can be given a new value.

When you type the number 100 in your code, that 100 is a literal. It means exactly what it says. A variable is different: it is a name, like score, that points to a value. Literals are the raw values. Variables are the labels we stick on them.

Literals

The four literal types in this unit

TypePython nameExamplesClue
Integerint42 -7 0Whole number, no decimal point
Floatfloat3.14 -0.5 2.0Has a decimal point (or an e)
Stringstr"hi" '42' ""Inside quotes
BooleanboolTrue FalseOnly these two, capitalized

The built-in function type() tells you the type of any value (the next slide explains exactly how it works):

print(type(42))      # <class 'int'>
print(type(3.14))    # <class 'float'>
print(type("42"))    # <class 'str'>
print(type(True))    # <class 'bool'>

Try these at the prompt. Notice that 42, 42.0, and "42" look alike but are three different types.

  • type(42)
  • type(42.0)
  • type("42")
  • type(True)
  • type("True")
  • type(None)

None is Python's special value for "no value at all." Its type is NoneType. It is not one of our four types, but you will meet it again later in the course.

Why does the type matter?

The type decides what an operator does. The same symbol can do very different jobs:

CodeResultWhat happened
2 + 24int + int: adds
"2" + "2""22"str + str: joins the text
2 * 36int * int: multiplies
"2" * 3"222"str * int: repeats the text 3 times

So before you predict what a line will do, always ask: "What type is each value?"

  • int, float, str, bool. type() reveals the type.
  • 42, 42.0, and "42" are three different types.
  • The type decides what + and * do.

Here are the four types we focus on. The type decides what you can do with a value. You can do math with 42, but "42" in quotes is text. Type each example into the prompt and read the class name Python gives back. Pay extra attention to the one with quotes around True.

Literals: type()

The type() function

type() is a built-in function: a tool that comes with Python. You put one value inside the parentheses (this is called the argument), and type() gives back (returns) that value's data type.

type(42)        # returns <class 'int'>
type("hello")   # returns <class 'str'>

Reading the answer

class is Python's word for a type. Skip the <class ' and '> and read the name in the middle:

Python showsIt means
<class 'int'>integer (whole number)
<class 'float'>float (number with a decimal point)
<class 'str'>string (text)
<class 'bool'>boolean (True or False)
<class 'NoneType'>None, Python's value for "nothing here"

At the >>> prompt vs. in a program

  • At the >>> prompt, Python shows the result of every line by itself, so type(42) is enough.
  • In a program (a .py file), results are not shown unless you print them. Write print(type(42)). A line with just type(42) runs, but nothing appears.

Python works out the value first

type() also works on variables and expressions. Python calculates the value, then reports its type: type(10 / 2) is float because 10 / 2 is 5.0, and type(5 > 3) is bool because 5 > 3 is True.

print() can fool you. print(42) and print("42") both show 42, because print() drops the quotes. Only type() shows that one is an int and the other is a str.

Pick a value for x and click Run. Compare what print(x) shows with what print(type(x)) shows. Try 42 and then "42".

Why it matters: input() always gives a string

Whatever the user types, input() stores it as a str, even digits. Type an age and step through to watch the type change after int().

Debugging tip: when math acts strangely or you get a TypeError, add print(type(your_variable)) to see what you are really working with. A variable has the type of the value it holds right now, so if you store a new value, type() can give a different answer.

Changing a value's type

Each type name is also a function that tries to convert a value to that type. This is how you fix the input() problem above:

CodeResultNote
int("42")42text of a whole number becomes an int
float("3.5")3.5text of a decimal becomes a float
str(42)"42"any value can become text
int(3.9)3chops off the decimal part; it does not round
float(7)7.0adds a decimal point

Converting does not change the original variable unless you store the result back, as in age = int(age).

  • type(value) returns the type, shown as <class 'name'>. class means type.
  • Use print(type(x)) in a program; the >>> prompt shows it automatically.
  • print(42) and print("42") look the same; type() tells them apart. input() always returns a str.
  • int(), float(), str() convert values; store the result to keep it.

We have been using type all along, so let's look at it closely. You hand it one value, and it hands back that value's type. The answer always looks like class, then the type name in quotes. Class is just Python's word for type, so read the name in the middle. One thing that trips people up: at the prompt, Python shows results automatically, but in a program you have to print them. Now try 42 and then "42" in quotes in the editor. The print line shows the same thing both times. Only type tells you that one is a number and the other is text. That is exactly why type is such a useful debugging tool, especially with input, which always gives you a string.

Literals: int

Integer literals

  • An integer is a whole number: positive, negative, or zero. No decimal point.
  • No commas! Write 1000000, not 1,000,000.
  • You may use underscores to make big numbers easier to read: 1_000_000 is the same as 1000000. Underscores go between digits only, one at a time.
  • A decimal integer cannot start with 0 (except zero itself). 007 is an error.
  • Python integers have no size limit apart from your computer's memory.
Watch out: x = 1,000 does not cause an error. The comma makes a tuple (a group of two values, 1 and 0). Your program keeps running with the wrong value. That makes this bug hard to find.

Pick a value for x and run it. Try 1_000_000, then 007 and 12abc.

How big can an int be?

In many languages, integers have a maximum size and "overflow" when they get too large. Python does not. 2 ** 100 gives the exact answer 1267650600228229401496703205376. Python just uses more memory as the number grows.

Where do negative numbers come from?

Technically, -7 is the minus sign (an operator) applied to the literal 7. You do not need to think about it that way when you write code, but it explains why there is a space allowed in - 7.

Why are leading zeros an error? In old Python 2, 017 meant octal 17 (which is 15). That confused many people, so Python 3 made it an error and requires the clear prefix 0o17 instead.
  • Whole numbers. No commas. Underscores allowed between digits. No leading zeros.
  • Python ints never overflow.
  • Leading zeros are banned because they used to mean octal.

Integers are the simplest literals, but they have a few rules. The biggest one: never use commas in a number. Python will not even warn you; it quietly makes a different kind of value. If you want to make a big number readable, use underscores instead.

Literals: float

Float literals

A float (floating-point number) is a number with a decimal point or an exponent.

LiteralValueWhy
3.143.14decimal point
2.02.0still a float, even though it is a whole number
5.5.0digits after the point are optional
.50.5digits before the point are optional
1e31000.0e means "times 10 to the power": 1 × 103
2.5e-30.00252.5 × 10-3
Division always makes a float: 10 / 2 is 5.0, not 5. Use // for whole-number division.
Floats are close, not always exact. Try 0.1 + 0.2. Computers store floats in binary, and some decimals (like 0.1) cannot be stored exactly, so you get a tiny rounding difference.

Reading scientific notation

The e means "times 10 to the power of." Move the decimal point right for a positive power and left for a negative one:

  • 1e3: move 3 places right, so 1000.0.
  • 2.5e-3: move 3 places left, so 0.0025.

Scientists use this for very large or very small numbers, like the distance to the Sun (1.496e11 meters).

Living with rounding differences

Because 0.1 + 0.2 is 0.30000000000000004, the comparison 0.1 + 0.2 == 0.3 is actually False! Two habits help:

  • Round before showing results: round(0.1 + 0.2, 2) gives 0.3.
  • For money, many programmers count in whole cents with ints (1999 instead of 19.99) so nothing gets rounded.
  • Decimal point or e makes a float.
  • / always gives a float. Floats can have tiny rounding differences.
  • 0.1 + 0.2 == 0.3 is False; round before comparing or showing.

A float is any number with a decimal point, even 2.0, which looks like a whole number. The letter e is scientific notation: 1e3 means 1 times 10 to the third, which is 1000.0. Try 0.1 plus 0.2 in the editor. The answer is surprising, and it is because the computer stores numbers in binary, which we will get to soon.

Literals: str

String literals

  • A string is text: any characters inside quotes.
  • Single 'hi' and double "hi" quotes work the same. Start and end with the same kind.
  • Use one kind of quote to hold the other: "It's fine".
  • Triple quotes """ make a string that can span several lines.
  • "" is the empty string: a string with zero characters.
Numbers in quotes are text. "5" + "5" is "55", not 10. And "5" + 5 is an error: TypeError: can only concatenate str (not "int") to str.

Pick a string and run it. len() counts the characters. Try the broken one to see Python's error.

Special characters: escape sequences

A backslash \ inside a string starts an escape sequence, a code for a character that is hard to type:

WriteYou getExample
\na new lineprint("Line 1\nLine 2") prints two lines
\ta tabprint("Name\tScore")
\" or \'a quote that does not end the string'It\'s fine'
\\one real backslash"C:\\Users"

Each escape counts as one character. len("a\nb") is 3: a, a new line, and b.

  • Quotes make a string. Same quote to open and close.
  • "5" is text, 5 is a number.
  • \n new line, \t tab, \\ backslash.

Anything in quotes is a string, even if it looks like a number. That is one of the most common beginner bugs: input gives you a string, and then math does not work the way you expect. Try It's broken in the editor. The apostrophe ends the string early, and Python cannot find the end.

Literals: bool

Boolean literals

  • There are exactly two boolean literals: True and False.
  • They are keywords, and they must be capitalized exactly like that.
  • Comparisons give booleans: 5 > 3 is True.
  • "True" in quotes is a string, not a boolean.
You typePython 3.13 says
print(true)NameError: name 'true' is not defined. Did you mean: 'True'?
print(type("True"))<class 'str'>
Fun fact: in Python, bool is a special kind of int. True acts like 1 and False like 0, so True + 1 is 2. (You will not need this often, but it explains some surprises.)

Every value has a "truth" value

The bool() function turns any value into True or False. The rule: empty or zero is False; everything else is True.

CodeResult
bool(0), bool(0.0)False
bool("") (empty string)False
bool(42), bool(-1)True
bool(" ") (a space is a character)True
bool("False")True

That last one surprises everyone: "False" is a non-empty string, so it counts as true. This is one more reason to keep booleans out of quotes.

  • Only True and False, capitalized.
  • "True" is a string. true is a NameError.
  • Empty or zero is False; everything else is True.
  • bool("False") is True.

Booleans are the yes or no values. There are only two of them, and Python is picky: capital T, capital F. Lowercase true is not a keyword, so Python thinks it is a variable you never created. Try each option and compare the type that prints.

Practice

Literal sorter

Choose the type of each literal, then click Check my answers. The answers come from running type() on each one. This is practice only; nothing is recorded.

Tricky ones to watch for

  • "3.14" looks like a float, but the quotes win: it is a str.
  • 1e3 has no decimal point, but the e makes it a float.
  • 0xFF has letters in it, but it is an int written in hexadecimal.
  • True without quotes is a bool; "True" with quotes is a str.

When you get one wrong, try it at a >>> prompt with type() to see the proof.

  • Look for quotes first (str), then True/False (bool), then a decimal point or e (float). Everything else here is int.

Here is a strategy. First, look for quotes. If it has quotes, it is a string, no matter what is inside. Next, is it exactly True or False? Then it is a boolean. Otherwise, does it have a decimal point or an e? Float. If none of those, it is an integer.

Number Systems

Four ways to write the same number

A number system (or base) is how many different digits you use before you "carry" to the next place.

SystemBaseDigits used
Decimal100 1 2 3 4 5 6 7 8 9
Binary20 1
Octal80 1 2 3 4 5 6 7
Hexadecimal160-9 then A B C D E F (10 to 15)
  • We count in decimal because people have 10 fingers.
  • Computers store everything as bits: tiny switches that are off (0) or on (1). That is binary.
  • Long binary numbers are hard to read, so programmers use octal and hexadecimal as shorthand. One octal digit stands for 3 bits, and one hex digit stands for 4 bits.

Counting from 0 to 16 in each system. Watch where each one "carries":

DecimalBinaryOctalHex
0000
1111
21022
31133
410044
510155
611066
711177
81000108
91001119
10101012A
11101113B
12110014C
13110115D
14111016E
15111117F
16100002010

What "carrying" really means

In decimal, after 9 you run out of digits, so you write a 0 and carry a 1 into the next place: 9, then 10. Binary works exactly the same way, it just runs out sooner. After 1 there are no more digits, so binary goes 0, 1, then 10 (which means two).

That leads to an old programmer joke: "There are 10 kinds of people in the world: those who understand binary and those who don't." (Read 10 in binary.)

The value never changes, only how it is written. Decimal 16, binary 10000, octal 20, and hex 10 are all the same amount, the same way "four" and "IV" both mean 4.
  • Base = number of digits. Decimal 10, binary 2, octal 8, hex 16.
  • Hex uses A to F for 10 to 15.
  • Every base carries when it runs out of digits.

In decimal, when you run out of digits after 9, you carry and write 10. Binary only has 0 and 1, so it carries after 1: one, ten, eleven, and so on. Octal carries after 7. Hexadecimal needs 16 digits, so after 9 it borrows the letters A through F. Look at the row for 16: it is a round number in binary, octal, and hex.

Number Systems: Binary

Reading binary: place values

In decimal, each place is worth 10 times the place to its right: ones, tens, hundreds.

In binary, each place is worth 2 times the place to its right: 1, 2, 4, 8, 16, 32, 64, 128...

To read a binary number, add up the place values that have a 1:

  1    1    0    1      (binary 1101)
  8    4    2    1      (place values)
  8 +  4 +  0 +  1 = 13
Vocabulary: one binary digit is a bit. Eight bits make a byte. One byte can hold 0 to 255 (that is 256 different values).

Click the bits to turn them on and off. Then try the challenge.

Going the other way: decimal to binary

To write 45 in binary, take the largest place value that fits, subtract it, and repeat:

  1. The places are 32, 16, 8, 4, 2, 1. The biggest that fits in 45 is 32. 45 − 32 = 13.
  2. 16 does not fit in 13, so that place gets a 0. 8 fits: 13 − 8 = 5.
  3. 4 fits: 5 − 4 = 1. 2 does not fit (0). 1 fits: 1 − 1 = 0. Done.
32  16   8   4   2   1
 1   0   1   1   0   1     45 = 101101 in binary

Biggest value for a number of bits: with n bits, the largest number is 2n − 1. Four bits go up to 15, and eight bits (one byte) go up to 255.

  • Binary places: 1, 2, 4, 8, 16, 32, 64, 128.
  • Add the places that have a 1.
  • Decimal to binary: subtract the largest place value that fits, repeat.

Binary works exactly like decimal, but every place is worth twice the one before it instead of ten times. To read 1101, add 8, plus 4, plus 1: that is 13. Use the bit board to build some numbers. What do you get when all eight bits are on?

Number Systems: Octal & Hex

Octal and hexadecimal

Octal (base 8)

Places are worth 1, 8, 64, 512... So octal 17 = 1 × 8 + 7 = 15.

Each octal digit matches exactly 3 bits: binary 001 111 → octal 17.

You might see octal in Linux and macOS file permissions, like 755.

Hexadecimal (base 16)

Places are worth 1, 16, 256... So hex 1F = 1 × 16 + 15 = 31.

Each hex digit matches exactly 4 bits, so two hex digits make one byte: binary 1111 1111 → hex FF = 255.

Where you have seen hex: web colors

A web color like #FF6B35 is three bytes in hex: red, green, and blue, each from 00 (0) to FF (255).

#FF6B35red FF = 255, green 6B = 107, blue 35 = 53. The orange on this page!
#FF0000all red, no green, no blue
#000000everything off: black
#FFFFFFeverything at 255: white
Check the math: hex 6B = 6 × 16 + 11 = 107. (B is 11.)

The shortcut: group the bits

Because one hex digit is exactly 4 bits, you can convert binary to hex without doing any big math. Split the binary number into groups of 4 from the right, then convert each group:

1011 0110
  B    6        binary 10110110 = hex B6 = 182

Octal works the same way with groups of 3 bits.

What 755 means in file permissions

Each octal digit is 3 bits, and each bit is a yes/no switch for read, write, and execute. 7 = 111 means all three; 5 = 101 means read and execute, but not write. So 755 means "the owner can do everything; everyone else can read and run it."

  • Octal places 1, 8, 64. Hex places 1, 16, 256.
  • 1 octal digit = 3 bits. 1 hex digit = 4 bits. 2 hex digits = 1 byte.
  • Binary to hex: groups of 4 bits. Binary to octal: groups of 3.

Octal and hex follow the same pattern as binary, just with bigger place values. The reason programmers like hex is that every hex digit is exactly four bits, so a long string of binary turns into a short, neat hex number. You have probably already seen hex if you have ever picked a color for a website or a graphic.

Number Systems in Python

Writing and converting bases in Python

SystemPrefixLiteralValueConvert to text
Binary0b0b101010bin(10) → '0b1010'
Octal0o0o1210oct(10) → '0o12'
Decimal(none)1010str(10) → '10'
Hex0x0xA10hex(10) → '0xa'
  • All four literals make the same int: 10 == 0b1010 == 0o12 == 0xA is True. Python always prints ints in decimal.
  • The prefix starts with a zero, not the letter O. Uppercase works too (0XFF), but lowercase is easier to read.
  • bin(), oct(), and hex() return strings.
  • int(text, base) goes the other way: int("ff", 16) is 255.

Type any integer literal for n: 255, 0xFF, 0b1010, 0o17. Then try a broken one like 0b102.

Now turn text into a number with int(text, base):

What these tools really give you

  • A prefix literal like 0xFF is just another way to type an int. Once stored, Python forgets how you wrote it: print(0xFF) shows 255.
  • bin(), oct(), and hex() go from an int to text for showing people. You cannot do math with their result: hex(10) + 1 is a TypeError.
  • int(text, base) goes from text back to an int. The text must not have a space and must only use digits that exist in that base. int("1010", 2) is 10; uppercase and lowercase hex both work.
Think of it as a round trip: int → bin() → text like '0b1010' → int(text, 0) or int("1010", 2) → back to the same int.
  • Prefixes: 0b, 0o, 0x. All make an int.
  • bin/oct/hex give strings; int(text, base) gives an int.
  • Prefix literals are ints; bin/oct/hex make text; int(text, base) makes an int.

Python lets you type a number in any of these four systems by adding a prefix. But no matter how you type it, it is stored as the same integer, and print shows it in decimal. To see a number in another base, use bin, oct, or hex. Notice those give you back a string, in quotes. To go from text back to a number, use int with a base.

Variables

Declaring variables

In Python, you declare (create) a variable the first time you assign it a value with =:

player_name = "Ava"
  • The name goes on the left, the value on the right. 100 = score is an error.
  • Read = as "store" or "gets", not "equals": player_name gets "Ava".
  • You do not write the type. Python figures it out from the value.
  • Assigning again replaces the old value. The variable can even change type, so type(score) always reports the type of the value it holds right now.
  • Names are case sensitive: score and Score are two different variables.
  • Using a variable before you assign it gives a NameError.

Step through and watch the Variables panel. Notice how score changes from an int to a float on line 6.

How Python reads score = score + 10

This line looks impossible in math, but it makes sense in Python because the right side runs first:

  1. Python looks up the current value of score (say 0).
  2. It calculates 0 + 10, which is 10.
  3. Only then does it store 10 into score, replacing the old 0.

Two handy shortcuts

x = y = 0          # both x and y get 0
width, height = 4, 3   # width gets 4, height gets 3

A variable is a label, not a box. Think of the name as a sticky note attached to a value. Assigning again moves the sticky note to a new value.

  • First assignment creates the variable. No type keyword needed.
  • Name on the left, value on the right.
  • The right side of = is calculated first, then stored.

Some languages make you say the type when you create a variable. Python does not. The first time you assign a value, the variable exists, and its type is whatever value it holds right now. Step through the editor slowly and watch the panel on the right.

Naming Conventions

Naming variables: rules and PEP 8 style

Rules (break them and you get an error)

  • Letters, digits, and underscores only. No spaces or dashes.
  • Cannot start with a digit. Cannot be a keyword.

Style: PEP 8

PEP 8 is the official style guide for Python code. Following it makes your code look like everyone else's, so it is easier to read.

StyleExamplePEP 8 uses it for
snake_casehigh_scoreVariables and functions
UPPER_CASEMAX_SCOREConstants (values that never change)
CapWordsHighScoreClass names (later in the course)
camelCasehighScoreNot used for Python variables
  • Pick names that say what the value means: total_cost, not tc or x.
  • Never use l, O, or I as one-letter names. They look like 1 and 0.

Type a name to check the rules and the style. Try highScore, HighScore, HIGH_SCORE, high score, and high_score.

Words you cannot use as names

Python has 35 keywords that are part of its grammar, such as if, else, for, while, def, return, import, and, or, not, True, False, and None. To see the whole list, run import keyword then print(keyword.kwlist).

Allowed, but a bad idea: built-in function names like print, input, str, list, and type are not keywords, so Python lets you use them as variable names. But then the original tool is hidden. After print = 5, the line print("hi") fails with TypeError: 'int' object is not callable.

Good names answer "what is this?" count is OK, student_count is better. A name can be long; clarity matters more than saving a few keystrokes.

  • snake_case for variables. UPPER_CASE for constants. CapWords for classes.
  • Descriptive names; avoid l, O, I.
  • Never name a variable print, input, str, list, or type.

There is a difference between rules and style. Break a rule and Python gives you an error. Break a style guideline and the code still runs, but other programmers will have a harder time reading it. PEP 8 says variables should be lowercase with underscores between words. That is called snake case, because the underscores make the name low and long, like a snake.

Debugging

Common mistakes

MistakeWrong codeWhat Python 3.13 saysFix
Comma in a numberx = 1,000No error. x becomes the tuple (1, 0)x = 1000 or 1_000
Leading zerox = 007SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integersx = 7
Wrong digit for the basex = 0b102SyntaxError: invalid digit '2' in binary literalBinary uses only 0 and 1
Wrong digit for the basex = 0o9SyntaxError: invalid digit '9' in octal literalOctal uses only 0 to 7
Lowercase booleanprint(true)NameError: name 'true' is not defined. Did you mean: 'True'?True
Adding text and a numberprint("5" + 5)TypeError: can only concatenate str (not "int") to strint("5") + 5
Decimal text to intint("3.9")ValueError: invalid literal for int() with base 10: '3.9'float("3.9")
Float in bin, oct, or hexbin(2.5)TypeError: 'float' object cannot be interpreted as an integerUse an int
Quote inside a string'It's'SyntaxError: unterminated string literal (detected at line 1)"It's"
Name starts with a digit2nd_place = "Ben"SyntaxError: invalid decimal literalsecond_place

Try some of these yourself:

  • x = 007
  • 0b102
  • true
  • "5" + 5
  • int("3.9")
  • bin(2.5)

Error messages are from Python 3.13. Older versions word some messages a little differently.

The sneakiest bugs give no error

Two mistakes in this table run without any message: x = 1,000 and using text where you meant a number (like keeping input() as a string and then comparing it). For those, use print(x, type(x)) to see what the variable really holds.

A debugging routine: (1) Read the last line of the error: the type (SyntaxError, NameError, TypeError, ValueError) tells you what kind of problem it is. (2) Go to the line number shown. (3) A SyntaxError means fix the way the line is written. A TypeError means check the types. A ValueError means the type is right but the value cannot be converted.
  • Literal mistakes: commas, leading zeros, wrong digits, lowercase true.
  • Type mistakes: str + int, int("3.9"), bin(2.5).
  • No error does not mean no bug: print the value and its type.

Read the error messages carefully. Python is usually telling you exactly what went wrong. Invalid digit 2 in binary literal means you used a digit that does not exist in binary. The sneakiest mistake is the first row: a comma in a number gives no error at all.

Practice

Check yourself

Choose an answer, then click Check. This is practice only. Nothing is graded or recorded.

Check these on every question:
  • Are there quotes? Then it is a string, no matter what is inside.
  • Is there a prefix like 0b, 0o, or 0x? Then work out the place values carefully.
  • Is a name legal (rules) and is it good style (PEP 8)? Those are two different questions.
  • Quotes first, then True/False, then decimal point.
  • Prefixes 0b, 0o, 0x. snake_case for variables.

Take your time. For the number system questions, write out the place values on scratch paper before you choose.

Summary

Cheat sheet

Literal types

  • int: 42, -7, 1_000
  • float: 3.14, 2.0, 1e3
  • str: "hi", '42', ""
  • bool: True, False
  • Check with print(type(value)), which shows <class 'int'> and so on

Number systems

0b1010   # binary, base 2
0o12     # octal, base 8
10       # decimal, base 10
0xA      # hex, base 16

bin(10)  # '0b1010'
oct(10)  # '0o12'
hex(10)  # '0xa'
int("ff", 16)  # 255

Variables (PEP 8)

high_score = 0     # snake_case
player_name = "Ava"
MAX_LIVES = 3      # constant
  • Name on the left, value on the right
  • No type needed; it comes from the value
  • Descriptive names, lowercase with underscores

Before you run, check:

  • No commas or leading zeros in numbers
  • True and False are capitalized; numbers you want to do math with are not in quotes
  • Binary uses only 0-1, octal only 0-7, hex only 0-9 and A-F
  • Every variable has a descriptive snake_case name and is assigned before it is used

Key words to know

literal (a value typed in code) · variable (a name for a value) · int / float / str / bool · type() · base (how many digits a number system uses) · bit and byte · prefix (0b, 0o, 0x) · snake_case · PEP 8

  • Four literal types, four number systems, snake_case names.
  • Know the key words: literal, variable, base, bit, byte, snake_case.

Let's wrap up. Every value you type is a literal, and its form tells you its type. Integers can be written in binary, octal, decimal, or hex, but they are all the same integer underneath. And every variable you create should have a clear, lowercase, snake case name, following PEP 8.