raise throws an exception on purpose. Use it when a function receives input it cannot honestly work with:
def book_seats(count):
if count < 1:
raise ValueError("count must be at least 1")
return f"{count} seats booked"
print(book_seats(2))
print(book_seats(0))
Output:
2 seats booked
Traceback (most recent call last):
...
ValueError: count must be at least 1
The message inside the parentheses appears in the traceback — write one that names the rule that was broken.
Raising is better than returning a made-up value. If book_seats(0) returned "0 seats booked" or None, the mistake would travel on through the program and surface somewhere far from its cause. The exception stops it at the source, and a caller who can handle the situation catches it with except ValueError — raise and try/except are the two ends of the same mechanism.
ValueError is the standard choice for "right type, unacceptable value". TypeError is for "wrong type entirely".
withdraw with two parameters: balance and amount.amount is negative or zero, raise ValueError with the message amount must be positive.amount is greater than balance, raise ValueError with the message insufficient funds.withdraw(100, 30) returns 70. withdraw(100, 200) raises ValueError.
Run your code to see the output, then press Submit.
import unittest
class TestWithdraw(unittest.TestCase):
def test_valid_withdrawal(self):
self.assertEqual(withdraw(100, 30), 70)
def test_whole_balance_can_be_withdrawn(self):
self.assertEqual(withdraw(100, 100), 0)
def test_zero_amount_raises_value_error(self):
with self.assertRaises(ValueError):
withdraw(100, 0)
def test_negative_amount_raises_value_error(self):
with self.assertRaises(ValueError):
withdraw(100, -5)
def test_overdraw_raises_value_error(self):
with self.assertRaises(ValueError):
withdraw(100, 200)
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > balance:
raise ValueError("insufficient funds")
return balance - amount
print(withdraw(100, 30))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.