我对python非常陌生,我有一个辅助功能,可以在python的流光中创建一个计算器,而且我在实现它方面遇到了困难,我在一门课程中遇到了困难,老师对我非常没有帮助,而且它让我非常烦恼,以至于我需要自己学习,我试着开始使用计算器的代码,我达到了无法继续的临界点,因为我不知道怎么做,我需要通过一系列数学题(1+1,5*8,等等)。计算器会打印“你的答案是:”而答案,你能帮我修改代码并解释你做了什么吗?提前谢谢。
import streamlit as st
st.title(' ofir Calculator')
strex=""
st.text_input('Please enter a mathematical expression',strex)
def valid_expression(strex):
for i in range(len(strex)):
if (strex[i]>='0' and strex[i]<='9') or strex[i]=='+' or strex[i]=='-' or strex[i]=='*' or strex[i]=='/':
if i==0:
if strex[i]=='+' or strex[i]=='-' or strex[i]=='*' or strex[i]=='/':
return False
pass
else:
return False
if not valid_expression(strex):
st.error("Invalid Exrpession")发布于 2022-05-31 12:06:51
这是从您的代码中修改的代码。我添加了一些字符以使其成为合法字符,并且我们使用eval()来计算表达式的值。代码被注释了。
代码
import streamlit as st
def get_value(user_expr):
"""
We use eval() to get the value of the expression.
ref: https://docs.python.org/3/library/functions.html#eval
"""
return eval(user_expr, {"__builtins__": None})
def valid_expression(strex):
"""
Evaluate if strex is a valid mathematical expression.
"""
for i in range(len(strex)):
# If the first char is invalid.
if i==0:
if strex[i] in ['+', '-', '*', '/', '%', ')']:
return False
# If the last char is also invalid.
if i == len(strex) - 1:
if strex[i] in ['+', '-', '*', '/', '%', '(']:
return False
# Validate char if it is a number, operators or parenthesis.
if (strex[i] >= '0' and strex[i] <= '9') or strex[i] in ['+', '-', '*', '/', '%', '(', ')']:
continue # continue with the next character
else:
return False
return True # We cannot find invalid chars.
def main():
st.title(' ofir Calculator')
# The input value from the user will be saved in user_expr.
user_expr = st.text_input('Please enter a mathematical expression')
if not valid_expression(user_expr):
st.error("Invalid Expression")
else:
st.success("Valid Expression")
# Get the value of the expression.
value = get_value(user_expr)
st.write(f'The answer is {value}.') # ref.: https://docs.python.org/3/tutorial/inputoutput.html
# Entry point
main()样本输出


https://stackoverflow.com/questions/72443689
复制相似问题