How can I condense a 'for x in range' statement within a 'if' 'elif' statement within a 'while' statement

I have a code that makes a math table and I feel has the possibility to be reduced as I have three of the same codes repeated but with only slightly different solutions for each of the if/elif statements.

num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
    x=str(input("\tEnter Math Operation: "))
    if x=="+":
        for table in range(1,11):
            print(str(num),str(x),table,"=",num+table) 
    elif x=="-":
       for table in range(1,11):
            print(str(num),str(x),table,"=",num-table) 
    elif x=="*":
       for table in range(1,11):
            print(str(num),str(x),table,"=",num*table)

Please tell me how this code can be condensed.


You would typically do something like this:

  • Store the operator as a function in a variable

  • Use a dictionary to look up operators

  • Use .format() instead of putting lots of string pieces together

  • Don't use str() if the argument is already a string

Here is what that looks like:

import operator
x = 10
operators = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
}
while True:
    op_name = input('Enter Math Operation ({}): '.format(', '.join(operators)))
    op_func = operators.get(op_name)
    if op_func is not None:
        break
for y in range(1, 11):
    print('{} {} {} = {}'.format(x, op_name, y, op_func(x, y)))

You can use a lookup table to store the different functions

num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
    x=str(input("\tEnter Math Operation: "))
ops = {
    '+': lambda x, y: x+y,
    '-': lambda x, y: x-y,
    '*': lambda x, y: x*y}

fn = ops[x]
for table in range(1,11):
    print(str(num),str(x),table,"=",fn(num,table))

Functions are first class objects in python. Assign the right function to a variable, and then use it.

num=10
x=str(input("Enter Math Operation (+, -, *): "))
# Read operation
while (x != "+" and x != "-" and x != "*"):
    x=str(input("\tEnter Math Operation: "))
# Select appropriate function
if x=="+":
    op = lambda x, y : x + y
elif x=="-":
    op = lambda x, y : x - y
elif x=="*":
    op = lambda x, y : x * y

# Use function
for table in range(1,11):
    val = op(num, table)
    print(str(num), str(x),table,"=", val)