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

@ -1 +0,0 @@
Subproject commit acf30787c8f64b85f14d97502c3e4fa1e4ce9e24

@ -1 +0,0 @@
Subproject commit 5cd38a2f67f35003c9223ee1f9d26f13c83af264

@ -1 +0,0 @@
Subproject commit 459b61d28366c6f9390fe1d847923bc7fc31be0c

View File

@ -0,0 +1,7 @@
def ft_garden_intro():
print("=== Welcome to My Garden ===")
print("Plant: Rose\nHeight: 25cm\nAge: 30 days\n\n=== End of Program ===")
if __name__ == "__main__":
ft_garden_intro()

View File

@ -0,0 +1,18 @@
class Plant:
def __init__(self, name, heigt, age):
self.name = name
self.heigt = heigt
self.age = age
def ft_garden_data():
rose = Plant("Rose: ", 25, 30)
Sunflower = Plant("Sunflower: ", 80, 45)
Cactus = Plant("Cactus: ", 15, 120)
print("=== Garden Plant Registry ===")
print(rose.name, rose.heigt, "cm,", rose.age, "days old")
print(Sunflower.name, Sunflower.heigt, "cm,", Sunflower.age, "days old")
print(Cactus.name, Cactus.heigt, "cm,", Cactus.age, "days old")
ft_garden_data()

View File

@ -0,0 +1,23 @@
class Plant:
def __init__(self, name, heigt, age):
self.name = name
self.heigt = heigt
self.age = age
def get_info(rose):
print(rose.name, rose.heigt, "cm,", rose.age, "days old")
def ft_plant_growth():
rose = Plant("Rose", 25, 30)
print("=== Day 1 ===")
get_info(rose)
rose.heigt += 6
rose.age += 6
print("=== Day 7 ===")
get_info(rose)
print("Growth this week: +6cm")
ft_plant_growth()

View File

@ -0,0 +1,22 @@
class Plant:
def __init__(self, name, height, age):
self.name = name
self.height = height
self.age = age
plant_data = [
("Rose", 25, 30),
("Oak", 200, 365),
("Cactus", 5, 90),
("Sunflower", 80, 45),
("Fern", 15, 120)
]
index = 0
plants = [Plant(name, height, age) for name, height, age in plant_data]
for p in plants:
print(f"Created: {p.name} ({p.height} cm, {p.age} days)")
index += 1
print(f"\nTotal plants created: {index}")

View File

@ -0,0 +1,34 @@
class Plant:
def __init__(self, name, height, age):
self.name = name
self.height = height
self.age = age
rose = Plant("Rose", 10, 15)
def get_height(self):
print("Invalid operation attempted: ")
print(f"height {self.height}cm [REJECTED]")
print("Security: Negative height rejected\n")
def get_age(self):
print(f"Invalid operation attempted: {self.age} days [REJECTED]")
print("Security: Negative age rejected")
def ft_garden_security():
print("=== Garden Security System ===")
if rose.height < 0:
get_height(rose)
if rose.age < 0:
get_age(rose)
if rose.age >= 0 & rose.height >= 0:
print(f"Plant created: {rose.name}")
print(f"Height updated: {rose.height}cm [OK]")
print(f"Age updated: {rose.age} days [OK]")
ft_garden_security()

View File

@ -0,0 +1,44 @@
class Plant:
def __init__(self, name, height, age):
self.name = name
self.height = height
self.age = age
self.type = type
class Tree(Plant):
def __init__(self, name, height, age, type, diameter, shade):
super().__init__(name=name, height=height, age=age)
self.diam = diameter
self.shade = shade
self.type = type
class Flower(Plant):
def __init__(self, name, height, age, type, color, bloom):
super().__init__(name=name, height=height, age=age)
self.color = color
self.bloom = bloom
self.type = type
class Vegetable(Plant):
def __init__(self, name, height, age, type, season, nutrional):
super().__init__(name=name, height=height, age=age)
self.season = season
self.nutrional = nutrional
self.type = type
r = Flower("Rose", 25, 30, "Flower", "red", "blooming")
o = Tree("Oak", 500, 1825, "Tree", 50, 78)
t = Vegetable("Tomato", 80, 90, "Vegatable", "summer",
"vitamin C")
print("=== Garden Plant Types ===\n")
print(f"{r.name} ({r.type}): {r.height}cm, {r.age} days, {r.color} color")
print(f"{r.name} is {r.bloom} beautifully !\n")
print(f"{o.name} ({o.type}): {o.height}cm, {o.age} days, {o.diam}cm diameter")
print(f"{o.name} provides {o.shade} square meters of shade\n")
print(f"{t.name} ({t.type}): {t.height}cm, {t.age} days, {t.season} harvest")
print(f"{t.name} is rich in {t.nutrional}")

View File

@ -0,0 +1,105 @@
class Plant:
def __init__(self, name, height, color, bloom, Prize):
self.name = name
self.height = height
self.color = color
self.bloom = bloom
self.Prize = Prize
def grow(self, heigt: int = 1) -> None:
self.height += heigt
print(f"{self.name} grew {heigt}cm")
class Garden:
def __init__(self, owner: str):
self.owner = owner
self._plants: list[Plant] = []
self.score = 0
def add_plant(self, plant: Plant) -> None:
self._plants.append(plant)
print(f"Added {plant.name} to {self.owner}'s garden")
def help_all_plants_grow(self) -> int:
print(f"\n{self.owner} is helping all plants grow...")
count = 0
for plant in self._plants:
plant.grow(1)
count += 1
return (count)
def list_plants(self) -> None:
print(f"\n=== {self.owner}'s Garden Report ===")
print("Plants in garden:")
for plant in self._plants:
display = f"- {plant.name}: {plant.height}cm"
if (plant.color != ""):
display += f", {plant.color} flowers"
if (plant.bloom == 1):
display += " (blooming)"
if (plant.Prize > 0):
display += f", Prize point: {plant.Prize}"
print(display)
def list_update(self, height) -> None:
regular = 0
flowering = 0
prize = 0
print(f"\nPlants added: {len(self._plants)}, Total growth: {height}cm")
for plant in self._plants:
if plant.bloom == 1:
flowering += 1
if plant.Prize > 0:
prize += 1
if (plant.Prize == 0) & (plant.bloom == 0):
regular += 1
update = f"Plant types: {regular} regular, {flowering} flowering, "
update += f"{prize} prize flowers\n"
print(update)
class GardenManager:
def __init__(self):
self._garden: list[Garden] = []
def add_garden(self, garden: Garden) -> None:
self._garden.append(garden)
def garden_list(self) -> None:
result = "Garden scores"
len = 0
totalheight = 0
for Garden in self._garden:
for plant in Garden._plants:
Garden.score += plant.height
Garden.score += 10
if plant.bloom == 1:
Garden.score += 10
totalheight += plant.height
len += 1
result += f" - {Garden.owner}: {Garden.score}"
if (totalheight >= 200):
print("Height validation test: True")
else:
print("Height validation test: False")
print(result)
print(f"Total gardens managed: {len}")
print("=== Garden Management System Demo ===\n")
alice = Garden("Alice")
alice.add_plant(Plant("Oak Tree", 100, "", 0, 0))
alice.add_plant(Plant("Rose", 25, "red", 1, 0))
alice.add_plant(Plant("Sunflower", 50, "yellow", 0, 10))
Bob = Garden("Bob")
Bob.add_plant(Plant("Acacia Tree", 82, "", "", 0))
Manager = GardenManager()
Manager.add_garden(alice)
Manager.add_garden(Bob)
original = 0
original += alice.help_all_plants_grow()
alice.list_plants()
alice.list_update(original)
Manager.garden_list()

View File

@ -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()

View File

@ -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()

View File

@ -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!")

View File

@ -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()

View File

@ -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()

View File

@ -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!")

View File

@ -0,0 +1 @@
print("Hello, Garden Community!")

View File

@ -0,0 +1,4 @@
def ft_plot_area():
lenght = int(input("Enter length: "))
widht = int(input("Enter Widht: "))
print("Plot area:", lenght * widht)

View File

@ -0,0 +1,5 @@
def ft_harvest_total():
day = int(input("Day 1 harvest: "))
day += int(input("Day 2 harvest: "))
day += int(input("Day 3 harvest: "))
print("Total harvest:", day)

View File

@ -0,0 +1,6 @@
def ft_plant_age():
age = int(input("Enter plant age in days: "))
if age > 60:
print("Plant is ready to harvest!")
else:
print("Plant needs more time to grow.")

View File

@ -0,0 +1,6 @@
def ft_water_reminder():
day = int(input("Days since last watering: "))
if day > 2:
print("Water the plants!")
else:
print("Plants are fine")

View File

@ -0,0 +1,6 @@
def ft_count_harvest_iterative():
day = int(input("Days until harvest: "))
while day > 0:
print("Day", 5 - day + 1)
day = day - 1
print("Harvest time!")

View File

@ -0,0 +1,9 @@
def ft_count_harvest_recursive(day=None, last=None):
if day is None and last is None:
last = int(input("Days until harvest: "))
day = 1
if day > last:
print("Harvest time!")
return
print("Day", day)
ft_count_harvest_recursive(day + 1, last)

View File

@ -0,0 +1,4 @@
def ft_garden_summary():
name = input("Enter garden name: ")
number = input("Enter number of plants: ")
print("Garden:", name, "\nPlants:", number, "\nStatus: Growing Well!")

View File

@ -0,0 +1,11 @@
def ft_seed_inventory(seed_type: str, quantity: int, unit: str) -> None:
seed_type = seed_type.lower()
seed_type = seed_type[0].upper() + seed_type[1:]
if unit == "packets":
print(seed_type, "seeds:", quantity, unit, "available")
elif unit == "grams":
print(seed_type, "seeds:", quantity, unit, "total")
elif unit == "area":
print(seed_type, "seeds: covers", quantity, "square meters")
else:
print("Unknown unit type")