Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Python  Module 2 – Values, variables, numbers and strings

Type conversion, number bases and bitwise operators

Convert between str, int, float and bool explicitly, read and write binary, octal and hexadecimal, and use Python's bitwise operators to work with bit flags.

  • Beginner
  • 30 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 30 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Convert between str, int, float and bool explicitly, and handle the errors
  • Read yes-or-no text without relying on bool()
  • Read and write binary, octal and hexadecimal values
  • Use &, |, ^, ~, << and >> to work with bit flags
  • Predict how shifts and masks treat negative and very large ints

Before you start

What you’ll learn · Before you start

What you will learn

  • Convert between str, int, float and bool explicitly, and handle the errors
  • Read yes-or-no text without relying on bool()
  • Read and write binary, octal and hexadecimal values
  • Use &, |, ^, ~, << and >> to work with bit flags
  • Predict how shifts and masks treat negative and very large ints

Before you start

On this page

Python never turns text into a number, or a number into text, to make an operation work. "3" + 4 does not give 7 or "34": it raises TypeError, because a string and a number cannot be added. (Numbers of different types do mix: in 1 + 2.5 the int is widened to a float, so the result is 3.5.) When you need a number from text, or text from a number, you say so by calling the type you want. This lesson covers those conversions, the other ways of writing whole numbers (binary, octal and hexadecimal), and the operators that work on the individual bits of a number.

int(), float() and str() convert only when you ask

Each built-in type’s name converts a value to that type: int(), float(), str() and bool().

int(), float() and str() Python · conversions.py
# Each type's name converts a value to that type.
print(int("42") + 1, float("2.5") * 2, str(42) + "!")

# int() accepts spaces around the digits, a sign and underscores between digits.
print(int(" 7\n"), int("-12"), int("1_000"))

# From a float, int() cuts off the fraction (towards zero); round() rounds instead.
print(int(7.9), int(-7.9), round(7.9))
print(float("1e3"), float(" -0.5 "), float("inf"))
print(str(3.0), str(True), repr("3"))

# Text that is not written as a whole number raises ValueError, even "7.0".
for text in ["7.5", "7.0", "seven", ""]:
    try:
        int(text)
    except ValueError as error:
        print(error)
print(int(float("7.5")))

Output

43 5.0 42!
7 -12 1000
7 -7 8
1000.0 -0.5 inf
3.0 True '3'
invalid literal for int() with base 10: '7.5'
invalid literal for int() with base 10: '7.0'
invalid literal for int() with base 10: 'seven'
invalid literal for int() with base 10: ''
7

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 conversions.py

  • int(text) accepts spaces and line breaks around the digits, a + or - sign, and single underscores between digits. As the string-methods lesson showed, it reads decimal digits of other scripts too, such as "७".
  • int() reads whole numbers only, so text with a decimal point raises ValueError: int("7.5") does, and so does int("7.0"). Read it with float() first when that is what you mean: int(float("7.5")) is 7. (A float has limited precision, so a very long number loses its last digits on the way; decimal.Decimal keeps them all.)
  • From a float, int() drops the fraction and moves towards zero: int(7.9) is 7 and int(-7.9) is -7. Use round() when you want the nearest whole number.
  • float() also reads scientific notation ("1e3") and the special values "inf" and "nan".
  • str() gives the text you would see from print(). repr() gives the text you would write in code, which is why repr("3") shows the quotes: it tells a string "3" apart from the number 3.

Step through a loop that converts three pieces of text and keeps the ones that are whole numbers, and watch which way each try goes:

Interactive · line by line Three pieces of text, one whole number Step through the loop. The cells under texts are the strings to convert; watch which way each try goes and what reaches numbers.

Program · convert_or_refuse.py

texts = [" 42", "7.5", "ten"]
numbers = []
for text in texts:
    try:
        numbers.append(int(text))
    except ValueError:
        print("refused", text)
print(numbers)

Variables

After line 8: texts is [' 42', '7.5', 'ten']; numbers is [42]; text is 'ten'.texts' 42'0'7.5'1'ten'2numbers420text'ten'
  • just taken by the loop
  • changed in this step
  • passed by the loop
  • read next
  • where the loop stopped

Printed so far

refused 7.5
refused ten
[42]

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 18 steps are listed below.

Line run 8
Next line end
Loop pass –
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. texts = [" 42", "7.5", "ten"] makes texts a list of 3 items.
  3. Line 2. numbers = [] makes numbers a list of 0 items.
  4. Line 3. for text in texts: takes the item at position 0 of texts: text is ' 42'.
  5. Line 4. try: runs.
  6. Line 5. numbers.append(int(text)) adds 42 to the end of numbers. int() ignores the space before 42, so the number goes into the list.
  7. Line 3. for text in texts: takes the item at position 1 of texts: text is '7.5'.
  8. Line 4. try: runs.
  9. Line 5. numbers.append(int(text)) leaves numbers as it was. Key point int("7.5") raised ValueError before append could run: int() reads whole numbers only, even when the text is a valid float.
  10. Line 6. Line 6 runs. The error is a ValueError, so this except clause catches it, and the program goes on inside its block.
  11. Line 7. print("refused", text) prints refused 7.5. The block reports the refused text, and the loop moves on to the next item instead of stopping.
  12. Line 3. for text in texts: takes the item at position 2 of texts: text is 'ten'.
  13. Line 4. try: runs.
  14. Line 5. numbers.append(int(text)) leaves numbers as it was. The word ten is refused the same way. Only digits, with a sign or spaces around them, make a whole number.
  15. Line 6. Line 6 runs.
  16. Line 7. print("refused", text) prints refused ten.
  17. Line 3. for text in texts: finds no item at position 3 of texts (it has 3 items), so the loop ends.
  18. Line 8. print(numbers) prints [42]. That was the last line, so the program ends. One of the three texts became a number, and the loop went on after each refusal because the try block caught the error.

Only " 42" became a number, because int() ignored its space, while "7.5" and "ten" raised ValueError and the except block reported them. Press Edit, change int(text) to float(text) and run it: "7.5" is accepted too, and the list becomes [42.0, 7.5].

Checkpoint

Check: int(), float() and str()

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print(int(" 12\n") + int("-3"))
    Show the answer: Question 1 of 2

    Answer: 9

    int() accepts whitespace around the digits and a + or - sign in front, then returns an ordinary int.

  2. Question 2 of 2 What is int(-7.9)?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: -7

    From a float, int() cuts off the fraction, which moves the value towards zero. Use round() for the nearest whole number.

bool() of any non-empty string is True

bool() follows Python’s rules for truth: zero, None and anything empty are false, and almost everything else is true. For strings that means the only false string is "". Step through the program and watch which way its if goes for the answer “no”:

Interactive · line by line An answer of no that an if reads as yes Step through the program. Watch what bool() says about four strings, then which way the if goes for the answer no.

Program · bool_trap.py

# bool() of a string asks only one question: is it empty?
print(bool("False"), bool("0"), bool(" "), bool(""))
print(bool(0), bool(0.0), bool(42), bool(None))

answer = "no"
if answer:
    print("This line runs, although the answer was no.")

# Text that means yes or no has to be read word by word.
print(answer.strip().casefold() in ("yes", "y", "true", "1"))

Variables

After line 10: answer is 'no'.answer'no'
  • changed in this step

Printed so far

True True True False
False False True False
This line runs, although the answer was no.
False

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 7 steps are listed below.

Line run 10
Next line end
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 2.
  2. Line 2. print(bool("False"), bool("0"), bool(" "), bool("")) prints True True True False. Key point Only the empty string is false. "False", "0" and a single space all hold characters, so bool() gives True for each.
  3. Line 3. print(bool(0), bool(0.0), bool(42), bool(None)) prints False False True False.
  4. Line 5. answer = "no" sets answer to 'no'.
  5. Line 6. answer is true (answer is 'no'), so the block under if answer: runs. The bug The test asks only whether answer is empty. 'no' has two characters, so the block runs.
  6. Line 7. print("This line runs, although the answer was no.") prints This line runs, although the answer was no..
  7. Line 10. print(answer.strip().casefold() in ("yes", "y", "true", "1")) prints False. That was the last line, so the program ends. The fix Comparing the cleaned text with the words that mean yes reads the answer for what it says.

bool("False") is True, and so is bool("0"), because neither string is empty. Settings files, forms and command lines give you text such as “yes”, “off” or “0”, and the only way to read it as a yes or no is to compare it with the words you accept, as the last line does and as this lesson’s exercise asks you to do.

Testing a yes-or-no answer with if

if answer: asks whether the text is empty, so it runs for “no” as well as for “yes”. Clean the text and compare it with the words you accept: answer.strip().casefold() in ("yes", "y").

Checkpoint

Check: bool() and text

  1. Question 1 of 2 Which of these is False?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: bool("")

    bool() of a string checks one thing, whether it is empty. What the text says does not matter.

  2. Question 2 of 2 A setting may arrive as " OFF " or as " On". Which test is True for the second and False for the first?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: text.strip().casefold() == "on"

    Clean the text first, then compare it with the words you accept. That is what the lesson's last line and the exercise do.

One number can be written in base 2, 8, 10 or 16

A whole number has no base: How many digits a way of writing numbers uses: base 2 (binary) has 0 and 1, base 8 (octal) 0 to 7, and base 16 (hexadecimal) 0 to 9 and a to f. The number itself stays the same. of its own: base 10 is only how it is usually written. Python can write and read numbers in base 2 (binary), base 8 (octal) and base 16 (hexadecimal, with the digits a to f for 10 to 15):

One number, four ways of writing it Python · bases.py
n = 493

# bin(), oct() and hex() give text with a prefix; format types b, o, x and X leave it out.
print(bin(n), oct(n), hex(n))
print(f"{n:b} {n:o} {n:x} {n:X} {n:#x}")
print(f"{5:08b}", f"{n:_b}")

# In code, the same prefixes write a number in another base. It is still an ordinary int.
print(0b111101101, 0o755, 0x1ED, 0x1ED == 493)

# int(text, base) reads text in any base from 2 to 36; base 0 follows the prefix.
print(int("755", 8), int("1ed", 16), int("0x1ED", 16), int("0b101", 0))

# A colour code is three hexadecimal numbers, one each for red, green and blue.
colour = "#1E90FF"
print(int(colour[1:3], 16), int(colour[3:5], 16), int(colour[5:7], 16))

Output

0b111101101 0o755 0x1ed
111101101 755 1ed 1ED 0x1ed
00000101 1_1110_1101
493 493 493 True
493 493 493 5
30 144 255

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 bases.py

  • bin(), oct() and hex() return text with the prefixes 0b, 0o and 0x. The format types b, o, x and X write the digits without the prefix, # adds it, a width with 0 pads with zeros (08b for one byte), and _ groups the digits in fours.
  • The same prefixes write numbers in code: 0b111101101, 0o755 and 0x1ED are all the int 493, and nothing about the number remembers how it was written.
  • int(text, base) reads text in any base from 2 to 36 and accepts the matching prefix, so int("0x1ED", 16) works. With base 0, the prefix decides the base, as it does in code.
  • Hexadecimal is everywhere in computing because one hex digit is exactly four bits: colour codes such as #1E90FF are three numbers from 0 to 255, one each for red, green and blue.
Number Base Converter Convert any number between binary, octal, decimal and hexadecimal, with the working shown, to check your conversions.

Writing a number in base 2 by hand is a loop: the remainder of dividing by 2 is the next bit from the right, and the quotient is what is left to write. Step through it for 493, the number of the program above, and watch bits grow from the right:

Interactive · line by line Writing 493 in binary, one remainder at a time Step through the loop and watch n and bits. Each pass finds one bit, from the right, and halves what is left of n.

Program · to_binary.py

n = 493
bits = ""
while n > 0:
    bits = str(n % 2) + bits
    n = n // 2
print(bits, bin(493))

Variables

After line 6: n is 0; bits is '111101101'.n0bits'111101101'
  • changed in this step

Printed so far

111101101 0b111101101

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 32 steps are listed below.

Line run 6
Next line end
Loop pass –
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. n = 493 sets n to 493.
  3. Line 2. bits = "" sets bits to ''.
  4. Line 3. while n > 0: tests its condition: it is true (n is 493), so the body runs.
  5. Line 4. bits = str(n % 2) + bits sets bits to '1' (it was ''). Key point 493 is odd, so its last bit is 1. The remainder of dividing by 2 is always the bit on the right.
  6. Line 5. n = n // 2 sets n to 246 (it was 493). Floor division by 2 drops that bit, as n >> 1 would, and leaves 246 to write.
  7. Line 3. while n > 0: tests its condition: it is true (n is 246), so the body runs again (pass 2).
  8. Line 4. bits = str(n % 2) + bits sets bits to '01' (it was '1'). 246 is even, so the next bit is 0. Each new bit goes in front of the bits already found.
  9. Line 5. n = n // 2 sets n to 123 (it was 246).
  10. Line 3. while n > 0: tests its condition: it is true (n is 123), so the body runs again (pass 3).
  11. Line 4. bits = str(n % 2) + bits sets bits to '101' (it was '01').
  12. Line 5. n = n // 2 sets n to 61 (it was 123).
  13. Line 3. while n > 0: tests its condition: it is true (n is 61), so the body runs again (pass 4).
  14. Line 4. bits = str(n % 2) + bits sets bits to '1101' (it was '101').
  15. Line 5. n = n // 2 sets n to 30 (it was 61).
  16. Line 3. while n > 0: tests its condition: it is true (n is 30), so the body runs again (pass 5).
  17. Line 4. bits = str(n % 2) + bits sets bits to '01101' (it was '1101').
  18. Line 5. n = n // 2 sets n to 15 (it was 30).
  19. Line 3. while n > 0: tests its condition: it is true (n is 15), so the body runs again (pass 6).
  20. Line 4. bits = str(n % 2) + bits sets bits to '101101' (it was '01101').
  21. Line 5. n = n // 2 sets n to 7 (it was 15).
  22. Line 3. while n > 0: tests its condition: it is true (n is 7), so the body runs again (pass 7).
  23. Line 4. bits = str(n % 2) + bits sets bits to '1101101' (it was '101101').
  24. Line 5. n = n // 2 sets n to 3 (it was 7).
  25. Line 3. while n > 0: tests its condition: it is true (n is 3), so the body runs again (pass 8).
  26. Line 4. bits = str(n % 2) + bits sets bits to '11101101' (it was '1101101').
  27. Line 5. n = n // 2 sets n to 1 (it was 3).
  28. Line 3. while n > 0: tests its condition: it is true (n is 1), so the body runs again (pass 9).
  29. Line 4. bits = str(n % 2) + bits sets bits to '111101101' (it was '11101101').
  30. Line 5. n = n // 2 sets n to 0 (it was 1).
  31. Line 3. while n > 0: tests its condition: it is false (n is 0), so the loop ends.
  32. Line 6. print(bits, bin(493)) prints 111101101 0b111101101. That was the last line, so the program ends. Nine passes gave nine bits, and the loop stopped when nothing was left to divide.

Nine passes gave nine bits, 111101101, the digits that bin(493) writes after its prefix. Press Edit, change both 2s in the loop to 8 and run it: the digits become 755, the octal form of the same number.

Checkpoint

Check: Binary, octal and hexadecimal

  1. Question 1 of 2 A number fits in 16 bits. How many hexadecimal digits does it need at most?

    Type a number.

    A hint

    One hex digit holds exactly four bits.

    Show the answer: Question 1 of 2

    Answer: 4 digits

    Each hexadecimal digit stands for four bits, so 16 bits need at most 16 ÷ 4 = 4 digits: the largest, 65535, is 0xffff.

  2. Question 2 of 2 What does this print?

    Read the code, then choose one answer.

    print(int("101", 2) + int("17", 8))
    Show the answer: Question 2 of 2

    Answer: 20

    int(text, base) reads the text in that base and returns an ordinary int, which then adds like any other.

ord() and chr() convert between a character and its number

Every character is stored as its Unicode code point, a number. ord() returns the number of a one-character string and chr() returns the character for a number, so each undoes the other:

Code points and characters Python · ord_chr.py
# ord() gives the number of a character, and chr() the character of a number.
print(ord("A"), ord("a"), ord("0"), ord("अ"))
print(chr(65), chr(0x905), chr(0x1F40D))

for ch in "अआइ":
    print(ch, ord(ch), hex(ord(ch)), chr(ord(ch)) == ch)

Output

65 97 48 2309
A अ 🐍
अ 2309 0x905 True
आ 2310 0x906 True
इ 2311 0x907 True

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 ord_chr.py

The letters A to Z and a to z, and the digits 0 to 9, have consecutive numbers, which is why ord(ch) - ord("0") was a classic way to turn a digit into its value. chr() accepts numbers from 0 to 0x10FFFF, the largest code point, and raises ValueError outside that range.

These are the code points that len() counts in the strings lesson: "अ" in a literal and chr(0x905) in code make the same one-character string, अ. Press Edit, change the loop’s text from "अआइ" to "aAz" and run it: the small a and the capital A lie 32 apart.

Checkpoint

Check: ord() and chr()

  1. One question What does this print?

    Read the code, then choose one answer.

    print(ord("7") - ord("0"))
    Show the answer: One question

    Answer: 7

    ord(ch) - ord("0") turns a digit character into its value, because the ten digits are numbered in order. In real code, int(ch) says the same more clearly.

Bit flags pack several yes-or-no settings into one number

The bitwise operator: An operator that works on each bit position of whole numbers separately: & (and), | (or), ^ (exclusive or), ~ (invert), and the shifts << and >>. treat a whole number as a row of bits and work on each bit position separately:

  • a & b (and) has a 1 bit wherever both a and b have one.
  • a | b (or) has a 1 bit wherever a, b or both have one.
  • a ^ b (exclusive or) has a 1 bit wherever exactly one of them has one.
  • ~a (invert) flips every bit; for Python’s ints, ~a equals -a - 1.
  • a << n (shift left) moves the bits n places to the left, which is the same as a * 2**n.
  • a >> n (shift right) moves the bits n places to the right and drops the lowest n, the same as a // 2**n.

Their everyday use is bit flag: One bit of a whole number used as a yes-or-no setting, so that several settings share one number: mode = READ | WRITE switches two on, and mode & WRITE tests one.: several yes-or-no settings packed into one number, one bit each. Unix file permissions work that way, with read worth 4, write 2 and execute 1:

Permissions as bit flags Python · permissions.py
READ, WRITE, EXEC = 4, 2, 1

# | combines flags: each flag is one bit.
mode = READ | WRITE
print(mode, f"{mode:03b}")

# & tests a flag: the result is the flag itself, or 0.
print(mode & WRITE, mode & EXEC, bool(mode & WRITE))

# |= switches a flag on, &= ~ switches it off, ^= flips it.
mode |= EXEC
mode &= ~WRITE
print(mode, f"{mode:03b}")
mode ^= READ
print(mode, f"{mode:03b}")

# Three groups of three bits make a Unix permission such as 755.
owner, group, others = 7, 5, 5
permission = owner << 6 | group << 3 | others
print(permission, oct(permission), f"{permission:09b}")

Output

6 110
2 0 True
5 101
1 001
493 0o755 111101101

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 permissions.py

| switches flags on, & with a flag tests it (the result is the flag’s value or 0, so wrap it in bool() when you want True or False), & ~flag switches a flag off, and ^ flips one. Because one octal digit is exactly three bits, each digit of a permission such as 755 describes one group of users:

The Unix permission 755 as nine bits: 111 for the owner, 101 for the group and 101 for others, so 0o755 equals 0b111101101 and 493.ownerr14w12x114 + 2 + 17groupr14w02x114 + 15othersr14w02x114 + 150o755 = 0b111101101 = 493

One octal digit is three bits

Text description of the diagram

The diagram shows the file permission 755 as nine bits in three groups of three, labelled owner, group and others.

  • Each group has three bits for read (r), write (w) and execute (x), worth 4, 2 and 1.
  • The owner's bits are 1, 1 and 1, so the owner may read, write and execute: 4 + 2 + 1 is 7.
  • The group's bits are 1, 0 and 1, so the group may read and execute but not write: 4 + 1 is 5.
  • The bits for others are also 1, 0 and 1, which is 5 again.
  • Because one octal digit holds exactly three bits, the three digits 7, 5 and 5 can be read straight off the groups. The line at the bottom says that 0o755 in octal is 0b111101101 in binary and 493 in decimal: three ways of writing the same number.

Press Edit in the program above and set others to 0: its last line becomes 488 0o750 111101000, the group’s bits unchanged and the last three bits clear.

Chmod Calculator Tick read, write and execute for each group and see the octal number, such as 755, and the symbolic mode.

Note

Python’s enum module has a Flag class that gives each bit a name and prints combinations readably; a later lesson on enums covers it. The operators underneath are the ones in this lesson.

Checkpoint

Check: Bitwise operators and flags

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    READ, WRITE, EXEC = 4, 2, 1
    mode = READ | EXEC
    print(mode, mode & WRITE)
    Show the answer: Question 1 of 2

    Answer: 5 0

    | switches flags on and & with a flag tests it: the result is the flag's own value when it is set and 0 when it is not.

  2. Question 2 of 2 Which line switches the WRITE flag off in mode, whether or not it was on before?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: mode &= ~WRITE

    & ~flag is the way to clear a flag, | flag to set it and ^ flag to flip it.

Python’s ints behave as if they had endless sign bits

Python’s ints have no fixed size, so they have no fixed number of bits either. The documentation describes the bitwise operators as working on two's complement: The usual way computers store negative whole numbers, in which -1 has a 1 in every bit. Python's bitwise operators act as if every int had endless sign bits, so -1 >> 10 is still -1. with an endless supply of sign bits:

Ints without a fixed width Python · infinite_bits.py
# Shifting left multiplies by a power of two; shifting right floor-divides.
print(1 << 10, 1001 >> 3, -1001 >> 3)

# ~x is -x - 1: Python ints behave as if they had endless sign bits.
print(~5, ~-6, -1 >> 10)
print(bin(-5), (-5).bit_count())

# A mask such as 0xFF keeps the lowest 8 bits, which gives the two's complement byte.
print(-5 & 0xFF, f"{-5 & 0xFF:08b}")

# bit_count() (Python 3.10 and newer) counts the ones; bit_length() gives the bits needed.
print((255).bit_count(), (255).bit_length(), (2**100).bit_length())

# Bitwise operators bind more tightly than comparisons, so this means (5 & 2) == 0.
print(5 & 2 == 0)

Output

1024 125 -126
-6 5 -1
-0b101 2
251 11111011
8 8 101
True

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 infinite_bits.py

  • Shifts multiply and floor-divide by powers of two. 1001 >> 3 is 125, while -1001 >> 3 is -126: the result is rounded down, exactly like -1001 // 8. And -1 >> 10 stays -1 because the sign bits never run out.
  • bin(-5) is '-0b101': a minus sign and the bits of 5, not a row of ones. To see a negative number as the byte a fixed-width language would store, mask: A number used with & to keep only some bits of another. x & 0xFF keeps the lowest eight bits, which turns -5 into 251, the byte a fixed-width language stores. it: -5 & 0xFF keeps the lowest eight bits, 251.
  • bit_length() is the number of bits needed to write a number without its sign, and bit_count() (Python 3.10 and newer) counts its 1 bits, ignoring the sign.
  • The bitwise operators bind more tightly than comparisons, so flags & WRITE == 0 means (flags & WRITE) == 0. Brackets still make such a line easier to read.

Key idea

A Python int has as many bits as it needs, with sign bits that never run out; apply a mask such as & 0xFF whenever you need the fixed width another language would use.

Programmer Calculator (Bitwise) Try the same operations at a fixed bit width (8, 16, 32 or 64 bits) to see where Python's endless ints differ from fixed-size ones.

Checkpoint

Check: Negative and very large ints

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print(-9 >> 1)
    Show the answer: Question 1 of 2

    Answer: -5

    a >> n is a // 2**n for every int, so negative numbers round down, exactly as -1001 >> 3 gave -126 in the lesson.

  2. Question 2 of 2 What is -1 & 0xFF?

    Type a number.

    A hint

    -1 has a 1 in every bit position, and the mask keeps the lowest eight.

    Show the answer: Question 2 of 2

    Answer: 255

    In two's complement -1 is all ones, so keeping the lowest eight bits gives eight ones, 255. That is the byte a fixed-width language would store for -1.

Practise: a settings and permissions reader

Two steps make one small toolkit. The first reads yes-or-no settings and counts the 1 bits of a number; the second turns a permission number into its nine letters and back. Both steps come with starter code, sample tests you run in the page and a first hint, and you can start with either:

Code lab · 2 steps

Build a settings and permissions reader

Read yes-or-no settings and count the 1 bits of a number, then write permission numbers as rwx letters and read them back.

  1. Read yes-or-no text and count the bits of a number To do
  2. Turn a permission number into rwx letters and back To do

Exercise · Easy · Python

Read yes-or-no text and count the bits of a number

Write two small functions in bits.py.

The first, parse_bool(text), reads a yes-or-no setting, as it might appear in a settings file or a form. It returns True for "yes", "true", "on" and "1", and False for "no", "false", "off" and "0", in any mix of upper and lower case and with any spaces around the word: parse_bool(" Yes ") is True and parse_bool("OFF") is False. Any other text, the empty string included, raises ValueError. (bool(text) will not do: bool("False") is True.)

The second, count_set_bits(n), returns how many bits of the whole number n are 1: count_set_bits(255) is 8 and count_set_bits(2**100) is 1. Count them yourself with the bitwise operators & and >>: the function may not use bin(), format(), int.bit_count() or an f-string, and the sample tests check both. A negative n raises ValueError. It must also work for very large numbers, such as 2**4000 - 1.

Starter code · bits.py

def parse_bool(text):
    """Return True or False for words such as 'yes', 'OFF' or '1'; raise ValueError for anything else."""
    # Replace this line with your code.
    return bool(text)


def count_set_bits(n):
    """Return how many bits of n (0 or more) are 1, without bin(), format(), int.bit_count() or f-strings."""
    # Replace this line with your code.
    return 0
The sample tests · test_bits.py
import ast
import inspect

import bits
from bits import count_set_bits, parse_bool


def raises_value_error(function, value):
    """True when function(value) raises ValueError."""
    try:
        function(value)
    except ValueError:
        return True
    return False


def test_true_words():
    """reads yes, true, on and 1 as True, in any case and with spaces around"""
    for text in ["yes", "true", "on", "1", " Yes ", "TRUE", "On\n"]:
        assert parse_bool(text) is True, f"parse_bool({text!r})"


def test_false_words():
    """reads no, false, off and 0 as False"""
    for text in ["no", "false", "off", "0", "  NO", "False", "oFF"]:
        assert parse_bool(text) is False, f"parse_bool({text!r})"


def test_other_text():
    """raises ValueError for any other text"""
    for text in ["", "   ", "maybe", "y", "2", "yes please"]:
        assert raises_value_error(parse_bool, text), f"parse_bool({text!r}) should raise ValueError"


def test_small_numbers():
    """counts the 1 bits of small numbers"""
    assert count_set_bits(0) == 0
    assert count_set_bits(1) == 1
    assert count_set_bits(0b1011) == 3
    assert count_set_bits(255) == 8
    assert count_set_bits(256) == 1


def test_large_numbers():
    """counts the 1 bits of very large numbers"""
    assert count_set_bits(2**100) == 1
    assert count_set_bits(2**100 - 1) == 100
    assert count_set_bits(2**4000 - 1) == 4000
    assert count_set_bits(10**30) == (10**30).bit_count()


def test_negative():
    """raises ValueError for a negative number"""
    assert raises_value_error(count_set_bits, -1)
    assert raises_value_error(count_set_bits, -255)


def test_no_shortcuts():
    """counts the bits without bin(), format(), bit_count() or an f-string"""
    tree = ast.parse(inspect.getsource(bits.count_set_bits))
    for node in ast.walk(tree):
        assert not (isinstance(node, ast.Name) and node.id in ("bin", "format")), "bin() and format() are not allowed"
        assert not (isinstance(node, ast.Attribute) and node.attr in ("bit_count", "format")), "bit_count() and str.format() are not allowed"
        assert not isinstance(node, ast.JoinedStr), "f-strings are not allowed"


def test_bitwise_operators():
    """counts the bits with the bitwise operators & or >>"""
    tree = ast.parse(inspect.getsource(bits.count_set_bits))
    used = {type(node.op) for node in ast.walk(tree) if isinstance(node, (ast.BinOp, ast.AugAssign))}
    assert ast.BitAnd in used or ast.RShift in used, "look at the bits with & or >>, not with % or //"
A hint

For parse_bool(), clean the text with strip() and casefold() first, then test it with in against a tuple of the accepted words. For count_set_bits(), n & 1 is the lowest bit of n (0 or 1) and n >> 1 drops that bit, so a loop that adds n & 1 and then shifts n until it is 0 visits every bit once.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Exercise · Easy · Python

Turn a permission number into rwx letters and back

File permissions are often shown as nine letters, three for each group of users, in the order owner, group and others: rwxr-xr-x is the permission 0o755 of this lesson's figure. Python's own stat.filemode() writes them this way, after one character for the kind of file. Write two functions in perms.py.

  • mode_text(mode) takes a permission from 0 to 0o777 and returns its nine letters: r, w or x where the bit is set, and - where it is not. mode_text(0o755) returns "rwxr-xr-x" and mode_text(0o640) returns "rw-r-----".
  • mode_number(text) goes the other way: mode_number("rwxr-x---") returns 0o750, which is 488.

Both raise ValueError for what they cannot handle: a mode below 0 or above 0o777, and text that is not nine characters long or that holds anything but the expected letter or - in some position. Build the letters with the bitwise operators of this lesson, not with stat.filemode(). The sample tests import your functions from perms.py.

Starter code · perms.py

def mode_text(mode):
    """Return the nine permission letters of mode, such as 'rwxr-xr-x' for 0o755."""
    # Replace this line with your code.
    return ""


def mode_number(text):
    """Return the permission number of nine letters, such as 0o750 for 'rwxr-x---'."""
    # Replace this line with your code.
    return 0
The sample tests · test_perms.py
import ast
import inspect
import stat

import perms
from perms import mode_number, mode_text


def raises_value_error(function, value):
    """True when function(value) raises ValueError."""
    try:
        function(value)
    except ValueError:
        return True
    return False


def test_lesson_modes():
    """writes 0o755, 0o640 and 0o750 as their nine letters"""
    assert mode_text(0o755) == "rwxr-xr-x"
    assert mode_text(0o640) == "rw-r-----"
    assert mode_text(0o750) == "rwxr-x---"


def test_every_mode():
    """agrees with stat.filemode() on all 512 permissions"""
    for mode in range(0o1000):
        assert mode_text(mode) == stat.filemode(mode)[1:], oct(mode)


def test_back_to_numbers():
    """reads nine letters back into the permission number"""
    assert mode_number("rwxr-x---") == 0o750
    assert mode_number("rw-r--r--") == 0o644
    assert mode_number("---------") == 0
    for mode in range(0o1000):
        assert mode_number(stat.filemode(mode)[1:]) == mode, oct(mode)


def test_bad_modes():
    """raises ValueError for a mode outside 0 to 0o777"""
    assert raises_value_error(mode_text, -1)
    assert raises_value_error(mode_text, 0o1000)


def test_bad_text():
    """raises ValueError for text that is not nine permission letters"""
    for text in ["rwxr-xr-", "rwxr-xr-xx", "rwxr-xr-q", "xwrr-xr-x", "RWXR-XR-X", ""]:
        assert raises_value_error(mode_number, text), repr(text)


def test_no_shortcut():
    """builds the letters itself, without stat.filemode()"""
    tree = ast.parse(inspect.getsource(perms))
    names = {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)}
    names |= {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)}
    assert "filemode" not in names, "write the letters with the bitwise operators, not stat.filemode()"
A hint

Number the nine letters 0 to 8 from the left. Letter i belongs to the bit 1 << (8 - i): the owner's read bit is 1 << 8 and the others' execute bit is 1 << 0. mode & bit is 0 when that bit is clear, and the letter for a set bit at position i is "rwx"[i % 3].

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

The questions on the lesson follow. They start with the idea you have practised least, and each one explains its answer the moment you give it:

Practice that adapts to you

Practise this lesson

17 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 17 What does permissions.py print?

    What does this program print? Choose one answer.

    READ, WRITE, EXEC = 4, 2, 1
    
    # | combines flags: each flag is one bit.
    mode = READ | WRITE
    print(mode, f"{mode:03b}")
    
    # & tests a flag: the result is the flag itself, or 0.
    print(mode & WRITE, mode & EXEC, bool(mode & WRITE))
    
    # |= switches a flag on, &= ~ switches it off, ^= flips it.
    mode |= EXEC
    mode &= ~WRITE
    print(mode, f"{mode:03b}")
    mode ^= READ
    print(mode, f"{mode:03b}")
    
    # Three groups of three bits make a Unix permission such as 755.
    owner, group, others = 7, 5, 5
    permission = owner << 6 | group << 3 | others
    print(permission, oct(permission), f"{permission:09b}")
    Show the answer: Question 1 of 17

    Answer: it prints

    6 110
    2 0 True
    5 101
    1 001
    493 0o755 111101101

    READ | WRITE is 4 + 2 = 6. mode & WRITE is the flag itself (2) when it is set and 0 when it is not. Switching EXEC on and WRITE off gives 4 + 1 = 5, and flipping READ leaves 1. The last line builds 0o755, which is 493 in decimal.

  2. Question 2 of 17 What does this print?

    Read the code, then choose one answer.

    print(int(" 42 ") + int("101", 2))
    Show the answer: Question 2 of 17

    Answer: 47

    int() ignores spaces around the digits, so the first part is 42, and int("101", 2) reads binary, which is 5. The sum is 47.

  3. Question 3 of 17 What is bool("False")?

    Choose one answer.

    Show the answer: Question 3 of 17

    Answer: True

    bool() of a string only checks whether the string is empty. "False" has five characters, so it is true. To read words such as "false" or "off", compare the text with them yourself.

  4. Question 4 of 17 0o755 is a number written in octal. What is it in decimal?

    Type a number.

    Show the answer: Question 4 of 17

    Answer: 493

    7 × 64 + 5 × 8 + 5 = 448 + 40 + 5 = 493. Each octal digit stands for three bits, so 0o755 is also 0b111101101.

  5. Question 5 of 17 Which of these turn the text "ff" (or "0xff") into the number 255?

    Choose every answer that is right.

    Show the answer: Question 5 of 17

    Answer:

    • int("ff", 16)
    • int("0xff", 16)
    • int("0xff", 0)

    int(text, 16) reads hexadecimal and also accepts the 0x prefix; base 0 works out the base from the prefix. Without a base, int("ff") expects decimal digits and raises ValueError, and hex() goes the other way: it takes a number and returns text, so it raises TypeError for a string.

  6. Question 6 of 17 What does int("7.0") do?

    Choose one answer.

    Show the answer: Question 6 of 17

    Answer: It raises ValueError

    Text with a decimal point is not an int literal. Read it with float() first when that is what the text holds.

  7. Question 7 of 17 A CSV column holds prices written as "1,299.50". Which line gives the number 1299.5?

    Choose one answer.

    Show the answer: Question 7 of 17

    Answer: float(text.replace(",", ""))

    The conversion functions read numbers as Python writes them, without grouping separators. Remove the separator first, and never use eval() on data.

  8. Question 8 of 17 What does this print?

    Read the code, then choose one answer.

    print(bool("0"), bool(0))
    Show the answer: Question 8 of 17

    Answer: True False

    Text and numbers follow different truth rules: a string is false only when empty, a number only when zero.

  9. Question 9 of 17 A form sends the text "on" when a box is ticked and "off" when it is not. Which test is True only for a ticked box?

    Choose one answer.

    Show the answer: Question 9 of 17

    Answer: text.strip().casefold() == "on"

    Whenever text carries a yes or a no, read the word, not the truth of the string.

  10. Question 10 of 17 Which prefix writes a number in octal in Python code?

    Choose one answer.

    Show the answer: Question 10 of 17

    Answer: 0o

    0b, 0o and 0x mark binary, octal and hexadecimal literals. A plain leading zero is not allowed, so a C-style 0755 is a syntax error.

  11. Question 11 of 17 What does this print?

    Read the code, then choose one answer.

    colour = "#1E90FF"
    print(int(colour[3:5], 16))
    Show the answer: Question 11 of 17

    Answer: 144

    A colour code is three two-digit hexadecimal numbers. Slice out each pair and read it with base 16.

  12. Question 12 of 17 What does chr(ord("अ")) give?

    Choose one answer.

    Show the answer: Question 12 of 17

    Answer: "अ"

    ord() and chr() undo each other for every character.

  13. Question 13 of 17 ch is a lower-case letter from a to z. Which expressions give its position in the alphabet, 1 for a and 26 for z?

    Choose every answer that is right.

    Show the answer: Question 13 of 17

    Answer:

    • ord(ch) - 96
    • ord(ch) - ord("a") + 1

    Consecutive code points make letter arithmetic possible; writing ord("a") instead of 97 keeps the reason visible in the code.

  14. Question 14 of 17 Which operator switches flags on?

    Choose one answer.

    Show the answer: Question 14 of 17

    Answer: |

    Set with |, test with &, clear with & ~ and flip with ^.

  15. Question 15 of 17 Which mask keeps only the group's three bits of a permission such as 0o754?

    Choose one answer.

    Show the answer: Question 15 of 17

    Answer: 0o070

    Each octal digit is one group of three bits, so a mask with 7 in one digit and 0 in the others selects that group.

  16. Question 16 of 17 What does (255).bit_length() return?

    Choose one answer.

    Show the answer: Question 16 of 17

    Answer: 8

    bit_length() is the number of bits needed to write a number without its sign, and bit_count() the number of those bits that are 1.

  17. Question 17 of 17 A protocol needs -2 as a 16-bit two's complement value written as four hexadecimal digits. Which expression gives fffe?

    Choose one answer.

    Show the answer: Question 17 of 17

    Answer: f"{-2 & 0xFFFF:04x}"

    Python writes negative ints with a minus sign. To get a fixed-width form, mask the number to that width first: & 0xFF for 8 bits, & 0xFFFF for 16.

Interview questions

Fresher · How do you convert a string to an integer in Python, and what can go wrong?

Call int(text). It accepts spaces and a line break around the digits, a + or - sign, underscores between digits and the decimal digits of any script, so int(" -1_000\n") is -1000. Anything else raises ValueError: letters, an empty string, and also a decimal point, so int("7.5") and even int("7.0") fail; read such text with float() first, knowing that a float keeps only about 16 significant digits. Give a base for other notations, as in int("ff", 16) or int("0b101", 0), where base 0 follows the prefix. Text from users and files can always be malformed, so wrap the call in try and handle ValueError where the input arrives. Never use eval() instead, and remember that bool() of a string converts nothing: it only asks whether the string is empty.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A service reads its debug switch with DEBUG = bool(os.environ.get("APP_DEBUG", "")). Operators set APP_DEBUG=0, and later APP_DEBUG=false, to switch debug logging off, but it stays on. Explain why, fix it, and say how you would stop the same bug in the other settings.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    A function turns colour codes such as "#1E90FF" into red, green and blue with int(code[1:3]), int(code[3:5]) and int(code[5:7]). Some codes crash with ValueError, and others give wrong colours with no error at all. Explain both, fix the function, and test it.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Convert explicitly with int(), float(), str() and bool(); int("7.5") raises ValueError, int(7.9) is 7 (towards zero) and round() rounds.
  • Every non-empty string is true, "False" included, so read yes-or-no text by comparing it with the words you accept.
  • bin(), oct() and hex() write prefixed text, int(text, base) reads it back, and 0b, 0o and 0x write numbers in code.
  • ord() and chr() convert between a character and its code point.
  • &, |, ^ and ~ work bit by bit and suit bit flags; << and >> multiply and floor-divide by powers of two.
  • Python’s ints act as if they had endless sign bits: mask with & 0xFF (and so on) when you need a fixed width.

Terms in this lesson

base
How many digits a way of writing numbers uses: base 2 (binary) has 0 and 1, base 8 (octal) 0 to 7, and base 16 (hexadecimal) 0 to 9 and a to f. The number itself stays the same.
bit flag
One bit of a whole number used as a yes-or-no setting, so that several settings share one number: mode = READ | WRITE switches two on, and mode & WRITE tests one.
bitwise operator
An operator that works on each bit position of whole numbers separately: & (and), | (or), ^ (exclusive or), ~ (invert), and the shifts << and >>.
mask
A number used with & to keep only some bits of another. x & 0xFF keeps the lowest eight bits, which turns -5 into 251, the byte a fixed-width language stores.
two's complement
The usual way computers store negative whole numbers, in which -1 has a 1 in every bit. Python's bitwise operators act as if every int had endless sign bits, so -1 >> 10 is still -1.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.