简体   繁体   English

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

[英]Enter an operator to perform a math operation

I want to enter an operator, +, -, , /, //, %, to perform a math operation using this program in python.我想在 python 中输入一个运算符,+, -, , /, //, % 来执行数学运算。 How do I code these strings: "s = str(n) + " " + str(i) + "= " + str(n * i)" for the.txt file funtions and "print(n, "*", i, "=", n * i)" to include the operator I choose?我如何对这些字符串进行编码:“s = str(n) + " " + str(i) + "= " + str(n * i)" 用于 .txt 文件功能和 "print(n, "*", i, "=", n * i)" 包括我选择的运算符? I'm not sure how to get this to work.我不知道如何让它工作。 Thanks for your time.谢谢你的时间。

#!/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()

Here is an option:这是一个选项:

operator = input('Enter an operator: ')

operators = '+-**/'

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

The program will ask for user input and then check if the input is in operators and if it is it will print out whatever result from using 2 and 3 and that operator.该程序将要求用户输入,然后检查输入是否在运算符中,如果是,它将打印出使用 2 和 3 以及该运算符的任何结果。 You can put pretty much any code in that f string .您可以在该f string中放置几乎任何代码。

About security:关于安全:

As someone in the comments mentioned this isn't safe (the use of exec() )?正如评论中提到的那样,这不安全(使用exec() )? Since I can only assume it is because then it is possible to run any code (including malicious) You can just filter what the user inputs.因为我只能假设这是因为它可以运行任何代码(包括恶意代码)您可以过滤用户输入的内容。

Here is probably an implementation to Your code (should use python 3.6 or higher or sth like that that supports f strings ):这可能是您的代码的实现(应该使用 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)

However this doesn't seem as efficient as I thought at first so You probably are better of using the other answer with using dictionaries and defining a function.然而,这似乎并不像我起初想的那么有效,所以您可能最好使用其他答案来使用字典并定义 function。

You could use a dictionary lookup:您可以使用字典查找:

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)

With a few test runs:通过一些测试运行:

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

To get it to work, I took the code I had: "s = str(n) + "*" + str(i) + "= " + str(n * i)" and modified this line using inspiration from code provided by @Matiiss: "exec(f"""result = {n}{operator}{i}""", globals())".为了让它工作,我使用了我的代码:"s = str(n) + "*" + str(i) + "= " + str(n * i)" 并使用提供的代码的灵感修改了这一行@Matiiss: "exec(f"""result = {n}{operator}{i}""", globals())"。 My new line is this: "str(n) + str(operator) + str(i) + "= " + str(n + i)".我的新行是这样的:“str(n) + str(operator) + str(i) + "= " + str(n + i)"。 I then made 4 lines with it.然后我用它做了4行。 Each line does one math operation: +, -, *, /.每行执行一次数学运算:+、-、*、/。 Then I did a nested if statement for each individual operation under the four lines that calls on the dictionary that @JacobLee provided.然后我在调用@JacobLee 提供的字典的四行下为每个单独的操作做了一个嵌套的 if 语句。 Combined with the user input code for choosing an operator, the operator the user chooses will call on the corresponding nested if statement.结合用户选择算子的输入代码,用户选择的算子会调用对应的嵌套if语句。 Finally, the code inside the nested if statement will perform the math and write it to the.txt file.最后,嵌套 if 语句中的代码将执行数学运算并将其写入 .txt 文件。 Thanks for your answers everyone, they helped a lot.谢谢大家的回答,他们帮了很多忙。 Have a nice day.祝你今天过得愉快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM