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

Booleans, None, truthiness and comparisons

Predict which Python values are truthy or falsy, use and, or and not knowing they return operands, and compare correctly with ==, is and chained comparisons.

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

What you will learn

  • Explain why True + True is 2, and turn a text answer into a bool correctly
  • Predict the truthiness of common values
  • Use and, or and not, knowing they return operands
  • Test for a missing value with is None, keeping 0 and the empty string as real answers
  • Compare with ==, is and chained comparisons correctly

Before you start

What you’ll learn · Before you start

What you will learn

  • Explain why True + True is 2, and turn a text answer into a bool correctly
  • Predict the truthiness of common values
  • Use and, or and not, knowing they return operands
  • Test for a missing value with is None, keeping 0 and the empty string as real answers
  • Compare with ==, is and chained comparisons correctly

Before you start

On this page

Programs keep asking yes-or-no questions: is the list empty, did the user type anything, is the score in range? Python’s answers are the two values True and False, but if, while, and, or and not accept almost any value, because nearly every object counts as either true or false. This lesson shows which values count as which, what and and or really return, how None fits in, and how to compare values without the classic traps.

One of those traps turns a user’s volume of 0 back up to 50 without any error, and another makes 1 < 2 == True come out False. You will step through the first, run the second, and learn the tests that avoid both.

True and False are a kind of int

True and False are the only two objects of type bool. Comparisons such as 3 > 2 produce them, and bool(value) converts any value to one of them. Under the hood, bool is a kind of int, with True worth 1 and False worth 0:

bool is a kind of int Python · bool_is_int.py
print(True == 1, False == 0)
print(True + True)
print(sum([True, False, True]))  # adding bools counts the True values
print(isinstance(True, int))  # bool is a kind of int

print(bool("False"))  # careful: any text that is not empty is true

Output

True True
2
2
True
True

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

That is why sum() of a list of bools counts the True values. Python’s documentation still discourages relying on bools behaving as numbers: when you mean a number, convert with int(flag). The last line is a common mistake when reading answers from users or files: bool("False") is True, because any string that is not empty is true. Compare the text instead, as in answer == "yes".

Version note

Using ~ (bitwise “not”) on a bool has been deprecated since Python 3.12 and is due to become an error in Python 3.16: ~True is the int -2, not False. Write not flag.

Checkpoint

Check: bool is a kind of int

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print(sum([True, True, False, True]))
    Show the answer: Question 1 of 2

    Answer: 3

    bool is a subclass of int, with True worth 1 and False worth 0, so sum() of a list of bools counts the True values: 3 here.

  2. Question 2 of 2 A form sends the answer as the text "False". What does bool(answer) give?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: True

    bool() of a string tests whether it is empty, so bool("False") is True. Compare the text instead, as in answer == "yes" or answer == "True".

Only a few values are falsy

In an if or while condition, and as an operand of and, or and not, Python treats a value as falsy: A value that counts as false in a condition. The falsy values are None, False, zero of any number type, and empty strings and collections such as "", [] and {}. or truthy: A value that counts as true in an if or while condition and in and, or and not. Every value is truthy except the falsy ones, so "0", [0] and " " are truthy.. The falsy values are few and worth knowing by heart:

  • None and False;
  • zero of any number type: 0, 0.0, 0j (and Decimal(0) and Fraction(0) from the standard library);
  • empty strings and empty collections: "", (), [], {}, set(), range(0).

Everything else is truthy, unless its class defines otherwise (classes are a later module).

Twelve values, true or false Python · truth_table.py
values = [None, False, 0, 0.0, "", [], {}, "0", " ", "False", [0], float("nan")]
for value in values:
    print(repr(value).ljust(8), bool(value))

Output

None     False
False    False
0        False
0.0      False
''       False
[]       False
{}       False
'0'      True
' '      True
'False'  True
[0]      True
nan      True

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

The last five values hold the surprises: the strings "0", " " and "False" are not empty, the list [0] has one item, and NaN is a float that is not zero, so all five are truthy. In practice, truthiness gives short, readable tests: PEP 8 recommends if items: and if not items: rather than if len(items):. Press Edit, add 0j, () and "None" to the list and run the program again: two of the three are falsy.

Version note

New in Python 3.14: NotImplemented, a special value that the comparison and arithmetic methods of classes return when they cannot handle an operand, raises TypeError when it is used as a condition. Python 3.9 to 3.13 only warned about it.

Checkpoint

Check: Truthy and falsy values

  1. Question 1 of 2 Which of these values is falsy?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 0.0

    The falsy values are None, False, zeros of every number type, and empty strings and collections. Text that shows a zero, a list holding a zero and a string of spaces are all truthy.

  2. Question 2 of 2 A block must run only when the list items has something in it. Which test does PEP 8 recommend?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: if items:

    PEP 8 recommends if items: and if not items: for sequences, because an empty sequence is falsy. Comparing a list with True is always False, and is not None asks a different question.

and and or return one of their operands

and and or evaluate their operands from left to right and stop as soon as the answer is known. They do not turn the answer into a bool: the result is the operand that decided it. The flowcharts show how each one chooses, and the program after them prints what they return:

Two flowcharts: x or y returns x when x is true, otherwise y; x and y returns x when x is false, otherwise y.x or yIs x true?noyesEvaluate yResult: yResult: xy is not evaluatedx and yIs x true?noyesResult: xy is not evaluatedEvaluate yResult: y

How or and and choose their result

Text description of the diagram

Two small flowcharts, one above the other. Both start by testing whether x is true (truthy).

  • x or y: if x is true, the result is x and y is not evaluated at all. If x is false, Python evaluates y and the result is y.
  • x and y: if x is false, the result is x and y is not evaluated at all. If x is true, Python evaluates y and the result is y.

In both cases the result is one of the two operands, not necessarily True or False.

What and and or return Python · and_or_values.py
print("" or "guest")  # or gives the first operand that is true ...
print("Asha" or "guest")
print(0 or None)  # ... or the last one, when none is true

print([] and 10)  # and gives the first operand that is false ...
print(5 and 10)  # ... or the last one, when none is false
print(0 and 1 / 0)  # 0 is false, so 1 / 0 is never evaluated

print(not "text", not 0)  # not always gives True or False

Output

guest
Asha
None
[]
10
0
False True

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

  • x or y gives x if x is true, and otherwise y. So "" or "guest" is "guest", a handy default for empty text.
  • x and y gives x if x is false, and otherwise y. In 0 and 1 / 0, the 0 already decides the answer, so the division never runs and there is no ZeroDivisionError: this is called short-circuiting: Stopping an and or an or as soon as its answer is known, so the operand on the right is never evaluated. In 0 and 1 / 0 the division never runs..
  • not is different: it always returns True or False.

A common mistake: or throws away a valid zero

The or default treats every falsy value as missing, and that includes 0 and the empty string, which are often perfectly good answers. Step through a saved volume of 0 read in two ways, and watch volume:

Interactive · line by line A volume of 0 replaced by a default Step through two ways of reading the saved volume and watch volume. The or default throws the 0 away, and the test for None keeps it.

Program · zero_trap.py

saved_volume = 0  # the user turned the sound off on purpose

volume = saved_volume or 50  # bug: the 0 is falsy, so it is replaced
print(volume)

volume = 50 if saved_volume is None else saved_volume  # only None means "not set"
print(volume)

Variables

After line 7: saved_volume is 0; volume is 0.saved_volume0volume0
  • changed in this step

Printed so far

50
0

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 6 steps are listed below.

Line run 7
Next line end
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. saved_volume = 0 sets saved_volume to 0. The user chose 0, silence, on purpose. Here 0 is a real answer, not a missing one.
  3. Line 3. volume = saved_volume or 50 sets volume to 50. The bug saved_volume or 50 gives its right operand whenever the left one is falsy, and 0 is falsy, so the user's 0 is replaced by 50.
  4. Line 4. print(volume) prints 50.
  5. Line 6. volume = 50 if saved_volume is None else saved_volume sets volume to 0 (it was 50). The fix Only None means that no volume was saved, so the test asks about None alone, and the 0 is kept.
  6. Line 7. print(volume) prints 0. That was the last line, so the program ends.

The user chose silence, and saved_volume or 50 turned it back up to 50. The fix tests for the one value that really means “not set”. a if condition else b is a conditional expression: An expression of the form a if condition else b. It evaluates the condition and gives a when the condition is true and b otherwise, evaluating only the side it picks.: it evaluates the condition and gives a when it is true and b otherwise (the next lesson places it among the operators).

Key idea

x or default replaces every falsy value, 0 and "" included. When 0 or an empty string is a real answer, test x is None instead.

Checkpoint

Check: What and and or return

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    name = ""
    print(name or "guest")
    Show the answer: Question 1 of 2

    Answer: guest

    x or y gives x when x is true and y otherwise. name is the empty string, which is falsy, so the result is "guest", a handy default for empty text.

  2. Question 2 of 2 Which of these runs without raising an error?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 0 and 1 / 0

    and and or stop as soon as the answer is known: and at the first falsy operand, or at the first truthy one. The operands after that are never evaluated.

None means no value, and is tested with is

None is the only object of its type, NoneType, and it stands for “no value here”: a setting that was not given, a result that does not exist, a search that found nothing. Functions that return nothing in particular return None:

Meet None Python · none_basics.py
result = print("Hello")  # print() shows the text and returns None
print(result)
print(result is None)
print(type(None))
print(None == 0, None == False, not None)  # falsy, but equal to neither

Output

Hello
None
True
<class 'NoneType'>
False False True

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

  • Test for it with is None and is not None, as PEP 8 recommends: there is exactly one None, and is checks for that very object, which no class can redefine.
  • None is falsy, but it is not equal to 0 or to False. Write value is None, not not value, when 0 or an empty string are valid values.
  • None takes part in no arithmetic and no ordering, so a missing value stops a program the moment it is used:
A missing score in a list Python · missing_score.py
scores = [72, None, 85]  # one student was absent
print(max(scores))

Output (exit status 1)

Printed as an error (standard error)

Traceback (most recent call last):
  File "missing_score.py", line 2, in <module>
    print(max(scores))
          ~~~^^^^^^^^
TypeError: '>' not supported between instances of 'NoneType' and 'int'

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

max() compares the items with >, and None cannot be compared with a number. Leave missing values out, or replace them, before you compute with the list.

Checkpoint

Check: None and how to test for it

  1. Question 1 of 2 Which test does PEP 8 recommend for checking that result is None?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: result is None

    PEP 8: comparisons to singletons such as None should always be made with is or is not. Truthiness is the wrong test whenever 0 or an empty value can be a real result.

  2. Question 2 of 2 scores = [72, None, 85]. What happens with max(scores)?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It raises TypeError, because None cannot be compared with a number

    None means no value, so it has no order. Leave missing values out of the list, or replace them, before you compute with it.

Comparisons give a bool, and they chain

Python has four kinds of comparison:

  • == and != compare values: 1 == 1.0 is True.
  • <, <=, > and >= compare order: "apple" < "banana" is True.
  • is and is not compare identity, whether both sides are the very same object: None is None is True.
  • in and not in test membership, which the next lesson covers: "a" in "cat" is True.

With the built-in types, all of them give a bool. They share one precedence level, and you can chained comparison: Comparisons written in a row, such as 0 <= marks <= 100, which means 0 <= marks and marks <= 100, with marks evaluated only once. them: 0 <= marks <= 100 means 0 <= marks and marks <= 100, with marks evaluated once, and Python stops at the first part that is false.

Chained comparisons Python · chained.py
marks = 75
print(0 <= marks <= 100)  # means 0 <= marks and marks <= 100
print(1 < 2 < 3, 3 > 2 > 1)

print(1 < 2 == True)  # chained too: 1 < 2 and 2 == True
print((1 < 2) == True)  # brackets end the chain

print(1 == 1.0, "1" == 1)  # numbers compare by value; text never equals a number
print("apple" < "banana", "Zebra" < "apple")  # text compares by code point

Output

True
True True
False
True
True False
True True

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

  • Chaining applies to every comparison operator, which is what makes 1 < 2 == True a puzzle: it means 1 < 2 and 2 == True, and 2 is not equal to True (which is 1), so the whole expression is False. Brackets end the chain. Better still, never compare with True or False at all: write if done:.
  • Numbers of different types compare by value, so 1 == 1.0 is True; a string is never equal to a number, and ordering a string against a number raises TypeError.
  • Strings are ordered character by character by their code points, in which the capitals A to Z all come before the small letters a to z: "Zebra" < "apple".

Checkpoint

Check: Comparisons and chaining

  1. Question 1 of 2 What does 0 <= marks <= 100 mean?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 0 <= marks and marks <= 100, with marks evaluated once

    A chain such as a <= b <= c means a <= b and b <= c, except that b is evaluated only once. Brackets end the chain.

  2. Question 2 of 2 What does this print?

    Read the code, then choose one answer.

    print("Zebra" < "apple", "apple" < "Apple")
    Show the answer: Question 2 of 2

    Answer: True False

    "Z" is 90 and "a" is 97, so "Zebra" < "apple" is True. "a" (97) is greater than "A" (65), so "apple" < "Apple" is False.

Equal values are not always the same object

== asks whether two objects have the same value; is asks whether they are the same object, which is comparing their identity: What makes an object itself and no other. It never changes while the object exists; x is y is True when both names refer to the same object, and id(x) shows the identity as a number. More in “Variables, objects and names in Python”. Two lists built separately are equal but not identical. Step through and compare the rows of a, b and c:

Interactive · line by line Equal lists, and two names for one list Step through and compare the rows. b is a list of its own that holds the same items as a, while c is drawn as the same list as a.

Program · is_vs_eq.py

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)  # the same value
print(a is b)  # but two different lists

c = a
print(c is a)  # two names for one list

answer = None
print(answer is None)  # the right way to test for None

Variables

After line 10: a is [1, 2, 3]; b is [1, 2, 3]; c is the same list as a; answer is None.a102132b102132csame list as aanswerNone
  • changed in this step

Printed so far

True
False
True
True

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 9 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 1.
  2. Line 1. a = [1, 2, 3] makes a a list of 3 items.
  3. Line 2. b = [1, 2, 3] sets b to a new list with the same items as a, [1, 2, 3]. Each [1, 2, 3] builds a new list, so b is a second list that happens to hold the same items.
  4. Line 3. print(a == b) prints True.
  5. Line 4. print(a is b) prints False. Key point a == b compared the items, which are equal. a is b asked whether the two names refer to one object, and they do not.
  6. Line 6. c = a makes c a second name for the list a names: one list, two names, not a copy. No list is built here. c becomes a second name for the list that a refers to, so c is a is True.
  7. Line 7. print(c is a) prints True.
  8. Line 9. answer = None sets answer to None.
  9. Line 10. print(answer is None) prints True. That was the last line, so the program ends. There is only one None, so is None asks exactly the right question, and no class can change its answer.

Use is for None (and for the rare object you create only to compare identity with), and == for everything else. For numbers and strings, Python may or may not reuse one object for equal values, depending on the version and on how the code was compiled, so is with them gives unreliable answers. Python 3.8 and newer warn when they see it used with a literal:

is with a number Python · is_literal.py
count = 300
print(count is 300)  # Python warns: is compares identity, not value
print(count == 300)

Output

True
True

Printed as an error (standard error)

is_literal.py:2: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
  print(count is 300)  # Python warns: is compares identity, not value

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

The program runs and the warning appears on standard error. The True from count is 300 comes from how CPython compiled this file, not from any rule of the language; a different program could print False.

Key idea

== compares values and is compares objects: use is only for None and other one-of-a-kind objects, and == for numbers, strings and everything else.

Checkpoint

Check: == against is

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    a = [1]
    c = a
    print(c is a, c == a)
    Show the answer: Question 1 of 2

    Answer: True True

    is is True only for one object under two names; == compares values. Two lists built separately with the same items would give False True.

  2. Question 2 of 2 Why should a program not test count is 300?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Whether two equal ints are one object depends on CPython and on how the code was compiled, so the answer is unreliable

    For numbers and strings, use ==. Python 3.8 and newer report a SyntaxWarning for is with a literal, as is_literal.py shows, because the result depends on details of the implementation.

Python Online Compiler Try your own truth tables and chained comparisons in the browser.

Practise: turn marks into a letter grade

Chained comparisons make range tests short and exact. Write a function that turns marks out of 100 into a letter grade and rejects marks outside 0 to 100. The sample tests check every cut-off from both sides, and a first hint is ready if you want one:

Exercise · Easy · Python

Turn marks into a letter grade

Write grade(marks), which turns marks out of 100 into a letter grade on this scale (the cut-offs are for this exercise; every college publishes its own):

  • from 90 to 100: "O"
  • from 80 up to, but not including, 90: "A+"
  • from 70 up to 80: "A"
  • from 60 up to 70: "B+"
  • from 50 up to 60: "B"
  • from 40 up to 50: "C"
  • from 0 up to 40: "F"

Marks may be whole numbers or have decimals: grade(89.5) is "A+", and grade(90) is "O". For marks below 0 or above 100, raise ValueError. Use chained comparisons such as 80 <= marks < 90; the sample tests check every cut-off from both sides.

Starter code · grades.py

def grade(marks):
    """Return the letter grade for marks from 0 to 100; raise ValueError outside that range."""
    # Replace this line with your code.
    return "F"
The sample tests · test_grades.py
from grades import grade


def raises_value_error(marks):
    """True when grade(marks) raises ValueError."""
    try:
        grade(marks)
    except ValueError:
        return True
    return False


def test_top_grade():
    """gives O from 90 up to 100"""
    assert grade(100) == "O"
    assert grade(95.5) == "O"
    assert grade(90) == "O"


def test_middle_grades():
    """gives A+, A, B+ and B from their cut-offs up to just below the next one"""
    assert grade(89.99) == "A+"
    assert grade(80) == "A+"
    assert grade(79.5) == "A"
    assert grade(70) == "A"
    assert grade(69) == "B+"
    assert grade(60) == "B+"
    assert grade(59.9) == "B"
    assert grade(50) == "B"


def test_lower_grades():
    """gives C from 40 and F below 40, down to 0"""
    assert grade(49.5) == "C"
    assert grade(40) == "C"
    assert grade(39.99) == "F"
    assert grade(0) == "F"


def test_out_of_range():
    """raises ValueError for marks below 0 or above 100"""
    assert raises_value_error(-1)
    assert raises_value_error(-0.5)
    assert raises_value_error(100.5)
    assert raises_value_error(101)
A hint

Check the range first: if not 0 <= marks <= 100: catches both kinds of bad marks in one test, and raise ValueError("…") stops the function. Then test the grades from the top down with if and elif; each test is a chained comparison such as 80 <= marks < 90, which is true for 80 and for 89.99 but not for 90.

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.

Afterwards, answer the questions on the lesson. The session asks about the idea you know least first, gets harder as you answer correctly, and explains each answer straight away:

Practice that adapts to you

Practise this lesson

16 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 16 What does this print?

    Read the code, then choose one answer.

    print(True + True)
    Show the answer: Question 1 of 16

    Answer: 2

    bool is a subclass of int, so True + True is 1 + 1, the int 2. Convert with int() when you really mean a number.

  2. Question 2 of 16 A survey stores each answer as the text "yes" or "no". Which line turns an answer into a bool correctly?

    Choose one answer.

    Show the answer: Question 2 of 16

    Answer: agreed = answer == "yes"

    bool() of a string only tests whether it is empty. To read the meaning of an answer, compare its text.

  3. Question 3 of 16 Which of these values are falsy?

    Choose every answer that is right.

    Show the answer: Question 3 of 16

    Answer:

    • None
    • 0
    • []
    • ""

    Zeros, empty strings and empty collections are falsy, and so are None and False. "0" and "False" are strings with characters in them, and [0] is a list with one item, so all three are truthy.

  4. Question 4 of 16 How many of these six values are truthy: 0, "0", [], [0], None, " "?

    Type a number.

    A hint

    A value is falsy only if it is None, False, a zero or empty.

    Show the answer: Question 4 of 16

    Answer: 3 values

    "0", [0] and " " are truthy: a string with a character in it, a list with one item, and a string holding a space. 0, [] and None are falsy.

  5. Question 5 of 16 What does and_or_values.py print?

    What does this program print? Choose one answer.

    print("" or "guest")  # or gives the first operand that is true ...
    print("Asha" or "guest")
    print(0 or None)  # ... or the last one, when none is true
    
    print([] and 10)  # and gives the first operand that is false ...
    print(5 and 10)  # ... or the last one, when none is false
    print(0 and 1 / 0)  # 0 is false, so 1 / 0 is never evaluated
    
    print(not "text", not 0)  # not always gives True or False
    Show the answer: Question 5 of 16

    Answer: it prints

    guest
    Asha
    None
    []
    10
    0
    False True

    or gives the first true operand, or the last operand when none is true (0 or None is None). and gives the first false operand, or the last one when none is false (5 and 10 is 10). Only not turns its result into a bool.

  6. Question 6 of 16 What does this print?

    Read the code, then choose one answer.

    print(repr("" or 0))
    Show the answer: Question 6 of 16

    Answer: 0

    When no operand of or is true, the result is the last operand: here 0. repr() shows it exactly, so you can see it is the int 0 and not False.

  7. Question 7 of 16 limit is a number, 0 included, or None when no limit was given. Which line sets a default of 100 only when no limit was given?

    Choose one answer.

    Show the answer: Question 7 of 16

    Answer: limit = 100 if limit is None else limit

    When 0 or an empty string is a real answer, the test must single out None. The conditional expression with is None does that; every test based on truthiness also catches 0.

  8. Question 8 of 16 limit may be a number, including 0, or None when no limit was set. Which test finds out that no limit was set?

    Choose one answer.

    Show the answer: Question 8 of 16

    Answer: if limit is None:

    Only limit is None is true for None alone. not limit is also true for a limit of 0, limit == False is true for 0 and false for None, and limit is False is never true here.

  9. Question 9 of 16 What does this print?

    Read the code, then choose one answer.

    result = print("hi")
    print(result)
    Show the answer: Question 9 of 16

    Answer: hi None

    Functions that return nothing in particular return None. print() writes its text and returns None, so result is None.

  10. Question 10 of 16 A function returns the seconds a timer has run, possibly 0, or None if the timer never started. Which test runs a block only when the timer started?

    Choose one answer.

    Show the answer: Question 10 of 16

    Answer: if seconds is not None:

    When 0 is a real answer and None means "no answer", test for None with is not None. Truthiness and comparisons with 0 each get one of the two cases wrong.

  11. Question 11 of 16 What does this print?

    Read the code, then choose one answer.

    print(1 < 2 == True)
    Show the answer: Question 11 of 16

    Answer: False

    Every comparison operator chains, so this means 1 < 2 and 2 == True. The first part is true, but 2 is not equal to True, which is worth 1, so the result is False. (1 < 2) == True would be True.

  12. Question 12 of 16 Which of these is True?

    Choose one answer.

    Show the answer: Question 12 of 16

    Answer: 1 == 1.0

    == on numbers compares values across int and float. Strings and numbers are never equal, strings order by code point, and a chain is false as soon as one of its parts is.

  13. Question 13 of 16 What does this print?

    Read the code, then choose one answer.

    print(5 > 3 == 3, (5 > 3) == 3)
    Show the answer: Question 13 of 16

    Answer: True False

    A chain compares each value with its neighbour. Brackets turn the left part into a bool first, and a bool compares with a number as 0 or 1.

  14. Question 14 of 16 What does this print?

    Read the code, then choose one answer.

    a = [1, 2]
    b = [1, 2]
    print(a == b, a is b)
    Show the answer: Question 14 of 16

    Answer: True False

    The two lists hold equal values, so == is True, but each [1, 2] creates a separate list, so they are not the same object and is is False.

  15. Question 15 of 16 a and b both hold the int 1000, worked out in different parts of a program. What can you rely on?

    Choose one answer.

    Show the answer: Question 15 of 16

    Answer: a == b is True; a is b may be True or False

    Compare numbers and strings with ==. Whether is gives True for equal values depends on the version and on how the code was compiled.

  16. Question 16 of 16 When is is the right comparison?

    Choose one answer.

    Show the answer: Question 16 of 16

    Answer: For None, and for an object you create only to compare identity with

    is compares objects, == values. Use is for None, as PEP 8 says, and for unique objects such as a value you create to mark "nothing was passed"; use == everywhere else.

Interview questions

Fresher · What is the difference between == and is in Python?

== compares values: it asks whether two objects are equal, which each type decides for itself, so [1, 2] == [1, 2] and 1 == 1.0 are both True. is compares identity: it asks whether both sides are the very same object, and no class can redefine it. Two lists built separately are equal but not identical, while b = a makes b is a true. Use is for None, as PEP 8 recommends, because there is exactly one None and a class with its own idea of equality cannot fool the test. Use == for numbers, strings and everything else: whether Python reuses one object for equal numbers or strings depends on the version and on how the code was compiled, so is with them gives unreliable answers, and Python 3.8 and newer warn when it is used with a literal.

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 timeout with timeout = config.get("timeout") or 30. An operator sets "timeout": 0 to mean no timeout at all, yet requests still stop after 30 seconds. Explain the bug, fix it, and say how you would find the same mistake elsewhere in the code base.

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

  2. Mid to senior

    In a code review you find if record == None: in a data pipeline. The author says it works in every test. Explain why PEP 8 asks for is None instead, and describe values for which == None gives a wrong or surprising result.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • True and False are a kind of int (1 and 0), but convert with int() when you mean a number.
  • The falsy values are None, False, zeros, and empty strings and collections. Everything else, including "0", "False" and [0], is truthy.
  • and and or short-circuit and return one of their operands; not always returns a bool.
  • x or default also replaces 0 and ""; test x is None when only None means “missing”.
  • Chained comparisons such as 0 <= marks <= 100 read like maths, and every comparison operator chains.
  • Use == for values and is only for None and other single objects; never compare with True or False.

Terms in this lesson

chained comparison
Comparisons written in a row, such as 0 <= marks <= 100, which means 0 <= marks and marks <= 100, with marks evaluated only once.
conditional expression
An expression of the form a if condition else b. It evaluates the condition and gives a when the condition is true and b otherwise, evaluating only the side it picks.
falsy
A value that counts as false in a condition. The falsy values are None, False, zero of any number type, and empty strings and collections such as "", [] and {}.
short-circuiting
Stopping an and or an or as soon as its answer is known, so the operand on the right is never evaluated. In 0 and 1 / 0 the division never runs.
truthy
A value that counts as true in an if or while condition and in and, or and not. Every value is truthy except the falsy ones, so "0", [0] and " " are truthy.

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.