Spaces:
Paused
Paused
| import streamlit as st | |
| def calculate(expression): | |
| """ | |
| Calculates the mathematical expression using a safer approach | |
| than eval(). | |
| Args: | |
| expression (str): The mathematical expression to be evaluated. | |
| Returns: | |
| float: The result of the calculation, or None if an error occurs. | |
| """ | |
| try: | |
| # Use ast.literal_eval() for a more secure evaluation | |
| result = ast.literal_eval(expression) | |
| except (SyntaxError, ValueError): | |
| return None # Indicate an error | |
| return result | |
| st.set_page_config(page_title="Beautiful Calculator", page_icon="calculator") | |
| st.title("Beautiful Calculator") | |
| # Use columns for a visually appealing layout | |
| col1, col2 = st.columns(2) | |
| # Create input fields for numbers and expression | |
| num1 = col1.number_input("First Number", key="num1") | |
| num2 = col2.number_input("Second Number", key="num2") | |
| user_expr = st.text_input("Enter Expression (e.g., +,-,*,/)", key="expression") | |
| # Create buttons for basic operations | |
| operators = ["+", "-", "*", "/"] | |
| for operator in operators: | |
| if st.button(operator, key=operator): | |
| # Ensure at least one number is provided before calculation | |
| if num1 is not None and num2 is not None: | |
| result = calculate(f"{num1} {operator} {num2}") | |
| else: | |
| result = None | |
| if result is not None: | |
| st.write(f"{num1} {operator} {num2} = {result}") | |
| else: | |
| st.error("Invalid expression or division by zero") | |
| # Display the user-entered expression for reference | |
| st.write("Your expression:", user_expr) | |