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.
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().
# 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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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 raisesValueError:int("7.5")does, and so doesint("7.0"). Read it withfloat()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.Decimalkeeps them all.)- From a float,
int()drops the fraction and moves towards zero:int(7.9)is 7 andint(-7.9)is -7. Useround()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 fromprint().repr()gives the text you would write in code, which is whyrepr("3")shows the quotes: it tells a string"3"apart from the number3.
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:
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
- just taken by the loop
- changed in this step
- passed by the loop
- read next
- where the loop stopped
Printed so far
Nothing printed yetrefused 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.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
texts = [" 42", "7.5", "ten"]makestextsa list of 3 items. - Line 2.
numbers = []makesnumbersa list of 0 items. - Line 3.
for text in texts:takes the item at position 0 oftexts:textis' 42'. - Line 4.
try:runs. - Line 5.
numbers.append(int(text))adds42to the end ofnumbers.int()ignores the space before 42, so the number goes into the list. - Line 3.
for text in texts:takes the item at position 1 oftexts:textis'7.5'. - Line 4.
try:runs. - Line 5.
numbers.append(int(text))leavesnumbersas it was. Key pointint("7.5")raised ValueError beforeappendcould run:int()reads whole numbers only, even when the text is a valid float. - Line 6. Line 6 runs. The error is a ValueError, so this except clause catches it, and the program goes on inside its block.
- Line 7.
print("refused", text)printsrefused 7.5. The block reports the refused text, and the loop moves on to the next item instead of stopping. - Line 3.
for text in texts:takes the item at position 2 oftexts:textis'ten'. - Line 4.
try:runs. - Line 5.
numbers.append(int(text))leavesnumbersas it was. The word ten is refused the same way. Only digits, with a sign or spaces around them, make a whole number. - Line 6. Line 6 runs.
- Line 7.
print("refused", text)printsrefused ten. - Line 3.
for text in texts:finds no item at position 3 oftexts(it has 3 items), so the loop ends. - 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()
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”:
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
- changed in this step
Printed so far
Nothing printed yetTrue 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.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 2.
- Line 2.
print(bool("False"), bool("0"), bool(" "), bool(""))printsTrue True True False. Key point Only the empty string is false. "False", "0" and a single space all hold characters, sobool()gives True for each. - Line 3.
print(bool(0), bool(0.0), bool(42), bool(None))printsFalse False True False. - Line 5.
answer = "no"setsanswerto'no'. - Line 6.
answeris true (answeris'no'), so the block underif answer:runs. The bug The test asks only whetheransweris empty. 'no' has two characters, so the block runs. - Line 7.
print("This line runs, although the answer was no.")printsThis line runs, although the answer was no.. - Line 10.
print(answer.strip().casefold() in ("yes", "y", "true", "1"))printsFalse. 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
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):
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
bin(),oct()andhex()return text with the prefixes0b,0oand0x. The format typesb,o,xandXwrite the digits without the prefix,#adds it, a width with0pads with zeros (08bfor one byte), and_groups the digits in fours.- The same prefixes write numbers in code:
0b111101101,0o755and0x1EDare 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, soint("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
#1E90FFare three numbers from 0 to 255, one each for red, green and blue.
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:
Program · to_binary.py
n = 493
bits = ""
while n > 0:
bits = str(n % 2) + bits
n = n // 2
print(bits, bin(493)) Variables
- changed in this step
Printed so far
Nothing printed yet111101101 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.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
n = 493setsnto493. - Line 2.
bits = ""setsbitsto''. - Line 3.
while n > 0:tests its condition: it is true (nis493), so the body runs. - Line 4.
bits = str(n % 2) + bitssetsbitsto'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. - Line 5.
n = n // 2setsnto246(it was493). Floor division by 2 drops that bit, asn >> 1would, and leaves 246 to write. - Line 3.
while n > 0:tests its condition: it is true (nis246), so the body runs again (pass 2). - Line 4.
bits = str(n % 2) + bitssetsbitsto'01'(it was'1'). 246 is even, so the next bit is 0. Each new bit goes in front of the bits already found. - Line 5.
n = n // 2setsnto123(it was246). - Line 3.
while n > 0:tests its condition: it is true (nis123), so the body runs again (pass 3). - Line 4.
bits = str(n % 2) + bitssetsbitsto'101'(it was'01'). - Line 5.
n = n // 2setsnto61(it was123). - Line 3.
while n > 0:tests its condition: it is true (nis61), so the body runs again (pass 4). - Line 4.
bits = str(n % 2) + bitssetsbitsto'1101'(it was'101'). - Line 5.
n = n // 2setsnto30(it was61). - Line 3.
while n > 0:tests its condition: it is true (nis30), so the body runs again (pass 5). - Line 4.
bits = str(n % 2) + bitssetsbitsto'01101'(it was'1101'). - Line 5.
n = n // 2setsnto15(it was30). - Line 3.
while n > 0:tests its condition: it is true (nis15), so the body runs again (pass 6). - Line 4.
bits = str(n % 2) + bitssetsbitsto'101101'(it was'01101'). - Line 5.
n = n // 2setsnto7(it was15). - Line 3.
while n > 0:tests its condition: it is true (nis7), so the body runs again (pass 7). - Line 4.
bits = str(n % 2) + bitssetsbitsto'1101101'(it was'101101'). - Line 5.
n = n // 2setsnto3(it was7). - Line 3.
while n > 0:tests its condition: it is true (nis3), so the body runs again (pass 8). - Line 4.
bits = str(n % 2) + bitssetsbitsto'11101101'(it was'1101101'). - Line 5.
n = n // 2setsnto1(it was3). - Line 3.
while n > 0:tests its condition: it is true (nis1), so the body runs again (pass 9). - Line 4.
bits = str(n % 2) + bitssetsbitsto'111101101'(it was'11101101'). - Line 5.
n = n // 2setsnto0(it was1). - Line 3.
while n > 0:tests its condition: it is false (nis0), so the loop ends. - Line 6.
print(bits, bin(493))prints111101101 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
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:
# 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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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()
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 bothaandbhave one.a | b(or) has a 1 bit wherevera,bor 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,~aequals-a - 1.a << n(shift left) moves the bitsnplaces to the left, which is the same asa * 2**n.a >> n(shift right) moves the bitsnplaces to the right and drops the lowestn, the same asa // 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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
| 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:
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.
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
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:
# 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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
- Shifts multiply and floor-divide by powers of two.
1001 >> 3is 125, while-1001 >> 3is -126: the result is rounded down, exactly like-1001 // 8. And-1 >> 10stays -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 & 0xFFkeeps the lowest eight bits, 251.bit_length()is the number of bits needed to write a number without its sign, andbit_count()(Python 3.10 and newer) counts its 1 bits, ignoring the sign.- The bitwise operators bind more tightly than comparisons, so
flags & WRITE == 0means(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.
Checkpoint
Check: Negative and very large ints
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.
- Read yes-or-no text and count the bits of a number To do
- 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.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
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 to0o777and returns its nine letters:r,worxwhere the bit is set, and-where it is not.mode_text(0o755)returns"rwxr-xr-x"andmode_text(0o640)returns"rw-r-----".mode_number(text)goes the other way:mode_number("rwxr-x---")returns0o750, 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].
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
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.
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.
-
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.
-
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.
Key takeaways
- Convert explicitly with
int(),float(),str()andbool();int("7.5")raisesValueError,int(7.9)is 7 (towards zero) andround()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()andhex()write prefixed text,int(text, base)reads it back, and0b,0oand0xwrite numbers in code.ord()andchr()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
- int() (Built-in Functions) (Python Software Foundation)
- Numeric Types, int, float and complex (The Python Standard Library) (Python Software Foundation)
- Truth Value Testing (The Python Standard Library) (Python Software Foundation)
- Bitwise Operations on Integer Types (The Python Standard Library) (Python Software Foundation)
- int.bit_count() and int.bit_length() (The Python Standard Library) (Python Software Foundation)
- chr() and ord() (Built-in Functions) (Python Software Foundation)
- Integer literals (The Python Language Reference) (Python Software Foundation)
- stat, Interpreting stat() results (file permission bits) (Python Software Foundation)
- CSS Color Module Level 4: the RGB hexadecimal notations (W3C CSS Working Group)
- enum.Flag (enum, Support for enumerations) (Python Software Foundation)
- Operator precedence (The Python Language Reference) (Python Software Foundation)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress