slimshadow commited on
Commit
61742c6
·
verified ·
1 Parent(s): 5e286c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -43
app.py CHANGED
@@ -1,50 +1,34 @@
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)
 
1
  import streamlit as st
2
 
3
+ # Function to perform the calculation
4
+ def calculate(operation, num1, num2):
5
+ if operation == 'Addition':
6
+ return num1 + num2
7
+ elif operation == 'Subtraction':
8
+ return num1 - num2
9
+ elif operation == 'Multiplication':
10
+ return num1 * num2
11
+ elif operation == 'Division':
12
+ if num2 != 0:
13
+ return num1 / num2
14
+ else:
15
+ return 'Error: Division by zero'
 
 
 
 
 
 
 
 
 
16
 
17
+ # Streamlit app
18
+ def main():
19
+ st.title("Simple Calculator")
20
 
21
+ # Input numbers
22
+ num1 = st.number_input("Enter first number", value=0.0, format="%f")
23
+ num2 = st.number_input("Enter second number", value=0.0, format="%f")
 
24
 
25
+ # Select operation
26
+ operation = st.selectbox("Select operation", ['Addition', 'Subtraction', 'Multiplication', 'Division'])
 
 
 
 
 
 
 
27
 
28
+ # Perform calculation
29
+ if st.button("Calculate"):
30
+ result = calculate(operation, num1, num2)
31
+ st.write(f"Result: {result}")
32
 
33
+ if __name__ == "__main__":
34
+ main()