Reputation: 19
I want to enter an operator, +, -, , /, //, %, to perform a math operation using this program in 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? 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()
Upvotes: 0
Views: 361
Reputation: 19
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())". My new line is this: "str(n) + str(operator) + str(i) + "= " + str(n + i)". I then made 4 lines with it. 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. Combined with the user input code for choosing an operator, the operator the user chooses will call on the corresponding nested if statement. Finally, the code inside the nested if statement will perform the math and write it to the .txt file. Thanks for your answers everyone, they helped a lot. Have a nice day.
Upvotes: 0
Reputation: 6156
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. You can put pretty much any code in that f string
.
About security:
As someone in the comments mentioned this isn't safe (the use of 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
):
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.
Upvotes: 1
Reputation: 4670
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
Upvotes: 2