Canstralian commited on
Commit
de4f7db
·
verified ·
1 Parent(s): 2963906

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -0
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import re
3
+
4
+ def calculate(value, operation):
5
+ """
6
+ Perform the specified operation on the given value.
7
+
8
+ Parameters:
9
+ value (int or float): The number to operate on.
10
+ operation (str): The operation to perform ('square', 'cube', 'double').
11
+
12
+ Returns:
13
+ int or float: The result of the operation.
14
+ """
15
+ operations = {
16
+ 'square': lambda x: x ** 2,
17
+ 'cube': lambda x: x ** 3,
18
+ 'double': lambda x: x * 2
19
+ }
20
+ return operations[operation](value)
21
+
22
+ def is_valid_input(user_input):
23
+ """
24
+ Validate user input using regular expressions to ensure it is a number.
25
+
26
+ Parameters:
27
+ user_input (str): The user input to validate.
28
+
29
+ Returns:
30
+ bool: True if the input is valid, False otherwise.
31
+ """
32
+ pattern = r'^\d+(\.\d+)?$' # Match integers and floating point numbers
33
+ return bool(re.match(pattern, user_input))
34
+
35
+ def main():
36
+ """
37
+ The main function to run the Streamlit app.
38
+ """
39
+ st.title("Enhanced Calculator")
40
+
41
+ # Select operation
42
+ operation = st.selectbox("Select an operation", ('square', 'cube', 'double'))
43
+
44
+ # Slider for numeric input
45
+ x = st.slider('Select a value', min_value=0.0, max_value=100.0, value=1.0, step=0.1)
46
+
47
+ # Validate numeric input using regular expression
48
+ user_input = st.text_input("Or enter a number:")
49
+ if user_input and is_valid_input(user_input):
50
+ x = float(user_input)
51
+ elif user_input:
52
+ st.error("Invalid input. Please enter a valid number.")
53
+
54
+ # Calculate the result
55
+ result = calculate(x, operation)
56
+
57
+ # Display the result
58
+ st.write(f'The {operation} of {x} is {result}')
59
+
60
+ if __name__ == "__main__":
61
+ main()