I'm trying to set up a situation in which the user inputs a number and an operator and the output is the (user number) (user operator) on a list of 1 through 10.
This is hard to explain, but here's the code:
num = int(input("Enter a number greater than 1: "))
oper = input("Choose a math operation (+, -, *): ")
for i in range(1, 11):
print(num)
And I get lost there. I want to get something that looks like
num oper 1 = (whatever num and the operator and 1 equal)
num oper 2 = (whatever num and the operator and 2 equal)
And so on.
So my question is: How do you assign a user-inputted operator to a variable?
Another possibility is to use the operator module to set up a dictionary of operator functions, like so:
import operator
operator_dict = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
}
num = int(input("Enter a number greater than 1: "))
oper = input("Choose a math operation (+, -, *): ")
for i in range(1, 11):
print(operator_dict[oper](float(num), i))
An example session:
Enter a number greater than 1: 3
Choose a math operation (+, -, *): *
3.0
6.0
9.0
12.0
15.0
18.0
21.0
24.0
27.0
30.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With