Repository files navigation

Python Piscine — 42 School

User:jericard

This repository contains the completed modules from the 42 School Python Piscine. Each module introduces a new set of skills, building upon the previous ones to progressively master the language.


Index


Module00 — Python Fundamentals

Objective: Introduction to basic Python syntax. Covers defining functions with type annotations, handling variables, reading user input, applying conditionals, iterating with loops, formatting strings with f-strings, and building both iterative and recursive solutions. The exercises follow a garden and harvest theme.

ExerciseMain concept
ft_hello_garden.pyFunction definition and type annotations
ft_plot_area.pyVariables, user input, and arithmetic
ft_harvest_total.pySumming multiple inputs
ft_plant_age.pyif/else conditionals
ft_water_reminder.pyMore conditionals with numeric comparisons
ft_count_harvest_*.pyfor loops vs. recursion
ft_garden_summary.pyString formatting with f-strings
ft_seed_inventory.pyFunctions with multiple parameters and conditional logic

Module01 — Object-Oriented Programming

Objective: Master the pillars of OOP in Python. Covers designing classes with __init__ and __str__, applying encapsulation through private attributes and getters/setters, building inheritance hierarchies using super(), and exploring static methods, class methods, and nested classes. The entire module uses a plant and garden ecosystem as its metaphor.

ExerciseMain concept
ft_garden_intro.pyScript structure with if __name__ == "__main__"
ft_garden_data.pyBasic class with __init__ and __str__
ft_plant_growth.pyInstance methods that modify state
ft_plant_factory.pyCreating multiple instances and typed lists
ft_garden_security.pyEncapsulation: private attributes, getters and setters
ft_plant_types.pyMultiple inheritance: Plant → Flower, Tree, Vegetable
ft_garden_analytics.pyNested classes, static methods, class methods, polymorphism

Module02 — Exception Handling

Objective: Learn to write robust code through Python's exception system. Covers try/except blocks for specific error types, the finally clause to guarantee cleanup, using raise to throw exceptions manually, and creating custom exception hierarchies that inherit from Exception. The context is a garden management system with watering and plant health errors.

ExerciseMain concept
ft_first_exception.pyBasic try/except, ValueError, error codes
ft_different_errors.pyMultiple exception types in a single block
ft_custom_errors.pyCustom exception classes with inheritance (GardenError, PlantError, WaterError)
ft_finally_block.pyfinally clause for guaranteed cleanup
ft_raise_errors.pyExplicit raise with descriptive messages
ft_garden_management.pyCombining all concepts: error recovery patterns

Module03 — Advanced Data Structures

Objective: Explore Python's native collections beyond lists: tuples, sets, and nested dictionaries. Also covers command-line arguments (sys.argv), generators with yield, and all three comprehension forms (list, dict, and set comprehensions). The theme revolves around video game analytics.

ExerciseMain concept
ft_command_quest.pysys.argv, argument parsing
ft_score_analytics.pyLists: sum, average, min, max
ft_coordinate_system.pyTuples, unpacking, 3D distance calculation
ft_achievement_tracker.pySets: union, intersection, difference
ft_inventory_system.pyNested dictionaries, iteration, .items()
ft_data_stream.pyGenerators with yield (primes, Fibonacci, events)
ft_analytics_dashboard.pyList, dictionary, and set comprehensions

Module04 — File Input/Output

Objective: Handle text files and I/O streams in Python. Covers opening modes (r, w), the importance of closing files correctly, using context managers (with) as best practice, accessing standard streams (sys.stdin, sys.stdout, sys.stderr), and handling file access errors such as FileNotFoundError and PermissionError. The theme is a file archive and vault system.

ExerciseMain concept
ft_ancient_text.pyReading files with open() and manual close
ft_archive_creation.pyWriting files and FileExistsError
ft_stream_management.pysys.stdin, sys.stdout, sys.stderr, readline() and write()
ft_vault_security.pyContext managers (with) for safe file handling
ft_crisis_response.pyMultiple exceptions: FileNotFoundError, PermissionError

Module05 — Abstract Classes and Polymorphism

Objective: Deepen OOP knowledge through abstract base classes (ABC) that define mandatory interfaces. Covers implementing multiple concrete classes that fulfill the same contract, practicing true polymorphism (a function works with any subtype without knowing it), and introducing duck typing with Protocol for composition without inheritance. The scenario is a data processing pipeline with different input types.

ExerciseMain concept
data_processor.pyABC, abstract methods, three concrete implementations (NumericProcessor, TextProcessor, LogProcessor)
data_stream.pyPolymorphic orchestrator, @staticmethod for validation, automatic routing
data_pipeline.pyDuck typing with Protocol, CSV and JSON export plugins

Module06 — Packages and Module System

Objective: Understand how Python organizes code into packages and modules. Covers different import styles (import module, from module import name), subpackage structure with __init__.py, controlled symbol exposure with __all__, and import aliasing. The module uses an alchemy package (alchemy) with subpackages for spells and recipes.

ExerciseMain concept
ft_alembic_0.py / ft_alembic_1.pyimport module vs. from module import name
ft_distillation_*.pyImports from nested subpackages
ft_transmutation_*.pyFull namespace paths in deep hierarchies
alchemy/__init__.py__all__, aliasing with as, re-exporting subpackages

Module07 — Advanced Design Patterns

Objective: Apply classic software engineering design patterns in Python. Covers the Factory Pattern (creating objects without specifying the concrete class), the Mixin Pattern (adding capabilities through multiple inheritance), and the Strategy Pattern (encapsulating interchangeable algorithms). The scenario is a Pokémon-style creature battle system.

ExerciseMain concept
ex0/battle.pyFactory Pattern: CreatureFactory, FlameFactory, AquaFactory
ex1/capacitor.pyMixin interfaces: HealCapability, TransformCapability, multiple inheritance
ex2/tournament.pyStrategy Pattern: NormalStrategy, DefensiveStrategy, AggressiveStrategy, isinstance() for dynamic dispatch

Module08 — Virtual Environments and Configuration

Objective: Master the infrastructure needed for real Python projects. Covers creating and detecting virtual environments (venv), managing dependencies with pip and poetry, consuming external APIs with requests, analyzing data with pandas and numpy, generating charts with matplotlib, and handling sensitive configuration through environment variables with python-dotenv. The theme is the Matrix universe.

ExerciseMain concept
construct.pyVirtual environment detection, sys.prefix, site.getsitepackages()
loading.pyDependencies with importlib.metadata, Binance API, data analysis with pandas/numpy, visualization with matplotlib
oracle.pyEnvironment variables with dotenv, environment-based config (dev/prod), secret validation

Module09 — Data Validation with Pydantic

Objective: Use Pydantic v2 to guarantee data integrity in Python. Covers creating models with BaseModel, declaring field constraints with Field (numeric ranges, string lengths, default values), defining Enum for controlled values, building custom validators with @model_validator for cross-field business rules, and composing nested models with collection-level validation. The scenario is a space station.

ExerciseMain concept
ex0/space_station.pyBaseModel, Field with ge, le, min_length, model_validate(), ValidationError
ex1/alien_contact.pyEnum, @model_validator(mode='after'), cross-field validations
ex2/space_crew.pyNested models (List[CrewMember]), collection validators, experience and leadership rules

Module10 — Functional Programming

Objective: Master the functional programming paradigm in Python. Covers lambda functions, filter(), map(), and sorted() with custom keys; building higher-order functions that receive and return functions; exploring closures and the nonlocal keyword for encapsulated state; using the functools module (reduce, partial, lru_cache, singledispatch); and implementing decorators with and without parameters using @functools.wraps. The context is a world of wizards and spells.

ExerciseMain concept
ex0/lambda_spells.pyLambdas, sorted(), filter(), map(), max(), min() with key functions
ex1/higher_magic.pyHigher-order functions, composition, Callable type hints
ex2/scope_mysteries.pyClosures, nonlocal, stateful functions, functional factory pattern
ex3/functools_artifacts.pyreduce, partial, lru_cache, singledispatch
ex4/decorator_mastery.pySimple and parameterized decorators, @functools.wraps, timer, validator, retry

42 School — Python Piscine | jericard

About

The 11 modules of the 42 Python Piscine: OOP, exceptions, data structures, file I/O, packaging, design patterns, Pydantic and functional programming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Python Piscine — 42 School

User:jericard

This repository contains the completed modules from the 42 School Python Piscine. Each module introduces a new set of skills, building upon the previous ones to progressively master the language.


Index


Module00 — Python Fundamentals

Objective: Introduction to basic Python syntax. Covers defining functions with type annotations, handling variables, reading user input, applying conditionals, iterating with loops, formatting strings with f-strings, and building both iterative and recursive solutions. The exercises follow a garden and harvest theme.

ExerciseMain concept
ft_hello_garden.pyFunction definition and type annotations
ft_plot_area.pyVariables, user input, and arithmetic
ft_harvest_total.pySumming multiple inputs
ft_plant_age.pyif/else conditionals
ft_water_reminder.pyMore conditionals with numeric comparisons
ft_count_harvest_*.pyfor loops vs. recursion
ft_garden_summary.pyString formatting with f-strings
ft_seed_inventory.pyFunctions with multiple parameters and conditional logic

Module01 — Object-Oriented Programming

Objective: Master the pillars of OOP in Python. Covers designing classes with __init__ and __str__, applying encapsulation through private attributes and getters/setters, building inheritance hierarchies using super(), and exploring static methods, class methods, and nested classes. The entire module uses a plant and garden ecosystem as its metaphor.

ExerciseMain concept
ft_garden_intro.pyScript structure with if __name__ == "__main__"
ft_garden_data.pyBasic class with __init__ and __str__
ft_plant_growth.pyInstance methods that modify state
ft_plant_factory.pyCreating multiple instances and typed lists
ft_garden_security.pyEncapsulation: private attributes, getters and setters
ft_plant_types.pyMultiple inheritance: Plant → Flower, Tree, Vegetable
ft_garden_analytics.pyNested classes, static methods, class methods, polymorphism

Module02 — Exception Handling

Objective: Learn to write robust code through Python's exception system. Covers try/except blocks for specific error types, the finally clause to guarantee cleanup, using raise to throw exceptions manually, and creating custom exception hierarchies that inherit from Exception. The context is a garden management system with watering and plant health errors.

ExerciseMain concept
ft_first_exception.pyBasic try/except, ValueError, error codes
ft_different_errors.pyMultiple exception types in a single block
ft_custom_errors.pyCustom exception classes with inheritance (GardenError, PlantError, WaterError)
ft_finally_block.pyfinally clause for guaranteed cleanup
ft_raise_errors.pyExplicit raise with descriptive messages
ft_garden_management.pyCombining all concepts: error recovery patterns

Module03 — Advanced Data Structures

Objective: Explore Python's native collections beyond lists: tuples, sets, and nested dictionaries. Also covers command-line arguments (sys.argv), generators with yield, and all three comprehension forms (list, dict, and set comprehensions). The theme revolves around video game analytics.

ExerciseMain concept
ft_command_quest.pysys.argv, argument parsing
ft_score_analytics.pyLists: sum, average, min, max
ft_coordinate_system.pyTuples, unpacking, 3D distance calculation
ft_achievement_tracker.pySets: union, intersection, difference
ft_inventory_system.pyNested dictionaries, iteration, .items()
ft_data_stream.pyGenerators with yield (primes, Fibonacci, events)
ft_analytics_dashboard.pyList, dictionary, and set comprehensions

Module04 — File Input/Output

Objective: Handle text files and I/O streams in Python. Covers opening modes (r, w), the importance of closing files correctly, using context managers (with) as best practice, accessing standard streams (sys.stdin, sys.stdout, sys.stderr), and handling file access errors such as FileNotFoundError and PermissionError. The theme is a file archive and vault system.

ExerciseMain concept
ft_ancient_text.pyReading files with open() and manual close
ft_archive_creation.pyWriting files and FileExistsError
ft_stream_management.pysys.stdin, sys.stdout, sys.stderr, readline() and write()
ft_vault_security.pyContext managers (with) for safe file handling
ft_crisis_response.pyMultiple exceptions: FileNotFoundError, PermissionError

Module05 — Abstract Classes and Polymorphism

Objective: Deepen OOP knowledge through abstract base classes (ABC) that define mandatory interfaces. Covers implementing multiple concrete classes that fulfill the same contract, practicing true polymorphism (a function works with any subtype without knowing it), and introducing duck typing with Protocol for composition without inheritance. The scenario is a data processing pipeline with different input types.

ExerciseMain concept
data_processor.pyABC, abstract methods, three concrete implementations (NumericProcessor, TextProcessor, LogProcessor)
data_stream.pyPolymorphic orchestrator, @staticmethod for validation, automatic routing
data_pipeline.pyDuck typing with Protocol, CSV and JSON export plugins

Module06 — Packages and Module System

Objective: Understand how Python organizes code into packages and modules. Covers different import styles (import module, from module import name), subpackage structure with __init__.py, controlled symbol exposure with __all__, and import aliasing. The module uses an alchemy package (alchemy) with subpackages for spells and recipes.

ExerciseMain concept
ft_alembic_0.py / ft_alembic_1.pyimport module vs. from module import name
ft_distillation_*.pyImports from nested subpackages
ft_transmutation_*.pyFull namespace paths in deep hierarchies
alchemy/__init__.py__all__, aliasing with as, re-exporting subpackages

Module07 — Advanced Design Patterns

Objective: Apply classic software engineering design patterns in Python. Covers the Factory Pattern (creating objects without specifying the concrete class), the Mixin Pattern (adding capabilities through multiple inheritance), and the Strategy Pattern (encapsulating interchangeable algorithms). The scenario is a Pokémon-style creature battle system.

ExerciseMain concept
ex0/battle.pyFactory Pattern: CreatureFactory, FlameFactory, AquaFactory
ex1/capacitor.pyMixin interfaces: HealCapability, TransformCapability, multiple inheritance
ex2/tournament.pyStrategy Pattern: NormalStrategy, DefensiveStrategy, AggressiveStrategy, isinstance() for dynamic dispatch

Module08 — Virtual Environments and Configuration

Objective: Master the infrastructure needed for real Python projects. Covers creating and detecting virtual environments (venv), managing dependencies with pip and poetry, consuming external APIs with requests, analyzing data with pandas and numpy, generating charts with matplotlib, and handling sensitive configuration through environment variables with python-dotenv. The theme is the Matrix universe.

ExerciseMain concept
construct.pyVirtual environment detection, sys.prefix, site.getsitepackages()
loading.pyDependencies with importlib.metadata, Binance API, data analysis with pandas/numpy, visualization with matplotlib
oracle.pyEnvironment variables with dotenv, environment-based config (dev/prod), secret validation

Module09 — Data Validation with Pydantic

Objective: Use Pydantic v2 to guarantee data integrity in Python. Covers creating models with BaseModel, declaring field constraints with Field (numeric ranges, string lengths, default values), defining Enum for controlled values, building custom validators with @model_validator for cross-field business rules, and composing nested models with collection-level validation. The scenario is a space station.

ExerciseMain concept
ex0/space_station.pyBaseModel, Field with ge, le, min_length, model_validate(), ValidationError
ex1/alien_contact.pyEnum, @model_validator(mode='after'), cross-field validations
ex2/space_crew.pyNested models (List[CrewMember]), collection validators, experience and leadership rules

Module10 — Functional Programming

Objective: Master the functional programming paradigm in Python. Covers lambda functions, filter(), map(), and sorted() with custom keys; building higher-order functions that receive and return functions; exploring closures and the nonlocal keyword for encapsulated state; using the functools module (reduce, partial, lru_cache, singledispatch); and implementing decorators with and without parameters using @functools.wraps. The context is a world of wizards and spells.

ExerciseMain concept
ex0/lambda_spells.pyLambdas, sorted(), filter(), map(), max(), min() with key functions
ex1/higher_magic.pyHigher-order functions, composition, Callable type hints
ex2/scope_mysteries.pyClosures, nonlocal, stateful functions, functional factory pattern
ex3/functools_artifacts.pyreduce, partial, lru_cache, singledispatch
ex4/decorator_mastery.pySimple and parameterized decorators, @functools.wraps, timer, validator, retry

42 School — Python Piscine | jericard

About

The 11 modules of the 42 Python Piscine: OOP, exceptions, data structures, file I/O, packaging, design patterns, Pydantic and functional programming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Python Piscine — 42 School

User:jericard

This repository contains the completed modules from the 42 School Python Piscine. Each module introduces a new set of skills, building upon the previous ones to progressively master the language.


Index


Module00 — Python Fundamentals

Objective: Introduction to basic Python syntax. Covers defining functions with type annotations, handling variables, reading user input, applying conditionals, iterating with loops, formatting strings with f-strings, and building both iterative and recursive solutions. The exercises follow a garden and harvest theme.

ExerciseMain concept
ft_hello_garden.pyFunction definition and type annotations
ft_plot_area.pyVariables, user input, and arithmetic
ft_harvest_total.pySumming multiple inputs
ft_plant_age.pyif/else conditionals
ft_water_reminder.pyMore conditionals with numeric comparisons
ft_count_harvest_*.pyfor loops vs. recursion
ft_garden_summary.pyString formatting with f-strings
ft_seed_inventory.pyFunctions with multiple parameters and conditional logic

Module01 — Object-Oriented Programming

Objective: Master the pillars of OOP in Python. Covers designing classes with __init__ and __str__, applying encapsulation through private attributes and getters/setters, building inheritance hierarchies using super(), and exploring static methods, class methods, and nested classes. The entire module uses a plant and garden ecosystem as its metaphor.

ExerciseMain concept
ft_garden_intro.pyScript structure with if __name__ == "__main__"
ft_garden_data.pyBasic class with __init__ and __str__
ft_plant_growth.pyInstance methods that modify state
ft_plant_factory.pyCreating multiple instances and typed lists
ft_garden_security.pyEncapsulation: private attributes, getters and setters
ft_plant_types.pyMultiple inheritance: Plant → Flower, Tree, Vegetable
ft_garden_analytics.pyNested classes, static methods, class methods, polymorphism

Module02 — Exception Handling

Objective: Learn to write robust code through Python's exception system. Covers try/except blocks for specific error types, the finally clause to guarantee cleanup, using raise to throw exceptions manually, and creating custom exception hierarchies that inherit from Exception. The context is a garden management system with watering and plant health errors.

ExerciseMain concept
ft_first_exception.pyBasic try/except, ValueError, error codes
ft_different_errors.pyMultiple exception types in a single block
ft_custom_errors.pyCustom exception classes with inheritance (GardenError, PlantError, WaterError)
ft_finally_block.pyfinally clause for guaranteed cleanup
ft_raise_errors.pyExplicit raise with descriptive messages
ft_garden_management.pyCombining all concepts: error recovery patterns

Module03 — Advanced Data Structures

Objective: Explore Python's native collections beyond lists: tuples, sets, and nested dictionaries. Also covers command-line arguments (sys.argv), generators with yield, and all three comprehension forms (list, dict, and set comprehensions). The theme revolves around video game analytics.

ExerciseMain concept
ft_command_quest.pysys.argv, argument parsing
ft_score_analytics.pyLists: sum, average, min, max
ft_coordinate_system.pyTuples, unpacking, 3D distance calculation
ft_achievement_tracker.pySets: union, intersection, difference
ft_inventory_system.pyNested dictionaries, iteration, .items()
ft_data_stream.pyGenerators with yield (primes, Fibonacci, events)
ft_analytics_dashboard.pyList, dictionary, and set comprehensions

Module04 — File Input/Output

Objective: Handle text files and I/O streams in Python. Covers opening modes (r, w), the importance of closing files correctly, using context managers (with) as best practice, accessing standard streams (sys.stdin, sys.stdout, sys.stderr), and handling file access errors such as FileNotFoundError and PermissionError. The theme is a file archive and vault system.

ExerciseMain concept
ft_ancient_text.pyReading files with open() and manual close
ft_archive_creation.pyWriting files and FileExistsError
ft_stream_management.pysys.stdin, sys.stdout, sys.stderr, readline() and write()
ft_vault_security.pyContext managers (with) for safe file handling
ft_crisis_response.pyMultiple exceptions: FileNotFoundError, PermissionError

Module05 — Abstract Classes and Polymorphism

Objective: Deepen OOP knowledge through abstract base classes (ABC) that define mandatory interfaces. Covers implementing multiple concrete classes that fulfill the same contract, practicing true polymorphism (a function works with any subtype without knowing it), and introducing duck typing with Protocol for composition without inheritance. The scenario is a data processing pipeline with different input types.

ExerciseMain concept
data_processor.pyABC, abstract methods, three concrete implementations (NumericProcessor, TextProcessor, LogProcessor)
data_stream.pyPolymorphic orchestrator, @staticmethod for validation, automatic routing
data_pipeline.pyDuck typing with Protocol, CSV and JSON export plugins

Module06 — Packages and Module System

Objective: Understand how Python organizes code into packages and modules. Covers different import styles (import module, from module import name), subpackage structure with __init__.py, controlled symbol exposure with __all__, and import aliasing. The module uses an alchemy package (alchemy) with subpackages for spells and recipes.

ExerciseMain concept
ft_alembic_0.py / ft_alembic_1.pyimport module vs. from module import name
ft_distillation_*.pyImports from nested subpackages
ft_transmutation_*.pyFull namespace paths in deep hierarchies
alchemy/__init__.py__all__, aliasing with as, re-exporting subpackages

Module07 — Advanced Design Patterns

Objective: Apply classic software engineering design patterns in Python. Covers the Factory Pattern (creating objects without specifying the concrete class), the Mixin Pattern (adding capabilities through multiple inheritance), and the Strategy Pattern (encapsulating interchangeable algorithms). The scenario is a Pokémon-style creature battle system.

ExerciseMain concept
ex0/battle.pyFactory Pattern: CreatureFactory, FlameFactory, AquaFactory
ex1/capacitor.pyMixin interfaces: HealCapability, TransformCapability, multiple inheritance
ex2/tournament.pyStrategy Pattern: NormalStrategy, DefensiveStrategy, AggressiveStrategy, isinstance() for dynamic dispatch

Module08 — Virtual Environments and Configuration

Objective: Master the infrastructure needed for real Python projects. Covers creating and detecting virtual environments (venv), managing dependencies with pip and poetry, consuming external APIs with requests, analyzing data with pandas and numpy, generating charts with matplotlib, and handling sensitive configuration through environment variables with python-dotenv. The theme is the Matrix universe.

ExerciseMain concept
construct.pyVirtual environment detection, sys.prefix, site.getsitepackages()
loading.pyDependencies with importlib.metadata, Binance API, data analysis with pandas/numpy, visualization with matplotlib
oracle.pyEnvironment variables with dotenv, environment-based config (dev/prod), secret validation

Module09 — Data Validation with Pydantic

Objective: Use Pydantic v2 to guarantee data integrity in Python. Covers creating models with BaseModel, declaring field constraints with Field (numeric ranges, string lengths, default values), defining Enum for controlled values, building custom validators with @model_validator for cross-field business rules, and composing nested models with collection-level validation. The scenario is a space station.

ExerciseMain concept
ex0/space_station.pyBaseModel, Field with ge, le, min_length, model_validate(), ValidationError
ex1/alien_contact.pyEnum, @model_validator(mode='after'), cross-field validations
ex2/space_crew.pyNested models (List[CrewMember]), collection validators, experience and leadership rules

Module10 — Functional Programming

Objective: Master the functional programming paradigm in Python. Covers lambda functions, filter(), map(), and sorted() with custom keys; building higher-order functions that receive and return functions; exploring closures and the nonlocal keyword for encapsulated state; using the functools module (reduce, partial, lru_cache, singledispatch); and implementing decorators with and without parameters using @functools.wraps. The context is a world of wizards and spells.

ExerciseMain concept
ex0/lambda_spells.pyLambdas, sorted(), filter(), map(), max(), min() with key functions
ex1/higher_magic.pyHigher-order functions, composition, Callable type hints
ex2/scope_mysteries.pyClosures, nonlocal, stateful functions, functional factory pattern
ex3/functools_artifacts.pyreduce, partial, lru_cache, singledispatch
ex4/decorator_mastery.pySimple and parameterized decorators, @functools.wraps, timer, validator, retry

42 School — Python Piscine | jericard

About

The 11 modules of the 42 Python Piscine: OOP, exceptions, data structures, file I/O, packaging, design patterns, Pydantic and functional programming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Python Piscine — 42 School

User:jericard

This repository contains the completed modules from the 42 School Python Piscine. Each module introduces a new set of skills, building upon the previous ones to progressively master the language.


Index


Module00 — Python Fundamentals

Objective: Introduction to basic Python syntax. Covers defining functions with type annotations, handling variables, reading user input, applying conditionals, iterating with loops, formatting strings with f-strings, and building both iterative and recursive solutions. The exercises follow a garden and harvest theme.

ExerciseMain concept
ft_hello_garden.pyFunction definition and type annotations
ft_plot_area.pyVariables, user input, and arithmetic
ft_harvest_total.pySumming multiple inputs
ft_plant_age.pyif/else conditionals
ft_water_reminder.pyMore conditionals with numeric comparisons
ft_count_harvest_*.pyfor loops vs. recursion
ft_garden_summary.pyString formatting with f-strings
ft_seed_inventory.pyFunctions with multiple parameters and conditional logic

Module01 — Object-Oriented Programming

Objective: Master the pillars of OOP in Python. Covers designing classes with __init__ and __str__, applying encapsulation through private attributes and getters/setters, building inheritance hierarchies using super(), and exploring static methods, class methods, and nested classes. The entire module uses a plant and garden ecosystem as its metaphor.

ExerciseMain concept
ft_garden_intro.pyScript structure with if __name__ == "__main__"
ft_garden_data.pyBasic class with __init__ and __str__
ft_plant_growth.pyInstance methods that modify state
ft_plant_factory.pyCreating multiple instances and typed lists
ft_garden_security.pyEncapsulation: private attributes, getters and setters
ft_plant_types.pyMultiple inheritance: Plant → Flower, Tree, Vegetable
ft_garden_analytics.pyNested classes, static methods, class methods, polymorphism

Module02 — Exception Handling

Objective: Learn to write robust code through Python's exception system. Covers try/except blocks for specific error types, the finally clause to guarantee cleanup, using raise to throw exceptions manually, and creating custom exception hierarchies that inherit from Exception. The context is a garden management system with watering and plant health errors.

ExerciseMain concept
ft_first_exception.pyBasic try/except, ValueError, error codes
ft_different_errors.pyMultiple exception types in a single block
ft_custom_errors.pyCustom exception classes with inheritance (GardenError, PlantError, WaterError)
ft_finally_block.pyfinally clause for guaranteed cleanup
ft_raise_errors.pyExplicit raise with descriptive messages
ft_garden_management.pyCombining all concepts: error recovery patterns

Module03 — Advanced Data Structures

Objective: Explore Python's native collections beyond lists: tuples, sets, and nested dictionaries. Also covers command-line arguments (sys.argv), generators with yield, and all three comprehension forms (list, dict, and set comprehensions). The theme revolves around video game analytics.

ExerciseMain concept
ft_command_quest.pysys.argv, argument parsing
ft_score_analytics.pyLists: sum, average, min, max
ft_coordinate_system.pyTuples, unpacking, 3D distance calculation
ft_achievement_tracker.pySets: union, intersection, difference
ft_inventory_system.pyNested dictionaries, iteration, .items()
ft_data_stream.pyGenerators with yield (primes, Fibonacci, events)
ft_analytics_dashboard.pyList, dictionary, and set comprehensions

Module04 — File Input/Output

Objective: Handle text files and I/O streams in Python. Covers opening modes (r, w), the importance of closing files correctly, using context managers (with) as best practice, accessing standard streams (sys.stdin, sys.stdout, sys.stderr), and handling file access errors such as FileNotFoundError and PermissionError. The theme is a file archive and vault system.

ExerciseMain concept
ft_ancient_text.pyReading files with open() and manual close
ft_archive_creation.pyWriting files and FileExistsError
ft_stream_management.pysys.stdin, sys.stdout, sys.stderr, readline() and write()
ft_vault_security.pyContext managers (with) for safe file handling
ft_crisis_response.pyMultiple exceptions: FileNotFoundError, PermissionError

Module05 — Abstract Classes and Polymorphism

Objective: Deepen OOP knowledge through abstract base classes (ABC) that define mandatory interfaces. Covers implementing multiple concrete classes that fulfill the same contract, practicing true polymorphism (a function works with any subtype without knowing it), and introducing duck typing with Protocol for composition without inheritance. The scenario is a data processing pipeline with different input types.

ExerciseMain concept
data_processor.pyABC, abstract methods, three concrete implementations (NumericProcessor, TextProcessor, LogProcessor)
data_stream.pyPolymorphic orchestrator, @staticmethod for validation, automatic routing
data_pipeline.pyDuck typing with Protocol, CSV and JSON export plugins

Module06 — Packages and Module System

Objective: Understand how Python organizes code into packages and modules. Covers different import styles (import module, from module import name), subpackage structure with __init__.py, controlled symbol exposure with __all__, and import aliasing. The module uses an alchemy package (alchemy) with subpackages for spells and recipes.

ExerciseMain concept
ft_alembic_0.py / ft_alembic_1.pyimport module vs. from module import name
ft_distillation_*.pyImports from nested subpackages
ft_transmutation_*.pyFull namespace paths in deep hierarchies
alchemy/__init__.py__all__, aliasing with as, re-exporting subpackages

Module07 — Advanced Design Patterns

Objective: Apply classic software engineering design patterns in Python. Covers the Factory Pattern (creating objects without specifying the concrete class), the Mixin Pattern (adding capabilities through multiple inheritance), and the Strategy Pattern (encapsulating interchangeable algorithms). The scenario is a Pokémon-style creature battle system.

ExerciseMain concept
ex0/battle.pyFactory Pattern: CreatureFactory, FlameFactory, AquaFactory
ex1/capacitor.pyMixin interfaces: HealCapability, TransformCapability, multiple inheritance
ex2/tournament.pyStrategy Pattern: NormalStrategy, DefensiveStrategy, AggressiveStrategy, isinstance() for dynamic dispatch

Module08 — Virtual Environments and Configuration

Objective: Master the infrastructure needed for real Python projects. Covers creating and detecting virtual environments (venv), managing dependencies with pip and poetry, consuming external APIs with requests, analyzing data with pandas and numpy, generating charts with matplotlib, and handling sensitive configuration through environment variables with python-dotenv. The theme is the Matrix universe.

ExerciseMain concept
construct.pyVirtual environment detection, sys.prefix, site.getsitepackages()
loading.pyDependencies with importlib.metadata, Binance API, data analysis with pandas/numpy, visualization with matplotlib
oracle.pyEnvironment variables with dotenv, environment-based config (dev/prod), secret validation

Module09 — Data Validation with Pydantic

Objective: Use Pydantic v2 to guarantee data integrity in Python. Covers creating models with BaseModel, declaring field constraints with Field (numeric ranges, string lengths, default values), defining Enum for controlled values, building custom validators with @model_validator for cross-field business rules, and composing nested models with collection-level validation. The scenario is a space station.

ExerciseMain concept
ex0/space_station.pyBaseModel, Field with ge, le, min_length, model_validate(), ValidationError
ex1/alien_contact.pyEnum, @model_validator(mode='after'), cross-field validations
ex2/space_crew.pyNested models (List[CrewMember]), collection validators, experience and leadership rules

Module10 — Functional Programming

Objective: Master the functional programming paradigm in Python. Covers lambda functions, filter(), map(), and sorted() with custom keys; building higher-order functions that receive and return functions; exploring closures and the nonlocal keyword for encapsulated state; using the functools module (reduce, partial, lru_cache, singledispatch); and implementing decorators with and without parameters using @functools.wraps. The context is a world of wizards and spells.

ExerciseMain concept
ex0/lambda_spells.pyLambdas, sorted(), filter(), map(), max(), min() with key functions
ex1/higher_magic.pyHigher-order functions, composition, Callable type hints
ex2/scope_mysteries.pyClosures, nonlocal, stateful functions, functional factory pattern
ex3/functools_artifacts.pyreduce, partial, lru_cache, singledispatch
ex4/decorator_mastery.pySimple and parameterized decorators, @functools.wraps, timer, validator, retry

42 School — Python Piscine | jericard

About

The 11 modules of the 42 Python Piscine: OOP, exceptions, data structures, file I/O, packaging, design patterns, Pydantic and functional programming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Python Piscine — 42 School

User:jericard

This repository contains the completed modules from the 42 School Python Piscine. Each module introduces a new set of skills, building upon the previous ones to progressively master the language.


Index


Module00 — Python Fundamentals

Objective: Introduction to basic Python syntax. Covers defining functions with type annotations, handling variables, reading user input, applying conditionals, iterating with loops, formatting strings with f-strings, and building both iterative and recursive solutions. The exercises follow a garden and harvest theme.

ExerciseMain concept
ft_hello_garden.pyFunction definition and type annotations
ft_plot_area.pyVariables, user input, and arithmetic
ft_harvest_total.pySumming multiple inputs
ft_plant_age.pyif/else conditionals
ft_water_reminder.pyMore conditionals with numeric comparisons
ft_count_harvest_*.pyfor loops vs. recursion
ft_garden_summary.pyString formatting with f-strings
ft_seed_inventory.pyFunctions with multiple parameters and conditional logic

Module01 — Object-Oriented Programming

Objective: Master the pillars of OOP in Python. Covers designing classes with __init__ and __str__, applying encapsulation through private attributes and getters/setters, building inheritance hierarchies using super(), and exploring static methods, class methods, and nested classes. The entire module uses a plant and garden ecosystem as its metaphor.

ExerciseMain concept
ft_garden_intro.pyScript structure with if __name__ == "__main__"
ft_garden_data.pyBasic class with __init__ and __str__
ft_plant_growth.pyInstance methods that modify state
ft_plant_factory.pyCreating multiple instances and typed lists
ft_garden_security.pyEncapsulation: private attributes, getters and setters
ft_plant_types.pyMultiple inheritance: Plant → Flower, Tree, Vegetable
ft_garden_analytics.pyNested classes, static methods, class methods, polymorphism

Module02 — Exception Handling

Objective: Learn to write robust code through Python's exception system. Covers try/except blocks for specific error types, the finally clause to guarantee cleanup, using raise to throw exceptions manually, and creating custom exception hierarchies that inherit from Exception. The context is a garden management system with watering and plant health errors.

ExerciseMain concept
ft_first_exception.pyBasic try/except, ValueError, error codes
ft_different_errors.pyMultiple exception types in a single block
ft_custom_errors.pyCustom exception classes with inheritance (GardenError, PlantError, WaterError)
ft_finally_block.pyfinally clause for guaranteed cleanup
ft_raise_errors.pyExplicit raise with descriptive messages
ft_garden_management.pyCombining all concepts: error recovery patterns

Module03 — Advanced Data Structures

Objective: Explore Python's native collections beyond lists: tuples, sets, and nested dictionaries. Also covers command-line arguments (sys.argv), generators with yield, and all three comprehension forms (list, dict, and set comprehensions). The theme revolves around video game analytics.

ExerciseMain concept
ft_command_quest.pysys.argv, argument parsing
ft_score_analytics.pyLists: sum, average, min, max
ft_coordinate_system.pyTuples, unpacking, 3D distance calculation
ft_achievement_tracker.pySets: union, intersection, difference
ft_inventory_system.pyNested dictionaries, iteration, .items()
ft_data_stream.pyGenerators with yield (primes, Fibonacci, events)
ft_analytics_dashboard.pyList, dictionary, and set comprehensions

Module04 — File Input/Output

Objective: Handle text files and I/O streams in Python. Covers opening modes (r, w), the importance of closing files correctly, using context managers (with) as best practice, accessing standard streams (sys.stdin, sys.stdout, sys.stderr), and handling file access errors such as FileNotFoundError and PermissionError. The theme is a file archive and vault system.

ExerciseMain concept
ft_ancient_text.pyReading files with open() and manual close
ft_archive_creation.pyWriting files and FileExistsError
ft_stream_management.pysys.stdin, sys.stdout, sys.stderr, readline() and write()
ft_vault_security.pyContext managers (with) for safe file handling
ft_crisis_response.pyMultiple exceptions: FileNotFoundError, PermissionError

Module05 — Abstract Classes and Polymorphism

Objective: Deepen OOP knowledge through abstract base classes (ABC) that define mandatory interfaces. Covers implementing multiple concrete classes that fulfill the same contract, practicing true polymorphism (a function works with any subtype without knowing it), and introducing duck typing with Protocol for composition without inheritance. The scenario is a data processing pipeline with different input types.

ExerciseMain concept
data_processor.pyABC, abstract methods, three concrete implementations (NumericProcessor, TextProcessor, LogProcessor)
data_stream.pyPolymorphic orchestrator, @staticmethod for validation, automatic routing
data_pipeline.pyDuck typing with Protocol, CSV and JSON export plugins

Module06 — Packages and Module System

Objective: Understand how Python organizes code into packages and modules. Covers different import styles (import module, from module import name), subpackage structure with __init__.py, controlled symbol exposure with __all__, and import aliasing. The module uses an alchemy package (alchemy) with subpackages for spells and recipes.

ExerciseMain concept
ft_alembic_0.py / ft_alembic_1.pyimport module vs. from module import name
ft_distillation_*.pyImports from nested subpackages
ft_transmutation_*.pyFull namespace paths in deep hierarchies
alchemy/__init__.py__all__, aliasing with as, re-exporting subpackages

Module07 — Advanced Design Patterns

Objective: Apply classic software engineering design patterns in Python. Covers the Factory Pattern (creating objects without specifying the concrete class), the Mixin Pattern (adding capabilities through multiple inheritance), and the Strategy Pattern (encapsulating interchangeable algorithms). The scenario is a Pokémon-style creature battle system.

ExerciseMain concept
ex0/battle.pyFactory Pattern: CreatureFactory, FlameFactory, AquaFactory
ex1/capacitor.pyMixin interfaces: HealCapability, TransformCapability, multiple inheritance
ex2/tournament.pyStrategy Pattern: NormalStrategy, DefensiveStrategy, AggressiveStrategy, isinstance() for dynamic dispatch

Module08 — Virtual Environments and Configuration

Objective: Master the infrastructure needed for real Python projects. Covers creating and detecting virtual environments (venv), managing dependencies with pip and poetry, consuming external APIs with requests, analyzing data with pandas and numpy, generating charts with matplotlib, and handling sensitive configuration through environment variables with python-dotenv. The theme is the Matrix universe.

ExerciseMain concept
construct.pyVirtual environment detection, sys.prefix, site.getsitepackages()
loading.pyDependencies with importlib.metadata, Binance API, data analysis with pandas/numpy, visualization with matplotlib
oracle.pyEnvironment variables with dotenv, environment-based config (dev/prod), secret validation

Module09 — Data Validation with Pydantic

Objective: Use Pydantic v2 to guarantee data integrity in Python. Covers creating models with BaseModel, declaring field constraints with Field (numeric ranges, string lengths, default values), defining Enum for controlled values, building custom validators with @model_validator for cross-field business rules, and composing nested models with collection-level validation. The scenario is a space station.

ExerciseMain concept
ex0/space_station.pyBaseModel, Field with ge, le, min_length, model_validate(), ValidationError
ex1/alien_contact.pyEnum, @model_validator(mode='after'), cross-field validations
ex2/space_crew.pyNested models (List[CrewMember]), collection validators, experience and leadership rules

Module10 — Functional Programming

Objective: Master the functional programming paradigm in Python. Covers lambda functions, filter(), map(), and sorted() with custom keys; building higher-order functions that receive and return functions; exploring closures and the nonlocal keyword for encapsulated state; using the functools module (reduce, partial, lru_cache, singledispatch); and implementing decorators with and without parameters using @functools.wraps. The context is a world of wizards and spells.

ExerciseMain concept
ex0/lambda_spells.pyLambdas, sorted(), filter(), map(), max(), min() with key functions
ex1/higher_magic.pyHigher-order functions, composition, Callable type hints
ex2/scope_mysteries.pyClosures, nonlocal, stateful functions, functional factory pattern
ex3/functools_artifacts.pyreduce, partial, lru_cache, singledispatch
ex4/decorator_mastery.pySimple and parameterized decorators, @functools.wraps, timer, validator, retry

42 School — Python Piscine | jericard

About

The 11 modules of the 42 Python Piscine: OOP, exceptions, data structures, file I/O, packaging, design patterns, Pydantic and functional programming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Python Piscine — 42 School

User:jericard

This repository contains the completed modules from the 42 School Python Piscine. Each module introduces a new set of skills, building upon the previous ones to progressively master the language.


Index


Module00 — Python Fundamentals

Objective: Introduction to basic Python syntax. Covers defining functions with type annotations, handling variables, reading user input, applying conditionals, iterating with loops, formatting strings with f-strings, and building both iterative and recursive solutions. The exercises follow a garden and harvest theme.

ExerciseMain concept
ft_hello_garden.pyFunction definition and type annotations
ft_plot_area.pyVariables, user input, and arithmetic
ft_harvest_total.pySumming multiple inputs
ft_plant_age.pyif/else conditionals
ft_water_reminder.pyMore conditionals with numeric comparisons
ft_count_harvest_*.pyfor loops vs. recursion
ft_garden_summary.pyString formatting with f-strings
ft_seed_inventory.pyFunctions with multiple parameters and conditional logic

Module01 — Object-Oriented Programming

Objective: Master the pillars of OOP in Python. Covers designing classes with __init__ and __str__, applying encapsulation through private attributes and getters/setters, building inheritance hierarchies using super(), and exploring static methods, class methods, and nested classes. The entire module uses a plant and garden ecosystem as its metaphor.

ExerciseMain concept
ft_garden_intro.pyScript structure with if __name__ == "__main__"
ft_garden_data.pyBasic class with __init__ and __str__
ft_plant_growth.pyInstance methods that modify state
ft_plant_factory.pyCreating multiple instances and typed lists
ft_garden_security.pyEncapsulation: private attributes, getters and setters
ft_plant_types.pyMultiple inheritance: Plant → Flower, Tree, Vegetable
ft_garden_analytics.pyNested classes, static methods, class methods, polymorphism

Module02 — Exception Handling

Objective: Learn to write robust code through Python's exception system. Covers try/except blocks for specific error types, the finally clause to guarantee cleanup, using raise to throw exceptions manually, and creating custom exception hierarchies that inherit from Exception. The context is a garden management system with watering and plant health errors.

ExerciseMain concept
ft_first_exception.pyBasic try/except, ValueError, error codes
ft_different_errors.pyMultiple exception types in a single block
ft_custom_errors.pyCustom exception classes with inheritance (GardenError, PlantError, WaterError)
ft_finally_block.pyfinally clause for guaranteed cleanup
ft_raise_errors.pyExplicit raise with descriptive messages
ft_garden_management.pyCombining all concepts: error recovery patterns

Module03 — Advanced Data Structures

Objective: Explore Python's native collections beyond lists: tuples, sets, and nested dictionaries. Also covers command-line arguments (sys.argv), generators with yield, and all three comprehension forms (list, dict, and set comprehensions). The theme revolves around video game analytics.

ExerciseMain concept
ft_command_quest.pysys.argv, argument parsing
ft_score_analytics.pyLists: sum, average, min, max
ft_coordinate_system.pyTuples, unpacking, 3D distance calculation
ft_achievement_tracker.pySets: union, intersection, difference
ft_inventory_system.pyNested dictionaries, iteration, .items()
ft_data_stream.pyGenerators with yield (primes, Fibonacci, events)
ft_analytics_dashboard.pyList, dictionary, and set comprehensions

Module04 — File Input/Output

Objective: Handle text files and I/O streams in Python. Covers opening modes (r, w), the importance of closing files correctly, using context managers (with) as best practice, accessing standard streams (sys.stdin, sys.stdout, sys.stderr), and handling file access errors such as FileNotFoundError and PermissionError. The theme is a file archive and vault system.

ExerciseMain concept
ft_ancient_text.pyReading files with open() and manual close
ft_archive_creation.pyWriting files and FileExistsError
ft_stream_management.pysys.stdin, sys.stdout, sys.stderr, readline() and write()
ft_vault_security.pyContext managers (with) for safe file handling
ft_crisis_response.pyMultiple exceptions: FileNotFoundError, PermissionError

Module05 — Abstract Classes and Polymorphism

Objective: Deepen OOP knowledge through abstract base classes (ABC) that define mandatory interfaces. Covers implementing multiple concrete classes that fulfill the same contract, practicing true polymorphism (a function works with any subtype without knowing it), and introducing duck typing with Protocol for composition without inheritance. The scenario is a data processing pipeline with different input types.

ExerciseMain concept
data_processor.pyABC, abstract methods, three concrete implementations (NumericProcessor, TextProcessor, LogProcessor)
data_stream.pyPolymorphic orchestrator, @staticmethod for validation, automatic routing
data_pipeline.pyDuck typing with Protocol, CSV and JSON export plugins

Module06 — Packages and Module System

Objective: Understand how Python organizes code into packages and modules. Covers different import styles (import module, from module import name), subpackage structure with __init__.py, controlled symbol exposure with __all__, and import aliasing. The module uses an alchemy package (alchemy) with subpackages for spells and recipes.

ExerciseMain concept
ft_alembic_0.py / ft_alembic_1.pyimport module vs. from module import name
ft_distillation_*.pyImports from nested subpackages
ft_transmutation_*.pyFull namespace paths in deep hierarchies
alchemy/__init__.py__all__, aliasing with as, re-exporting subpackages

Module07 — Advanced Design Patterns

Objective: Apply classic software engineering design patterns in Python. Covers the Factory Pattern (creating objects without specifying the concrete class), the Mixin Pattern (adding capabilities through multiple inheritance), and the Strategy Pattern (encapsulating interchangeable algorithms). The scenario is a Pokémon-style creature battle system.

ExerciseMain concept
ex0/battle.pyFactory Pattern: CreatureFactory, FlameFactory, AquaFactory
ex1/capacitor.pyMixin interfaces: HealCapability, TransformCapability, multiple inheritance
ex2/tournament.pyStrategy Pattern: NormalStrategy, DefensiveStrategy, AggressiveStrategy, isinstance() for dynamic dispatch

Module08 — Virtual Environments and Configuration

Objective: Master the infrastructure needed for real Python projects. Covers creating and detecting virtual environments (venv), managing dependencies with pip and poetry, consuming external APIs with requests, analyzing data with pandas and numpy, generating charts with matplotlib, and handling sensitive configuration through environment variables with python-dotenv. The theme is the Matrix universe.

ExerciseMain concept
construct.pyVirtual environment detection, sys.prefix, site.getsitepackages()
loading.pyDependencies with importlib.metadata, Binance API, data analysis with pandas/numpy, visualization with matplotlib
oracle.pyEnvironment variables with dotenv, environment-based config (dev/prod), secret validation

Module09 — Data Validation with Pydantic

Objective: Use Pydantic v2 to guarantee data integrity in Python. Covers creating models with BaseModel, declaring field constraints with Field (numeric ranges, string lengths, default values), defining Enum for controlled values, building custom validators with @model_validator for cross-field business rules, and composing nested models with collection-level validation. The scenario is a space station.

ExerciseMain concept
ex0/space_station.pyBaseModel, Field with ge, le, min_length, model_validate(), ValidationError
ex1/alien_contact.pyEnum, @model_validator(mode='after'), cross-field validations
ex2/space_crew.pyNested models (List[CrewMember]), collection validators, experience and leadership rules

Module10 — Functional Programming

Objective: Master the functional programming paradigm in Python. Covers lambda functions, filter(), map(), and sorted() with custom keys; building higher-order functions that receive and return functions; exploring closures and the nonlocal keyword for encapsulated state; using the functools module (reduce, partial, lru_cache, singledispatch); and implementing decorators with and without parameters using @functools.wraps. The context is a world of wizards and spells.

ExerciseMain concept
ex0/lambda_spells.pyLambdas, sorted(), filter(), map(), max(), min() with key functions
ex1/higher_magic.pyHigher-order functions, composition, Callable type hints
ex2/scope_mysteries.pyClosures, nonlocal, stateful functions, functional factory pattern
ex3/functools_artifacts.pyreduce, partial, lru_cache, singledispatch
ex4/decorator_mastery.pySimple and parameterized decorators, @functools.wraps, timer, validator, retry

42 School — Python Piscine | jericard

About

The 11 modules of the 42 Python Piscine: OOP, exceptions, data structures, file I/O, packaging, design patterns, Pydantic and functional programming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Python Piscine — 42 School

User:jericard

This repository contains the completed modules from the 42 School Python Piscine. Each module introduces a new set of skills, building upon the previous ones to progressively master the language.


Index


Module00 — Python Fundamentals

Objective: Introduction to basic Python syntax. Covers defining functions with type annotations, handling variables, reading user input, applying conditionals, iterating with loops, formatting strings with f-strings, and building both iterative and recursive solutions. The exercises follow a garden and harvest theme.

ExerciseMain concept
ft_hello_garden.pyFunction definition and type annotations
ft_plot_area.pyVariables, user input, and arithmetic
ft_harvest_total.pySumming multiple inputs
ft_plant_age.pyif/else conditionals
ft_water_reminder.pyMore conditionals with numeric comparisons
ft_count_harvest_*.pyfor loops vs. recursion
ft_garden_summary.pyString formatting with f-strings
ft_seed_inventory.pyFunctions with multiple parameters and conditional logic

Module01 — Object-Oriented Programming

Objective: Master the pillars of OOP in Python. Covers designing classes with __init__ and __str__, applying encapsulation through private attributes and getters/setters, building inheritance hierarchies using super(), and exploring static methods, class methods, and nested classes. The entire module uses a plant and garden ecosystem as its metaphor.

ExerciseMain concept
ft_garden_intro.pyScript structure with if __name__ == "__main__"
ft_garden_data.pyBasic class with __init__ and __str__
ft_plant_growth.pyInstance methods that modify state
ft_plant_factory.pyCreating multiple instances and typed lists
ft_garden_security.pyEncapsulation: private attributes, getters and setters
ft_plant_types.pyMultiple inheritance: Plant → Flower, Tree, Vegetable
ft_garden_analytics.pyNested classes, static methods, class methods, polymorphism

Module02 — Exception Handling

Objective: Learn to write robust code through Python's exception system. Covers try/except blocks for specific error types, the finally clause to guarantee cleanup, using raise to throw exceptions manually, and creating custom exception hierarchies that inherit from Exception. The context is a garden management system with watering and plant health errors.

ExerciseMain concept
ft_first_exception.pyBasic try/except, ValueError, error codes
ft_different_errors.pyMultiple exception types in a single block
ft_custom_errors.pyCustom exception classes with inheritance (GardenError, PlantError, WaterError)
ft_finally_block.pyfinally clause for guaranteed cleanup
ft_raise_errors.pyExplicit raise with descriptive messages
ft_garden_management.pyCombining all concepts: error recovery patterns

Module03 — Advanced Data Structures

Objective: Explore Python's native collections beyond lists: tuples, sets, and nested dictionaries. Also covers command-line arguments (sys.argv), generators with yield, and all three comprehension forms (list, dict, and set comprehensions). The theme revolves around video game analytics.

ExerciseMain concept
ft_command_quest.pysys.argv, argument parsing
ft_score_analytics.pyLists: sum, average, min, max
ft_coordinate_system.pyTuples, unpacking, 3D distance calculation
ft_achievement_tracker.pySets: union, intersection, difference
ft_inventory_system.pyNested dictionaries, iteration, .items()
ft_data_stream.pyGenerators with yield (primes, Fibonacci, events)
ft_analytics_dashboard.pyList, dictionary, and set comprehensions

Module04 — File Input/Output

Objective: Handle text files and I/O streams in Python. Covers opening modes (r, w), the importance of closing files correctly, using context managers (with) as best practice, accessing standard streams (sys.stdin, sys.stdout, sys.stderr), and handling file access errors such as FileNotFoundError and PermissionError. The theme is a file archive and vault system.

ExerciseMain concept
ft_ancient_text.pyReading files with open() and manual close
ft_archive_creation.pyWriting files and FileExistsError
ft_stream_management.pysys.stdin, sys.stdout, sys.stderr, readline() and write()
ft_vault_security.pyContext managers (with) for safe file handling
ft_crisis_response.pyMultiple exceptions: FileNotFoundError, PermissionError

Module05 — Abstract Classes and Polymorphism

Objective: Deepen OOP knowledge through abstract base classes (ABC) that define mandatory interfaces. Covers implementing multiple concrete classes that fulfill the same contract, practicing true polymorphism (a function works with any subtype without knowing it), and introducing duck typing with Protocol for composition without inheritance. The scenario is a data processing pipeline with different input types.

ExerciseMain concept
data_processor.pyABC, abstract methods, three concrete implementations (NumericProcessor, TextProcessor, LogProcessor)
data_stream.pyPolymorphic orchestrator, @staticmethod for validation, automatic routing
data_pipeline.pyDuck typing with Protocol, CSV and JSON export plugins

Module06 — Packages and Module System

Objective: Understand how Python organizes code into packages and modules. Covers different import styles (import module, from module import name), subpackage structure with __init__.py, controlled symbol exposure with __all__, and import aliasing. The module uses an alchemy package (alchemy) with subpackages for spells and recipes.

ExerciseMain concept
ft_alembic_0.py / ft_alembic_1.pyimport module vs. from module import name
ft_distillation_*.pyImports from nested subpackages
ft_transmutation_*.pyFull namespace paths in deep hierarchies
alchemy/__init__.py__all__, aliasing with as, re-exporting subpackages

Module07 — Advanced Design Patterns

Objective: Apply classic software engineering design patterns in Python. Covers the Factory Pattern (creating objects without specifying the concrete class), the Mixin Pattern (adding capabilities through multiple inheritance), and the Strategy Pattern (encapsulating interchangeable algorithms). The scenario is a Pokémon-style creature battle system.

ExerciseMain concept
ex0/battle.pyFactory Pattern: CreatureFactory, FlameFactory, AquaFactory
ex1/capacitor.pyMixin interfaces: HealCapability, TransformCapability, multiple inheritance
ex2/tournament.pyStrategy Pattern: NormalStrategy, DefensiveStrategy, AggressiveStrategy, isinstance() for dynamic dispatch

Module08 — Virtual Environments and Configuration

Objective: Master the infrastructure needed for real Python projects. Covers creating and detecting virtual environments (venv), managing dependencies with pip and poetry, consuming external APIs with requests, analyzing data with pandas and numpy, generating charts with matplotlib, and handling sensitive configuration through environment variables with python-dotenv. The theme is the Matrix universe.

ExerciseMain concept
construct.pyVirtual environment detection, sys.prefix, site.getsitepackages()
loading.pyDependencies with importlib.metadata, Binance API, data analysis with pandas/numpy, visualization with matplotlib
oracle.pyEnvironment variables with dotenv, environment-based config (dev/prod), secret validation

Module09 — Data Validation with Pydantic

Objective: Use Pydantic v2 to guarantee data integrity in Python. Covers creating models with BaseModel, declaring field constraints with Field (numeric ranges, string lengths, default values), defining Enum for controlled values, building custom validators with @model_validator for cross-field business rules, and composing nested models with collection-level validation. The scenario is a space station.

ExerciseMain concept
ex0/space_station.pyBaseModel, Field with ge, le, min_length, model_validate(), ValidationError
ex1/alien_contact.pyEnum, @model_validator(mode='after'), cross-field validations
ex2/space_crew.pyNested models (List[CrewMember]), collection validators, experience and leadership rules

Module10 — Functional Programming

Objective: Master the functional programming paradigm in Python. Covers lambda functions, filter(), map(), and sorted() with custom keys; building higher-order functions that receive and return functions; exploring closures and the nonlocal keyword for encapsulated state; using the functools module (reduce, partial, lru_cache, singledispatch); and implementing decorators with and without parameters using @functools.wraps. The context is a world of wizards and spells.

ExerciseMain concept
ex0/lambda_spells.pyLambdas, sorted(), filter(), map(), max(), min() with key functions
ex1/higher_magic.pyHigher-order functions, composition, Callable type hints
ex2/scope_mysteries.pyClosures, nonlocal, stateful functions, functional factory pattern
ex3/functools_artifacts.pyreduce, partial, lru_cache, singledispatch
ex4/decorator_mastery.pySimple and parameterized decorators, @functools.wraps, timer, validator, retry

42 School — Python Piscine | jericard

About

The 11 modules of the 42 Python Piscine: OOP, exceptions, data structures, file I/O, packaging, design patterns, Pydantic and functional programming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Python Piscine — 42 School

User:jericard

This repository contains the completed modules from the 42 School Python Piscine. Each module introduces a new set of skills, building upon the previous ones to progressively master the language.


Index


Module00 — Python Fundamentals

Objective: Introduction to basic Python syntax. Covers defining functions with type annotations, handling variables, reading user input, applying conditionals, iterating with loops, formatting strings with f-strings, and building both iterative and recursive solutions. The exercises follow a garden and harvest theme.

ExerciseMain concept
ft_hello_garden.pyFunction definition and type annotations
ft_plot_area.pyVariables, user input, and arithmetic
ft_harvest_total.pySumming multiple inputs
ft_plant_age.pyif/else conditionals
ft_water_reminder.pyMore conditionals with numeric comparisons
ft_count_harvest_*.pyfor loops vs. recursion
ft_garden_summary.pyString formatting with f-strings
ft_seed_inventory.pyFunctions with multiple parameters and conditional logic

Module01 — Object-Oriented Programming

Objective: Master the pillars of OOP in Python. Covers designing classes with __init__ and __str__, applying encapsulation through private attributes and getters/setters, building inheritance hierarchies using super(), and exploring static methods, class methods, and nested classes. The entire module uses a plant and garden ecosystem as its metaphor.

ExerciseMain concept
ft_garden_intro.pyScript structure with if __name__ == "__main__"
ft_garden_data.pyBasic class with __init__ and __str__
ft_plant_growth.pyInstance methods that modify state
ft_plant_factory.pyCreating multiple instances and typed lists
ft_garden_security.pyEncapsulation: private attributes, getters and setters
ft_plant_types.pyMultiple inheritance: Plant → Flower, Tree, Vegetable
ft_garden_analytics.pyNested classes, static methods, class methods, polymorphism

Module02 — Exception Handling

Objective: Learn to write robust code through Python's exception system. Covers try/except blocks for specific error types, the finally clause to guarantee cleanup, using raise to throw exceptions manually, and creating custom exception hierarchies that inherit from Exception. The context is a garden management system with watering and plant health errors.

ExerciseMain concept
ft_first_exception.pyBasic try/except, ValueError, error codes
ft_different_errors.pyMultiple exception types in a single block
ft_custom_errors.pyCustom exception classes with inheritance (GardenError, PlantError, WaterError)
ft_finally_block.pyfinally clause for guaranteed cleanup
ft_raise_errors.pyExplicit raise with descriptive messages
ft_garden_management.pyCombining all concepts: error recovery patterns

Module03 — Advanced Data Structures

Objective: Explore Python's native collections beyond lists: tuples, sets, and nested dictionaries. Also covers command-line arguments (sys.argv), generators with yield, and all three comprehension forms (list, dict, and set comprehensions). The theme revolves around video game analytics.

ExerciseMain concept
ft_command_quest.pysys.argv, argument parsing
ft_score_analytics.pyLists: sum, average, min, max
ft_coordinate_system.pyTuples, unpacking, 3D distance calculation
ft_achievement_tracker.pySets: union, intersection, difference
ft_inventory_system.pyNested dictionaries, iteration, .items()
ft_data_stream.pyGenerators with yield (primes, Fibonacci, events)
ft_analytics_dashboard.pyList, dictionary, and set comprehensions

Module04 — File Input/Output

Objective: Handle text files and I/O streams in Python. Covers opening modes (r, w), the importance of closing files correctly, using context managers (with) as best practice, accessing standard streams (sys.stdin, sys.stdout, sys.stderr), and handling file access errors such as FileNotFoundError and PermissionError. The theme is a file archive and vault system.

ExerciseMain concept
ft_ancient_text.pyReading files with open() and manual close
ft_archive_creation.pyWriting files and FileExistsError
ft_stream_management.pysys.stdin, sys.stdout, sys.stderr, readline() and write()
ft_vault_security.pyContext managers (with) for safe file handling
ft_crisis_response.pyMultiple exceptions: FileNotFoundError, PermissionError

Module05 — Abstract Classes and Polymorphism

Objective: Deepen OOP knowledge through abstract base classes (ABC) that define mandatory interfaces. Covers implementing multiple concrete classes that fulfill the same contract, practicing true polymorphism (a function works with any subtype without knowing it), and introducing duck typing with Protocol for composition without inheritance. The scenario is a data processing pipeline with different input types.

ExerciseMain concept
data_processor.pyABC, abstract methods, three concrete implementations (NumericProcessor, TextProcessor, LogProcessor)
data_stream.pyPolymorphic orchestrator, @staticmethod for validation, automatic routing
data_pipeline.pyDuck typing with Protocol, CSV and JSON export plugins

Module06 — Packages and Module System

Objective: Understand how Python organizes code into packages and modules. Covers different import styles (import module, from module import name), subpackage structure with __init__.py, controlled symbol exposure with __all__, and import aliasing. The module uses an alchemy package (alchemy) with subpackages for spells and recipes.

ExerciseMain concept
ft_alembic_0.py / ft_alembic_1.pyimport module vs. from module import name
ft_distillation_*.pyImports from nested subpackages
ft_transmutation_*.pyFull namespace paths in deep hierarchies
alchemy/__init__.py__all__, aliasing with as, re-exporting subpackages

Module07 — Advanced Design Patterns

Objective: Apply classic software engineering design patterns in Python. Covers the Factory Pattern (creating objects without specifying the concrete class), the Mixin Pattern (adding capabilities through multiple inheritance), and the Strategy Pattern (encapsulating interchangeable algorithms). The scenario is a Pokémon-style creature battle system.

ExerciseMain concept
ex0/battle.pyFactory Pattern: CreatureFactory, FlameFactory, AquaFactory
ex1/capacitor.pyMixin interfaces: HealCapability, TransformCapability, multiple inheritance
ex2/tournament.pyStrategy Pattern: NormalStrategy, DefensiveStrategy, AggressiveStrategy, isinstance() for dynamic dispatch

Module08 — Virtual Environments and Configuration

Objective: Master the infrastructure needed for real Python projects. Covers creating and detecting virtual environments (venv), managing dependencies with pip and poetry, consuming external APIs with requests, analyzing data with pandas and numpy, generating charts with matplotlib, and handling sensitive configuration through environment variables with python-dotenv. The theme is the Matrix universe.

ExerciseMain concept
construct.pyVirtual environment detection, sys.prefix, site.getsitepackages()
loading.pyDependencies with importlib.metadata, Binance API, data analysis with pandas/numpy, visualization with matplotlib
oracle.pyEnvironment variables with dotenv, environment-based config (dev/prod), secret validation

Module09 — Data Validation with Pydantic

Objective: Use Pydantic v2 to guarantee data integrity in Python. Covers creating models with BaseModel, declaring field constraints with Field (numeric ranges, string lengths, default values), defining Enum for controlled values, building custom validators with @model_validator for cross-field business rules, and composing nested models with collection-level validation. The scenario is a space station.

ExerciseMain concept
ex0/space_station.pyBaseModel, Field with ge, le, min_length, model_validate(), ValidationError
ex1/alien_contact.pyEnum, @model_validator(mode='after'), cross-field validations
ex2/space_crew.pyNested models (List[CrewMember]), collection validators, experience and leadership rules

Module10 — Functional Programming

Objective: Master the functional programming paradigm in Python. Covers lambda functions, filter(), map(), and sorted() with custom keys; building higher-order functions that receive and return functions; exploring closures and the nonlocal keyword for encapsulated state; using the functools module (reduce, partial, lru_cache, singledispatch); and implementing decorators with and without parameters using @functools.wraps. The context is a world of wizards and spells.

ExerciseMain concept
ex0/lambda_spells.pyLambdas, sorted(), filter(), map(), max(), min() with key functions
ex1/higher_magic.pyHigher-order functions, composition, Callable type hints
ex2/scope_mysteries.pyClosures, nonlocal, stateful functions, functional factory pattern
ex3/functools_artifacts.pyreduce, partial, lru_cache, singledispatch
ex4/decorator_mastery.pySimple and parameterized decorators, @functools.wraps, timer, validator, retry

42 School — Python Piscine | jericard

About

The 11 modules of the 42 Python Piscine: OOP, exceptions, data structures, file I/O, packaging, design patterns, Pydantic and functional programming.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages