Chagrin / app.py
Canstralian's picture
Create app.py
de4f7db verified
raw
history blame
1.7 kB
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()