Combining Conditions

Combining Conditions

Two range checks can be chained into one comparison:

score = 85
print(0 <= score <= 100)

Output:

True

0 <= score <= 100 means 0 <= score and score <= 100.

An if can also contain another if. The inner block is indented one more level:

def classify(order_total, is_member):
    if order_total >= 500:
        if is_member:
            return "free shipping and a gift"
        return "free shipping"
    return "standard shipping"

Nesting works, but it gets hard to read past two levels. The same logic is usually flatter with and:

def classify(order_total, is_member):
    if order_total >= 500 and is_member:
        return "free shipping and a gift"
    if order_total >= 500:
        return "free shipping"
    return "standard shipping"

Prefer the flat version when both are possible.

Exercise

A library card is issued when the applicant lives in the city and is at least 15, or has a guardian's signature at any age from 6 up.

  1. Define a function named gets_card with three parameters: is_resident, age, and has_signature.
  2. Return True when a card is issued, otherwise False.

gets_card(True, 20, False) returns True. gets_card(False, 20, False) returns False. gets_card(False, 8, True) returns True. gets_card(True, 4, True) returns False.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestGetsCard(unittest.TestCase):
    def test_adult_resident_gets_a_card(self):
        self.assertIs(gets_card(True, 20, False), True)

    def test_adult_non_resident_without_signature_does_not(self):
        self.assertIs(gets_card(False, 20, False), False)

    def test_child_of_8_with_signature_gets_a_card(self):
        self.assertIs(gets_card(False, 8, True), True)

    def test_child_of_4_never_gets_a_card(self):
        self.assertIs(gets_card(True, 4, True), False)

    def test_resident_of_exactly_15_gets_a_card(self):
        self.assertIs(gets_card(True, 15, False), True)

    def test_young_resident_without_signature_does_not(self):
        self.assertIs(gets_card(True, 12, False), False)
def gets_card(is_resident, age, has_signature):
    return (is_resident and age >= 15) or (has_signature and age >= 6)


print(gets_card(True, 20, False))
print(gets_card(False, 20, False))
print(gets_card(False, 8, True))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.