输入运算符以执行数学运算

2024-04-16 15:57:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想输入一个运算符,+,-,,/,/,/,%,用python中的这个程序执行一个数学运算。如何对这些字符串进行编码:“s=str(n)+”“+str(I)+”=“+str(n*I)”用于.txt文件函数,以及“print(n,*”,I,“=”,n*I)”以包含我选择的运算符?我不知道该怎么做。谢谢你抽出时间

#!/usr/bin/python

def tablep():
    n=int(input("Enter Number of .txt Files to Create:")) # number of txt files
   
    for x in range(0, n):
        n=int(input("Enter a Number to Create Multiples of: "))
        import operator
        operatorlookup = {
            '+': operator.add,
            '-': operator.sub,
            '*': operator.mul,
            '/': operator.truediv}
        o=int(input("Enter Calculation Symbols for Calculation You Want to Perform: "))
        m=operatorlookup.get(o)
        start=int(input("Enter a Start Range Number: "))
        end=int(input("Enter an End Range Number: "))
        f=int(input("Enter Table Number to Name .txt File: "))
        f_path = "table_" + str(f) + ".txt" # this will numerate each table 
        file = open(f_path, 'a') # 'a' tag will create a file if it doesn't exist
        
        if start<end:
            for i in range(start,end+1):
                s = str(n) + "*" + str(i) + "=  " + str(n * i) # I want to put the math operation of my choosing here in this "str(n * i)".
                file.write(s)
                file.write("\n")
                print(n,"*",i,"=", n * i) # I want to put the math operation of my choosing here in this "n * i)".

        elif start>end:
            for i in range(start,end,-1):
                s = str(n) + "*" + str(i) + "=  " + str(n * i) # I want to put the math operation of my choosing here in this "str(n * i)".
                file.write(s)
                file.write("\n")
                print(n, "*", i, "=", n * i) # I want to put the math operation of my choosing here in this "n * i)".

    file.close()
    print("\nYou are done creating files now. Run the program again if you want to create more. Thank you for using this program and have a nice day!\n")

w = tablep()

Tags: oftointxtnumberforinputthis
3条回答

为了让它正常工作,我使用了我的代码:“s=str(n)+”*“+str(I)+”=“+str(n*I)”并根据@matiss提供的代码修改了这一行:“exec(f)”“result={n}{operator}{I}”“,globals()”。我的新行是:“str(n)+str(操作符)+str(i)+”=“+str(n+i)”。然后我用它画了4行。每行做一个数学运算:+,-,*,/。然后,我对@JacobLee提供的字典中调用的四行下的每个操作都执行了一个嵌套的if语句。与用于选择运算符的用户输入代码相结合,用户选择的运算符将调用相应的嵌套if语句。最后,嵌套if语句中的代码将执行计算并将其写入.txt文件。谢谢大家的回答,他们帮了大忙。祝你今天愉快

您可以使用字典查找:

def evaluate(a: int, b: int, operation: str):
    oper = {
        "+": a+b, "-": a-b, "*": a*b, "/": a/b, "%": a%b, "//": a//b
    }
    return oper.get(operation)

通过一些测试运行:

>>> evaluate(2, 5, "+")
7
>>> evaluate(2, 5, "-")
-3
>>> evaluate(2, 5, "*")
10
>>> evaluate(2, 5, "bananas")
None

这里有一个选项:

operator = input('Enter an operator: ')

operators = '+-**/'

if operator in operators:
    executable = f'print(2{operator}3)'
    exec(executable)

程序将要求用户输入,然后检查输入是否在运算符中,如果是,它将打印使用2和3以及该运算符的任何结果。您可以在该f string中放置几乎任何代码

关于安全:

正如评论中提到的,这是不安全的(使用exec())?因为我只能假设这是因为可以运行任何代码(包括恶意代码),所以您只需过滤用户输入的内容即可

下面可能是您的代码的一个实现(应该使用python 3.6或更高版本或类似于支持f strings的东西):

n = 5
i = 3
operator = '*'

# main part ========================
result = None
exec(f"""result = {n}{operator}{i}""", globals())

s = f'''{n} * {i} = {result}'''
print(s)

然而,这似乎并不像我一开始想的那样有效,所以您可能会更好地使用另一个答案,使用字典和定义函数

相关问题 更多 >