This commit is contained in:
lfirmin
2026-01-07 21:42:11 +01:00
parent d02ef5f88a
commit 11040c45b8
25 changed files with 572 additions and 3 deletions
@@ -0,0 +1,17 @@
def test_temperature():
print("=== Garden Temperature Checker ===")
user_input = input("Testing temperature: ")
try:
temperature = int(user_input)
except ValueError:
print(f"Error: {user_input} is not a valid number")
return
if temperature < 0:
print(f"Error: {temperature}°C is too cold for plants (min 0°C)")
if temperature > 40:
print(f"Error: {temperature}°C is too hot for plants (min 0°C)")
else:
print(f"Temperature {temperature}°C is perfect for plants!")
test_temperature()
@@ -0,0 +1,40 @@
def garden_operations():
print("=== Garden Error Types Demo ===\n")
print("Testing ValueError...")
try:
int("abc")
except ValueError:
print("Caught ValueError: invalid literal for int()")
print("\nTesting ZeroDivisionError...")
try:
5 / 0
except ZeroDivisionError:
print("Caught ZeroDivisionError: division by zero")
print("\nTesting FileNotFoundError...")
try:
name = "missing.txt"
open("/home/masalvad/work/poo/garden_guardian/ex1/" + name, "r")
except FileNotFoundError:
print(f"Caught FileNotFoundError: No such file '{name}'")
print("\nTesting KeyError...")
try:
fruit = {"name": "apple", "color": "red"}
key = "price"
print(fruit[key])
except KeyError:
print(f"Caught KeyError: '{key}")
print("\nTesting multiple errors together...")
try:
fruit = {"name": "apple", "color": "red"}
key = "price"
print(fruit[key])
name = "missing.txt"
open("/home/masalvad/work/poo/garden_guardian/ex1/" + name, "r")
5 / 0
int("abc")
except (ValueError, FileExistsError, FileNotFoundError, KeyError):
print("Caught an error, but program continues!")
print("\nAll error types tested successfully!")
garden_operations()
@@ -0,0 +1,56 @@
class Plant:
def __init__(self, name, water, wilting):
self.name = name
self.water = water
self.wilting = wilting
def check_water(self):
if self.water < 5:
raise WaterError("Not enough water in the tank!")
def check_wilting(self):
if self.wilting == 1:
raise PlantError(f"The {self.name} plant is wilting!")
def check_garden(self):
if self.wilting == 1:
raise PlantError(f"The {self.name} plant is wilting!")
if self.water < 5:
raise WaterError("Not enough water in the tank!")
class GardenError(Exception):
pass
class WaterError(GardenError):
pass
class PlantError(GardenError):
pass
tomato = Plant("tomato", 2, 1)
print("=== Custom Garden Errors Demo ===")
print("\nTesting PlantError...")
try:
tomato.check_wilting()
except PlantError as e:
print("Caught PlantError:", e)
print("\nTesting WaterError...")
try:
tomato.check_water()
except WaterError as e:
print("Caught WaterError:", e)
print("\nTesting catching all garden errors...")
try:
tomato.check_garden()
except GardenError as e:
print("Caught GardenError:", e)
print("\nAll custom error types work correctly!")
@@ -0,0 +1,37 @@
class Plant:
def __init__(self, name, water):
self.name = name
self.water = water
tomato = Plant("tomato", 10)
lettuce = Plant("lettuce", 5)
carrots = Plant("carrots", 7)
def water_plants(plants_list):
print("Open watering system")
try:
for p in plants_list:
p.water += 1
print(f"Watering {p.name}")
except AttributeError:
print(f"Error: Cannot water {p} - invalid plant!")
else:
print("Watering completed successfully!")
finally:
print("Closing watering system (cleanup)")
def test_watering_system():
print("=== Garden Watering System ===")
plantlist = [tomato, lettuce, carrots]
badlist = [tomato, None, lettuce]
print("\nTesting normal watering...")
water_plants(plantlist)
print("\nTesting with error...")
water_plants(badlist)
print("\nCleanup always happens, even with errors!")
test_watering_system()
@@ -0,0 +1,48 @@
def check_plant_health(plant_name, water_level, sunlight):
if not plant_name:
raise ValueError("Plant name cannot be empty!")
if water_level < 1:
raise ValueError(f"Water level {water_level} is too low (min 1)")
if water_level > 10:
raise ValueError(f"Water level {water_level} is too high (max 10)")
if sunlight < 2:
raise ValueError(f"Sunlight hours {sunlight} is too low (min 2)")
if sunlight > 12:
raise ValueError(f"Sunlight hours {sunlight} is too high (max 12)")
return f"Plant '{plant_name}' is healthy!"
def test_plant_checks():
print("=== Garden Plant Health Checker ===")
print("\nTesting good values...")
try:
print(check_plant_health("tomato", 10, 5))
except ValueError as e:
print("Error:", e)
print("\nTesting empty plant name...")
try:
print(check_plant_health("", 10, 5))
except ValueError as e:
print("Error:", e)
print("\nTesting bad water level...")
try:
print(check_plant_health("tomato", 15, 5))
except ValueError as e:
print("Error:", e)
print("\nTesting bad sunlight hours...")
try:
print(check_plant_health("tomato", 10, 0))
except ValueError as e:
print("Error:", e)
print("\nAll error raising tests completed!")
test_plant_checks()
@@ -0,0 +1,69 @@
class Plant:
def __init__(self, name, water, sun):
self.name = name
self.water = water
self.sun = sun
def watering(self, water: int = 1) -> None:
self.water += water
print(f"Watering {self.name} success")
def check_plant_health(name, water, sun):
srt = f"Error checking {name}: "
if water < 1:
raise ValueError(f"{srt}Water level {water} is too low (min 1)")
if water > 10:
raise ValueError(f"{srt}Water level {water} is too high (max 10)")
if sun < 2:
raise ValueError(f"{srt}Sunlight hours {sun} is too low (min 2)")
if sun > 12:
raise ValueError(f"{srt}Sunlight hours {sun} is too high (max 12)")
return f"{name}: healthy (water: {water}, sun: {sun})"
class Garden:
def __init__(self):
self._plants: list[Plant] = []
def add_plant(self, plant: Plant) -> None:
if plant.name == "":
raise ValueError("Error adding plant: Plant name cannot be empty!")
else:
self._plants.append(plant)
print(f"Added {plant.name} succesfully")
def water_plants(self) -> None:
print("Open watering system")
try:
for p in self._plants:
p.water += 1
print(f"Watering {p.name}")
except AttributeError:
print(f"Error: Cannot water {p} - invalid plant!")
finally:
print("Closing watering system (cleanup)")
def check_garden_health(self) -> None:
print("\nChecking Plant health...")
for p in self._plants:
try:
print(Plant.check_plant_health(p.name, p.water, p.sun))
except ValueError as e:
print(e)
garden = Garden()
print("=== Garden Management System ===\n")
print("Adding plants to garden...")
try:
garden.add_plant(Plant("tomato", 5, 8))
garden.add_plant(Plant("lettuce", 14, 3))
garden.add_plant(Plant("", 5, 6))
except ValueError as e:
print(e)
print("\nWatering plants...")
garden.water_plants()
garden.check_garden_health()
print("Garden management system test complete!")