slimshadow commited on
Commit
5e286c3
·
verified ·
1 Parent(s): 2740c96

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ def calculate(expression):
4
+ """
5
+ Calculates the mathematical expression using a safer approach
6
+ than eval().
7
+
8
+ Args:
9
+ expression (str): The mathematical expression to be evaluated.
10
+
11
+ Returns:
12
+ float: The result of the calculation, or None if an error occurs.
13
+ """
14
+
15
+ try:
16
+ # Use ast.literal_eval() for a more secure evaluation
17
+ result = ast.literal_eval(expression)
18
+ except (SyntaxError, ValueError):
19
+ return None # Indicate an error
20
+
21
+ return result
22
+
23
+ st.set_page_config(page_title="Beautiful Calculator", page_icon="calculator")
24
+ st.title("Beautiful Calculator")
25
+
26
+ # Use columns for a visually appealing layout
27
+ col1, col2 = st.columns(2)
28
+
29
+ # Create input fields for numbers and expression
30
+ num1 = col1.number_input("First Number", key="num1")
31
+ num2 = col2.number_input("Second Number", key="num2")
32
+ user_expr = st.text_input("Enter Expression (e.g., +,-,*,/)", key="expression")
33
+
34
+ # Create buttons for basic operations
35
+ operators = ["+", "-", "*", "/"]
36
+ for operator in operators:
37
+ if st.button(operator, key=operator):
38
+ # Ensure at least one number is provided before calculation
39
+ if num1 is not None and num2 is not None:
40
+ result = calculate(f"{num1} {operator} {num2}")
41
+ else:
42
+ result = None
43
+
44
+ if result is not None:
45
+ st.write(f"{num1} {operator} {num2} = {result}")
46
+ else:
47
+ st.error("Invalid expression or division by zero")
48
+
49
+ # Display the user-entered expression for reference
50
+ st.write("Your expression:", user_expr)