首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >流光中的Python基础计算器

流光中的Python基础计算器
EN

Stack Overflow用户
提问于 2022-05-31 07:22:06
回答 1查看 262关注 0票数 0

我对python非常陌生,我有一个辅助功能,可以在python的流光中创建一个计算器,而且我在实现它方面遇到了困难,我在一门课程中遇到了困难,老师对我非常没有帮助,而且它让我非常烦恼,以至于我需要自己学习,我试着开始使用计算器的代码,我达到了无法继续的临界点,因为我不知道怎么做,我需要通过一系列数学题(1+1,5*8,等等)。计算器会打印“你的答案是:”而答案,你能帮我修改代码并解释你做了什么吗?提前谢谢。

代码语言:javascript
复制
 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")
EN

回答 1

Stack Overflow用户

发布于 2022-05-31 12:06:51

这是从您的代码中修改的代码。我添加了一些字符以使其成为合法字符,并且我们使用eval()来计算表达式的值。代码被注释了。

代码

代码语言:javascript
复制
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()

样本输出

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72443689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档