In the settings category add a new button that enables and disables the E notation for the results. Python 3.12 code: import math
import re
from typing import Any, Union, Callable
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QTextEdit, QScrollBar, QPushButton, QLabel, QFrame,
QGridLayout
)
from PySide6.QtGui import QFont
from PySide6.QtCore import Qt
-- Utility Functions --
def convert_angle(func: Callable[[float], float], x: float, use_degrees: bool) -> float:
"""Convert angle based on degree mode."""
return func(math.radians(x) if use_degrees else x)
-- Conversions Category --
def kilograms_to_pounds(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word.capitalize() for word in sentence.split())
def remove_duplicates(text: str) -> str:
"""Remove duplicate words and empty lines from a string."""
words = ' '.join(line.strip() for line in text.splitlines() if line.strip()).split()
return ' '.join(dict.fromkeys(words))
def preprocess_text_functions(expression: str) -> str:
"""Preprocess text functions to ensure proper quoting of arguments."""
def add_quotes(match):
func, args = match.groups()
return f'{func}("{args}")' if func in ['capitalize', 'duplicates'] else match.group(0)
return re.sub(r'\b(capitalize|duplicates)(([^)]+))', add_quotes, expression)
def validate_inverse_trig(expression: str, safe_globals: dict) -> Union[str, None]:
"""Validate inputs for inverse trigonometric functions."""
for func, arg in re.findall(r"(\b\w+\b)(([^)]+))", expression):
if func in ["asin", "acos"]:
try:
value = eval(arg, {"builtins": None}, safe_globals)
if abs(value) > 1:
return f"Error: {func}(x) is undefined for |x| > 1"
except Exception as e:
return f"Error: {e}"
return None
Assistant
def safe_evaluate(expression: str, safe_globals: dict) -> Union[float, str]:
"""Safely evaluate the expression and format the result."""
try:
result = eval(expression, {"builtins": None}, safe_globals)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
To add a new button in the Settings category that enables and disables E notation for the results, you'll need to make several modifications to your existing code. Below are the step-by-step instructions along with the updated Python 3.12 code incorporating the new feature.
Overview of Changes
Add a New State Variable: Introduce a boolean variable to track whether E notation is enabled or disabled.
Add a New Button in Settings: Create a new button within the Settings category to toggle E notation.
Update the Result Formatting: Modify the result display logic to format the output based on the E notation setting.
Step-by-Step Implementation
1. Add a New State Variable
Add a new instance variable self.use_e_notation in the CalculatorGUI class to keep track of the E notation state.
python
class CalculatorGUI(QMainWindow):
"""PySide6-based Calculator with Degrees/Radians toggle and history."""
def __init__(self):
super().__init__()
self.use_degrees = False
self.use_e_notation = False # New state variable for E notation
self.setup_window()
self.create_widgets()
self.layout_widgets()
2. Add a New Button in Settings
Modify the create_function_buttons method to include a new button for toggling E notation within the Settings category.
Add a method toggle_e_notation within the CalculatorGUI class to handle the enabling and disabling of E notation.
python
def toggle_e_notation(self) -> None:
"""Toggle the E notation setting."""
self.use_e_notation = not self.use_e_notation
state = "On" if self.use_e_notation else "Off"
self.e_notation_button.setText(f"E Notation: {state}")
4. Update the Result Formatting Logic
Modify the safe_evaluate and/or display_result methods to format the output based on the E notation setting. Here, we'll update the safe_evaluate function to respect the E notation preference.
python
def safe_evaluate(expression: str, safe_globals: dict, use_e_notation: bool) -> Union[float, str]:
"""Safely evaluate the expression and format the result."""
try:
result = eval(expression, {"builtins": None}, safe_globals)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
if isinstance(result, (int, float)):
if use_e_notation:
# Format using scientific notation with up to 2 decimal places
result = f"{result:.2e}"
else:
# Standard formatting with rounding
result = round(result, 2)
return result
except Exception as e:
return f"Error: {e}"
Update the evaluate_expression function to pass the use_e_notation flag:
Update the calculate method to include the use_e_notation flag when calling evaluate_expression:
python
def calculate(self) -> None:
"""Evaluate the expression and update history."""
expression = self.entry.text().strip()
if expression:
result = evaluate_expression(expression, use_degrees=self.use_degrees, use_e_notation=self.use_e_notation)
self.display_result(expression, result)
self.entry.clear()
5. Final Updated Code
Below is the complete updated code incorporating all the changes mentioned above.
python
Explanation of Changes
State Variable (self.use_e_notation):
Added to track whether E notation is enabled (True) or disabled (False).
E Notation Button (self.e_notation_button):
Created within the Settings category.
Initially labeled as "E Notation: Off".
Connected to the toggle_e_notation method to toggle its state.
toggle_e_notation Method:
Flips the self.use_e_notation boolean.
Updates the button text to reflect the current state ("On" or "Off").
Result Formatting (safe_evaluate and evaluate_expression):
Modified safe_evaluate to accept the use_e_notation flag.
If E notation is enabled, formats the result using scientific notation with two decimal places (e.g., 1.23e+04).
If disabled, rounds the result to two decimal places without using E notation.
Passing the E Notation Flag:
Updated evaluate_expression to accept and pass the use_e_notation flag.
Modified the calculate method to include the current state of E notation when evaluating expressions.
Running the Updated Calculator
With these changes, when you run your calculator application:
Settings Category:
Contains two buttons:
Radians/Degrees Toggle: Switches between radians and degrees for trigonometric calculations.
E Notation Toggle: Enables or disables scientific (E) notation for displaying results.
E Notation Behavior:
Enabled: Results will display in scientific notation, e.g., 1.23e+04.
Disabled: Results will display normally with up to two decimal places, e.g., 12300.00.
Example Usage
Default State (E Notation Off):
Input:100000
Output:100000.00
After Enabling E Notation:
Input:100000
Output:1.00e+05
This enhancement provides users with greater flexibility in how results are displayed, especially useful for handling very large or very small numbers.