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