If

If

An if statement runs a block of code only when a condition is True:

def check_in(bag_weight):
    fee = 0
    if bag_weight > 23:
        fee = 250
    return fee

print(check_in(30))
print(check_in(20))

Output:

250
0

The line fee = 250 is indented under the if, so it belongs to the if. It ran for the 30 kg bag and was skipped for the 20 kg bag.

Indentation is how Python knows which lines are inside the if. The standard indent is four spaces. The block ends where the indentation returns to the previous level — return fee is not indented under the if, so it always runs.

The colon at the end of the if line is required.

Exercise

  1. Define a function named final_price with one parameter, price.
  2. If price is greater than 100, reduce it by 10.
  3. Return the price.

final_price(150) returns 140. final_price(80) returns 80.

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

Tests

import unittest


class TestFinalPrice(unittest.TestCase):
    def test_150_is_reduced_to_140(self):
        self.assertEqual(final_price(150), 140)

    def test_80_is_unchanged(self):
        self.assertEqual(final_price(80), 80)

    def test_exactly_100_is_unchanged(self):
        self.assertEqual(final_price(100), 100)

    def test_101_is_reduced_to_91(self):
        self.assertEqual(final_price(101), 91)
def final_price(price):
    if price > 100:
        price = price - 10
    return price


print(final_price(150))
print(final_price(80))
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.