summaryrefslogtreecommitdiff
path: root/py02
diff options
context:
space:
mode:
authoryctct <yctct@yctct.com>2026-06-07 08:59:04 +0200
committeryctct <yctct@yctct.com>2026-06-07 08:59:04 +0200
commit15115b4c52bfda0d1cca9fa1155beecbb873ec35 (patch)
treeb3f0975e63eb04dcba732a78ce9bd9abda8acf01 /py02
First commit, add all files
Diffstat (limited to 'py02')
-rwxr-xr-xpy02/ex0/ft_first_exception.py27
-rwxr-xr-xpy02/ex1/ft_raise_exception.py35
-rwxr-xr-xpy02/ex2/ft_different_errors.py36
-rwxr-xr-xpy02/ex3/ft_custom_errors.py63
-rwxr-xr-xpy02/ex4/ft_finally_block.py46
5 files changed, 207 insertions, 0 deletions
diff --git a/py02/ex0/ft_first_exception.py b/py02/ex0/ft_first_exception.py
new file mode 100755
index 0000000..f0c7a7b
--- /dev/null
+++ b/py02/ex0/ft_first_exception.py
@@ -0,0 +1,27 @@
+#!/usr/bin/env python3
+# https://docs.python.org/3/tutorial/errors.html#handling-exceptions
+
+def input_temperature(temp_str: str) -> int:
+ print(f" Input data is '{temp_str}'")
+ tested_value = test_temperature(temp_str)
+ return tested_value
+
+
+def test_temperature(temp):
+ try:
+ temp = int(temp)
+ except ValueError as ve:
+ print(" Caught input_temperature error:", ve)
+ else:
+ print(f" Temperature is now {temp}°C")
+ return temp
+
+
+if __name__ == "__main__":
+ print("=== Garden Temperature ===")
+ print()
+ input_temperature("25")
+ print()
+ input_temperature("abc")
+ print()
+ print(" All tests completed - program didn't crash!")
diff --git a/py02/ex1/ft_raise_exception.py b/py02/ex1/ft_raise_exception.py
new file mode 100755
index 0000000..7f33045
--- /dev/null
+++ b/py02/ex1/ft_raise_exception.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python3
+# https://docs.python.org/3/tutorial/errors.html#handling-exceptions
+
+def input_temperature(temp_str: str) -> int:
+ print(f" Input data is '{temp_str}'")
+ temp = test_temperature(temp_str)
+ return temp
+
+
+def test_temperature(temp):
+ try:
+ temp = int(temp)
+ if temp > 40:
+ raise ValueError(f"{temp}°C is too hot for plants (max 40°C)")
+ elif temp < 0:
+ raise ValueError(f"{temp}°C is too cold for plants (min 0°C)")
+ except ValueError as ve:
+ print(" Caught input_temperature error:", ve)
+ else:
+ print(f" Temperature is now {temp}°C")
+ return temp
+
+
+if __name__ == "__main__":
+ print("=== Garden Temperature ===")
+ print()
+ input_temperature("25")
+ print()
+ input_temperature("abc")
+ print()
+ input_temperature("100")
+ print()
+ input_temperature("-50")
+ print()
+ print(" All tests completed - program didn't crash!")
diff --git a/py02/ex2/ft_different_errors.py b/py02/ex2/ft_different_errors.py
new file mode 100755
index 0000000..cd64d5f
--- /dev/null
+++ b/py02/ex2/ft_different_errors.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+# https://docs.python.org/3/tutorial/errors.html#handling-exceptions
+
+def garden_operation(operation_number):
+ if operation_number == 0:
+ int("abc")
+ elif operation_number == 1:
+ 10 / 0
+ elif operation_number == 2:
+ open("/file.txt")
+ elif operation_number == 3:
+ "string" + 3
+ else:
+ print("Operation completed successfully")
+
+
+def test_error_types():
+ print("=== Garden Type Demo ===")
+ for i in range(5):
+ try:
+ print(f"Testing operation {i} ...")
+ garden_operation(i)
+ except ValueError as err:
+ print("Caught ValueError", err)
+ except ZeroDivisionError as err:
+ print("Caught ZeroDivisionError:", err)
+ except FileNotFoundError as err:
+ print("Caught FileNotFoundError:", err)
+ except TypeError as err:
+ print("Caught TypeError:", err)
+ print()
+ return print("All error types tested successfully!")
+
+
+if __name__ == "__main__":
+ test_error_types()
diff --git a/py02/ex3/ft_custom_errors.py b/py02/ex3/ft_custom_errors.py
new file mode 100755
index 0000000..57d5a47
--- /dev/null
+++ b/py02/ex3/ft_custom_errors.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python3
+
+class GardenError(Exception):
+ def __init__(self, message="Unknown plant error"):
+ self.message = message
+ # Why self.message; why not just 'message'
+ super().__init__(self.message)
+
+
+class PlantError(GardenError):
+ pass
+
+
+class WaterError(GardenError):
+ pass
+
+
+def test_plant_error(veg_item):
+ if veg_item not in veg_list:
+ raise PlantError(f"The {veg_item} is not in the list!")
+ else:
+ print("The vegetale is in the list")
+
+
+def test_water_error(level):
+ if level < 10:
+ raise WaterError("Not enough water in the tank!")
+ else:
+ print("We have enough water!")
+
+
+def main():
+ print("== Custom Garden Errors Demo")
+ print()
+ try:
+ print("Testing PlantError...")
+ test_plant_error("spinach")
+ except PlantError as err:
+ print("Caught PlantError:", err)
+ print()
+ try:
+ print("Testing WaterError...")
+ test_water_error(4)
+ except WaterError as err:
+ print("Caught WaterError:", err)
+ try:
+ print()
+ print("Testing catching all garden errors...")
+ test_plant_error("spinach")
+ except GardenError as err:
+ print("Caught GardenError:", err)
+ try:
+ test_water_error(4)
+ except GardenError as err:
+ print("Caught GardenError:", err)
+ finally:
+ print()
+ print("All custom error types work correctly!")
+
+
+if __name__ == "__main__":
+ veg_list = ["carrot", "fennel", "sesame"]
+ main()
diff --git a/py02/ex4/ft_finally_block.py b/py02/ex4/ft_finally_block.py
new file mode 100755
index 0000000..b029636
--- /dev/null
+++ b/py02/ex4/ft_finally_block.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python3
+
+class GardenError(Exception):
+ def __init__(self, message="Unknown plant error"):
+ self.message = message
+ # Why self.message; why not just 'message'
+ super().__init__(self.message)
+
+
+class PlantError(GardenError):
+ pass
+
+
+class WaterError(GardenError):
+ pass
+
+
+def water_plant(plant):
+ if plant == plant.capitalize():
+ print(f"Watering {plant}: [OK]")
+ else:
+ raise PlantError(f"Invalid plant name to water: '{plant}'")
+
+
+def test_watering_system(plants):
+ print("Open watering system")
+ try:
+ for plant in plants:
+ water_plant(plant)
+ except PlantError as err:
+ print("Caught PlantError:", err)
+ print("...ending tests and returning to main")
+ finally:
+ print("Closing watering system")
+
+
+if __name__ == "__main__":
+ print("=== Garden Watering System ===")
+ print()
+ print("Testing valid plants...")
+ test_watering_system(["Tomato", "Lettuce", "Carrots"])
+ print()
+ print("Testing invalid plants...")
+ test_watering_system(["Tomato", "lettuce", "Carrots"])
+ print()
+ print("Cleanup always happens, even with errors!")