-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-sphinx-documentation.py
More file actions
1589 lines (1144 loc) · 44 KB
/
02-sphinx-documentation.py
File metadata and controls
1589 lines (1144 loc) · 44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Question: Create comprehensive Sphinx documentation for a Python project.
Build a complete documentation system using Sphinx with various features
including API documentation, tutorials, and examples.
Requirements:
1. Create a sample Python module with proper docstrings
2. Set up Sphinx configuration
3. Create documentation with multiple sections
4. Include code examples and API references
5. Demonstrate various Sphinx features (autodoc, cross-references, etc.)
Example usage:
# Generate documentation
sphinx-build -b html docs docs/_build/html
# View documentation
open docs/_build/html/index.html
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
#
# Tips for success:
# - Read the question carefully
# - Think about documentation structure and organization
# - Start with basic docstrings and build up
# - Test your documentation generation step by step
# - Don't worry if it's not perfect - learning is a process!
#
# Remember: Good documentation is crucial for any Python project!
#
# Take your time, experiment, and enjoy the learning process!
# Try to implement your solution here:
# (Write your code below this line)
# HINT SECTION (Only look if you're really stuck!)
#
# Think about:
# - What makes good documentation structure?
# - How to write clear and comprehensive docstrings?
# - What Sphinx extensions and features to use?
# - How to organize documentation files and sections?
#
# Remember: Start with basic docstrings and build up complexity gradually!
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Create a sample Python module with basic docstrings
# ===============================================================================
# Explanation:
# Good documentation starts with well-written docstrings in your code.
# We'll create a sample calculator module to demonstrate various docstring styles.
"""
Sample Calculator Module
This module provides basic mathematical operations and demonstrates
various Sphinx documentation features.
Example:
Basic usage of the calculator::
from calculator import Calculator
calc = Calculator()
result = calc.add(5, 3)
print(f"Result: {result}")
Attributes:
PI (float): Mathematical constant pi
E (float): Mathematical constant e
Todo:
* Add more advanced mathematical operations
* Implement error handling for division by zero
* Add support for complex numbers
"""
import math
from typing import Union, List, Optional
# Module-level constants
PI = math.pi
E = math.e
class Calculator:
"""A simple calculator class for basic mathematical operations.
This class provides methods for basic arithmetic operations
and demonstrates proper Sphinx documentation practices.
Attributes:
history (List[str]): A list of performed operations
precision (int): Number of decimal places for results
Example:
Creating and using a calculator::
calc = Calculator(precision=2)
result = calc.add(10, 5)
print(calc.get_history())
"""
def __init__(self, precision: int = 2):
"""Initialize the calculator.
Args:
precision (int, optional): Number of decimal places for results.
Defaults to 2.
Raises:
ValueError: If precision is negative.
Example:
>>> calc = Calculator(precision=3)
>>> calc.precision
3
"""
if precision < 0:
raise ValueError("Precision must be non-negative")
self.precision = precision
self.history: List[str] = []
def add(self, a: Union[int, float], b: Union[int, float]) -> float:
"""Add two numbers.
Args:
a (Union[int, float]): First number
b (Union[int, float]): Second number
Returns:
float: Sum of a and b, rounded to specified precision
Example:
>>> calc = Calculator()
>>> calc.add(5, 3)
8.0
>>> calc.add(2.5, 1.7)
4.2
"""
result = round(a + b, self.precision)
self.history.append(f"{a} + {b} = {result}")
return result
# Step 2: Add more methods with comprehensive docstrings
# ===============================================================================
# Explanation:
# Building on Step 1, we'll add more methods to demonstrate different
# docstring patterns and Sphinx features like cross-references.
# Continue the Calculator class from Step 1:
class CalculatorStep2:
"""Enhanced calculator class with more operations.
This class extends the basic calculator functionality and demonstrates
advanced Sphinx documentation features including cross-references,
parameter validation, and comprehensive examples.
Attributes:
history (List[str]): A list of performed operations
precision (int): Number of decimal places for results
Note:
This calculator maintains operation history for debugging purposes.
Use :meth:`clear_history` to reset the history when needed.
See Also:
:class:`Calculator`: Basic calculator implementation
:func:`math.pow`: Built-in power function
"""
def __init__(self, precision: int = 2):
"""Initialize the calculator.
Args:
precision (int, optional): Number of decimal places for results.
Defaults to 2.
Raises:
ValueError: If precision is negative.
Example:
>>> calc = CalculatorStep2(precision=3)
>>> calc.precision
3
"""
if precision < 0:
raise ValueError("Precision must be non-negative")
self.precision = precision
self.history: List[str] = []
def add(self, a: Union[int, float], b: Union[int, float]) -> float:
"""Add two numbers.
Args:
a (Union[int, float]): First number
b (Union[int, float]): Second number
Returns:
float: Sum of a and b, rounded to specified precision
Example:
>>> calc = CalculatorStep2()
>>> calc.add(5, 3)
8.0
>>> calc.add(2.5, 1.7)
4.2
"""
result = round(a + b, self.precision)
self.history.append(f"{a} + {b} = {result}")
return result
def subtract(self, a: Union[int, float], b: Union[int, float]) -> float:
"""Subtract second number from first number.
Args:
a (Union[int, float]): Number to subtract from
b (Union[int, float]): Number to subtract
Returns:
float: Difference of a and b, rounded to specified precision
Example:
>>> calc = CalculatorStep2()
>>> calc.subtract(10, 3)
7.0
>>> calc.subtract(5.5, 2.2)
3.3
"""
result = round(a - b, self.precision)
self.history.append(f"{a} - {b} = {result}")
return result
def multiply(self, a: Union[int, float], b: Union[int, float]) -> float:
"""Multiply two numbers.
Args:
a (Union[int, float]): First number
b (Union[int, float]): Second number
Returns:
float: Product of a and b, rounded to specified precision
Example:
>>> calc = CalculatorStep2()
>>> calc.multiply(4, 5)
20.0
>>> calc.multiply(2.5, 3)
7.5
"""
result = round(a * b, self.precision)
self.history.append(f"{a} * {b} = {result}")
return result
def divide(self, a: Union[int, float], b: Union[int, float]) -> float:
"""Divide first number by second number.
Args:
a (Union[int, float]): Dividend
b (Union[int, float]): Divisor
Returns:
float: Quotient of a and b, rounded to specified precision
Raises:
ZeroDivisionError: If divisor is zero
Example:
>>> calc = CalculatorStep2()
>>> calc.divide(10, 2)
5.0
>>> calc.divide(7, 3)
2.33
Warning:
Division by zero will raise a ZeroDivisionError.
"""
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
result = round(a / b, self.precision)
self.history.append(f"{a} / {b} = {result}")
return result
def power(self, base: Union[int, float], exponent: Union[int, float]) -> float:
"""Raise base to the power of exponent.
Args:
base (Union[int, float]): Base number
exponent (Union[int, float]): Exponent
Returns:
float: Result of base^exponent, rounded to specified precision
Example:
>>> calc = CalculatorStep2()
>>> calc.power(2, 3)
8.0
>>> calc.power(4, 0.5)
2.0
Note:
This method uses Python's built-in ** operator.
For more advanced mathematical functions, consider using
the :mod:`math` module.
"""
result = round(base ** exponent, self.precision)
self.history.append(f"{base} ^ {exponent} = {result}")
return result
# Step 3: Add utility methods and demonstrate advanced Sphinx features
# ===============================================================================
# Explanation:
# Building on Steps 1-2, we'll add utility methods and demonstrate
# advanced Sphinx features like parameter tables, cross-references, and code blocks.
# Continue the Calculator class from Steps 1-2:
class CalculatorStep3:
"""Complete calculator class with utility methods.
This class includes all basic operations plus utility methods for
history management and advanced mathematical functions.
Attributes:
history (List[str]): A list of performed operations
precision (int): Number of decimal places for results
Note:
This calculator maintains operation history for debugging purposes.
Use :meth:`clear_history` to reset the history when needed.
See Also:
:class:`Calculator`: Basic calculator implementation
:func:`math.pow`: Built-in power function
:mod:`math`: Mathematical functions module
"""
def __init__(self, precision: int = 2):
"""Initialize the calculator.
Args:
precision (int, optional): Number of decimal places for results.
Defaults to 2.
Raises:
ValueError: If precision is negative.
Example:
>>> calc = CalculatorStep3(precision=3)
>>> calc.precision
3
"""
if precision < 0:
raise ValueError("Precision must be non-negative")
self.precision = precision
self.history: List[str] = []
def add(self, a: Union[int, float], b: Union[int, float]) -> float:
"""Add two numbers.
Args:
a (Union[int, float]): First number
b (Union[int, float]): Second number
Returns:
float: Sum of a and b, rounded to specified precision
Example:
>>> calc = CalculatorStep3()
>>> calc.add(5, 3)
8.0
>>> calc.add(2.5, 1.7)
4.2
"""
result = round(a + b, self.precision)
self.history.append(f"{a} + {b} = {result}")
return result
def subtract(self, a: Union[int, float], b: Union[int, float]) -> float:
"""Subtract second number from first number.
Args:
a (Union[int, float]): Number to subtract from
b (Union[int, float]): Number to subtract
Returns:
float: Difference of a and b, rounded to specified precision
Example:
>>> calc = CalculatorStep3()
>>> calc.subtract(10, 3)
7.0
>>> calc.subtract(5.5, 2.2)
3.3
"""
result = round(a - b, self.precision)
self.history.append(f"{a} - {b} = {result}")
return result
def multiply(self, a: Union[int, float], b: Union[int, float]) -> float:
"""Multiply two numbers.
Args:
a (Union[int, float]): First number
b (Union[int, float]): Second number
Returns:
float: Product of a and b, rounded to specified precision
Example:
>>> calc = CalculatorStep3()
>>> calc.multiply(4, 5)
20.0
>>> calc.multiply(2.5, 3)
7.5
"""
result = round(a * b, self.precision)
self.history.append(f"{a} * {b} = {result}")
return result
def divide(self, a: Union[int, float], b: Union[int, float]) -> float:
"""Divide first number by second number.
Args:
a (Union[int, float]): Dividend
b (Union[int, float]): Divisor
Returns:
float: Quotient of a and b, rounded to specified precision
Raises:
ZeroDivisionError: If divisor is zero
Example:
>>> calc = CalculatorStep3()
>>> calc.divide(10, 2)
5.0
>>> calc.divide(7, 3)
2.33
Warning:
Division by zero will raise a ZeroDivisionError.
"""
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
result = round(a / b, self.precision)
self.history.append(f"{a} / {b} = {result}")
return result
def power(self, base: Union[int, float], exponent: Union[int, float]) -> float:
"""Raise base to the power of exponent.
Args:
base (Union[int, float]): Base number
exponent (Union[int, float]): Exponent
Returns:
float: Result of base^exponent, rounded to specified precision
Example:
>>> calc = CalculatorStep3()
>>> calc.power(2, 3)
8.0
>>> calc.power(4, 0.5)
2.0
Note:
This method uses Python's built-in ** operator.
For more advanced mathematical functions, consider using
the :mod:`math` module.
"""
result = round(base ** exponent, self.precision)
self.history.append(f"{base} ^ {exponent} = {result}")
return result
def get_history(self) -> List[str]:
"""Get the calculation history.
Returns:
List[str]: List of all performed operations
Example:
>>> calc = CalculatorStep3()
>>> calc.add(5, 3)
8.0
>>> calc.multiply(2, 4)
8.0
>>> calc.get_history()
['5 + 3 = 8.0', '2 * 4 = 8.0']
"""
return self.history.copy()
def clear_history(self) -> None:
"""Clear the calculation history.
Example:
>>> calc = CalculatorStep3()
>>> calc.add(5, 3)
8.0
>>> len(calc.get_history())
1
>>> calc.clear_history()
>>> len(calc.get_history())
0
"""
self.history.clear()
def sqrt(self, number: Union[int, float]) -> float:
"""Calculate square root of a number.
Args:
number (Union[int, float]): Number to calculate square root for
Returns:
float: Square root of the number, rounded to specified precision
Raises:
ValueError: If number is negative
Example:
>>> calc = CalculatorStep3()
>>> calc.sqrt(16)
4.0
>>> calc.sqrt(2)
1.41
Note:
This method uses :func:`math.sqrt` for calculation.
"""
if number < 0:
raise ValueError("Cannot calculate square root of negative number")
result = round(math.sqrt(number), self.precision)
self.history.append(f"√{number} = {result}")
return result
def factorial(self, n: int) -> int:
"""Calculate factorial of a number.
Args:
n (int): Non-negative integer to calculate factorial for
Returns:
int: Factorial of n
Raises:
ValueError: If n is negative
TypeError: If n is not an integer
Example:
>>> calc = CalculatorStep3()
>>> calc.factorial(5)
120
>>> calc.factorial(0)
1
Note:
This method uses :func:`math.factorial` for calculation.
See Also:
:func:`math.factorial`: Built-in factorial function
"""
if not isinstance(n, int):
raise TypeError("Factorial is only defined for integers")
if n < 0:
raise ValueError("Factorial is only defined for non-negative integers")
result = math.factorial(n)
self.history.append(f"{n}! = {result}")
return result
# Step 4: Create Sphinx configuration and documentation structure
# ===============================================================================
# Explanation:
# Building on Steps 1-3, we'll now create the Sphinx configuration files
# and documentation structure that would be used to generate HTML documentation.
# Sphinx conf.py configuration (this would be in docs/conf.py):
SPHINX_CONF_PY = '''
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = 'Calculator Documentation'
copyright = '2025, Python Practices'
author = 'Python Practices Team'
release = '1.0.0'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = [
'sphinx.ext.autodoc', # Automatic documentation from docstrings
'sphinx.ext.viewcode', # Add source code links
'sphinx.ext.napoleon', # Support for Google and NumPy style docstrings
'sphinx.ext.intersphinx', # Link to other project's documentation
'sphinx.ext.todo', # Support for todo items
'sphinx.ext.coverage', # Coverage checker
'sphinx.ext.mathjax', # Math support
'sphinx.ext.ifconfig', # Include content based on configuration
'sphinx.ext.githubpages', # Publish HTML docs in GitHub Pages
]
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output ------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'sphinx_rtd_theme' # Read the Docs theme
html_static_path = ['_static']
# -- Extension configuration ------------------------------------------------
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_preprocess_types = False
napoleon_type_aliases = None
napoleon_attr_annotations = True
# Autodoc settings
autodoc_default_options = {
'members': True,
'member-order': 'bysource',
'special-members': '__init__',
'undoc-members': True,
'exclude-members': '__weakref__'
}
# Intersphinx mapping
intersphinx_mapping = {
'python': ('https://docs.python.org/3', None),
'numpy': ('https://numpy.org/doc/stable/', None),
}
# Todo extension
todo_include_todos = True
'''
# Main index.rst file (this would be in docs/index.rst):
SPHINX_INDEX_RST = '''
Calculator Documentation
========================
Welcome to the Calculator project documentation!
This project demonstrates comprehensive Sphinx documentation practices
for Python projects, including API documentation, tutorials, and examples.
.. toctree::
:maxdepth: 2
:caption: Contents:
installation
quickstart
api
examples
advanced
contributing
Features
--------
* Basic arithmetic operations (add, subtract, multiply, divide)
* Advanced mathematical functions (power, square root, factorial)
* Operation history tracking
* Configurable precision
* Comprehensive error handling
Quick Example
-------------
Here's a quick example of how to use the Calculator:
.. code-block:: python
from calculator import CalculatorStep3
# Create a calculator with 3 decimal places
calc = CalculatorStep3(precision=3)
# Perform some calculations
result1 = calc.add(10, 5)
result2 = calc.multiply(result1, 2)
result3 = calc.sqrt(result2)
# Check the history
print(calc.get_history())
Installation
------------
.. code-block:: bash
pip install calculator
For development installation:
.. code-block:: bash
git clone https://github.com/example/calculator.git
cd calculator
pip install -e .
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
'''
# API documentation file (this would be in docs/api.rst):
SPHINX_API_RST = '''
API Reference
=============
This section contains the complete API reference for the Calculator module.
Calculator Module
-----------------
.. automodule:: calculator
:members:
:undoc-members:
:show-inheritance:
Calculator Class
----------------
.. autoclass:: calculator.CalculatorStep3
:members:
:undoc-members:
:show-inheritance:
:special-members: __init__
Basic Operations
~~~~~~~~~~~~~~~~
.. automethod:: calculator.CalculatorStep3.add
.. automethod:: calculator.CalculatorStep3.subtract
.. automethod:: calculator.CalculatorStep3.multiply
.. automethod:: calculator.CalculatorStep3.divide
Advanced Operations
~~~~~~~~~~~~~~~~~~~
.. automethod:: calculator.CalculatorStep3.power
.. automethod:: calculator.CalculatorStep3.sqrt
.. automethod:: calculator.CalculatorStep3.factorial
Utility Methods
~~~~~~~~~~~~~~~
.. automethod:: calculator.CalculatorStep3.get_history
.. automethod:: calculator.CalculatorStep3.clear_history
Constants
---------
.. autodata:: calculator.PI
:annotation: = 3.141592653589793
.. autodata:: calculator.E
:annotation: = 2.718281828459045
Exceptions
----------
The calculator may raise the following exceptions:
.. py:exception:: ValueError
Raised when invalid input values are provided.
.. py:exception:: ZeroDivisionError
Raised when attempting to divide by zero.
.. py:exception:: TypeError
Raised when incorrect types are provided to methods.
'''
# Step 5: Add tutorial and example documentation files
# ===============================================================================
# Explanation:
# Building on Steps 1-4, we'll add comprehensive tutorial and example
# documentation files that demonstrate various Sphinx features.
# Quickstart guide (this would be in docs/quickstart.rst):
SPHINX_QUICKSTART_RST = '''
Quick Start Guide
=================
This guide will help you get started with the Calculator module quickly.
Installation
------------
First, install the calculator module:
.. code-block:: bash
pip install calculator
Basic Usage
-----------
Import and Create Calculator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: python
from calculator import CalculatorStep3
# Create a calculator with default precision (2 decimal places)
calc = CalculatorStep3()
# Or create with custom precision
calc_precise = CalculatorStep3(precision=4)
Perform Basic Operations
~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: python
# Addition
result = calc.add(10, 5)
print(f"10 + 5 = {result}") # Output: 10 + 5 = 15.0
# Subtraction
result = calc.subtract(20, 8)
print(f"20 - 8 = {result}") # Output: 20 - 8 = 12.0
# Multiplication
result = calc.multiply(6, 7)
print(f"6 * 7 = {result}") # Output: 6 * 7 = 42.0
# Division
result = calc.divide(15, 3)
print(f"15 / 3 = {result}") # Output: 15 / 3 = 5.0
Advanced Operations
~~~~~~~~~~~~~~~~~~~
.. code-block:: python
# Power
result = calc.power(2, 8)
print(f"2^8 = {result}") # Output: 2^8 = 256.0
# Square root
result = calc.sqrt(16)
print(f"√16 = {result}") # Output: √16 = 4.0
# Factorial
result = calc.factorial(5)
print(f"5! = {result}") # Output: 5! = 120
Working with History
~~~~~~~~~~~~~~~~~~~~
.. code-block:: python
# Perform some operations
calc.add(5, 3)
calc.multiply(2, 4)
calc.sqrt(16)
# Get operation history
history = calc.get_history()
for operation in history:
print(operation)
# Clear history
calc.clear_history()
print(f"History after clear: {calc.get_history()}") # Output: []
Error Handling
--------------
The calculator includes comprehensive error handling:
.. code-block:: python
try:
# This will raise ZeroDivisionError
calc.divide(10, 0)
except ZeroDivisionError as e:
print(f"Error: {e}")
try:
# This will raise ValueError
calc.sqrt(-4)
except ValueError as e:
print(f"Error: {e}")
try:
# This will raise TypeError
calc.factorial(3.5)
except TypeError as e:
print(f"Error: {e}")
Next Steps
----------
* Read the :doc:`api` for complete method documentation
* Check out :doc:`examples` for more complex usage scenarios
* See :doc:`advanced` for advanced features and customization
'''
# Examples documentation (this would be in docs/examples.rst):
SPHINX_EXAMPLES_RST = '''
Examples
========