0

Hi I am new to Python having an indentation error in the following code:

print "------------------------- Basics Arithamatic Calculator-------------------------"

int_num_one=input('Enter First Num: ')
int_num_two=input('Enter Second Num: ')

list_options={"+", "-", "/", "*"}

print "Which operation you want to perform *, -, +, / ?"
char_selected_option=raw_input()
print "Operation selected is %r" % (char_selected_option)

for char_symbol in list_options:
    print "Char symbol is %r" % (char_symbol)
bool_operation_Not_Found=True
if char_symbol==char_selected_option:
    int_result=str(int_num_one) + char_selected_option + str(int_num_two)
    print int_result
    print "%d %s %d = %d" % (int_num_one, char_selected_option, int_num_two, eval(int_result))
    bool_operation_Not_Found=False
break
if bool_operation_Not_Found:
print "Invalid Input"
Zubair
  • 5,833
  • 3
  • 27
  • 49
  • the `break` is in the wrong place as it does not belong to the `for` loop – Mailerdaimon Nov 20 '13 at 08:14
  • A quick note about your `bool_operation_Not_Found` flag: You can probably get rid of this in favor of using an `else` clause following your `for` loop. The `else`'s block will only be run if the loop ran off the end of its sequence without `break`ing. – Blckknght Nov 20 '13 at 08:18
  • @Blckknght, can you give a code snippet.. I think then the else block will be executed every time the if fails. – Zubair Nov 20 '13 at 10:14
  • @Zubair: Um, the code is easy. If you're using MattD's properly indented code in his answer, just replace the `if bool_operation_Not_Found:` line near the end with `else:` (at the same indentation level as the `for`). You can also remove the lines setting the flag to `True` or `False`, if you feel like it (since they're no longer needed). – Blckknght Nov 20 '13 at 10:21

2 Answers2

1

It looks like the code 'inside' the for loop was not indented correctly, this should work.

for char_symbol in list_options:
    print "Char symbol is %r" % (char_symbol)
    bool_operation_Not_Found=True
    if char_symbol==char_selected_option:
        int_result=str(int_num_one) + char_selected_option + str(int_num_two)
        print int_result
        print "%d %s %d = %d" % (int_num_one, char_selected_option, int_num_two, eval(int_result))
        bool_operation_Not_Found=False
        break
if bool_operation_Not_Found:
    print "Invalid Input"
MattD
  • 42
  • 9
0

This could be a lot shorter; instead of using a set and eval, you could use a dictionary of functions:

ops = {'+': lambda a, b: a + b,
       '-': lambda a, b: a - b,
       '/': lambda a, b: float(a) / b,
       '*': lambda a, b: a * b,
       }
try:
    print "%d %s %d = %f" % (
            int_num_one,
            char_symbol,
            int_num_two,
            ops[char_symbol](int_num_one, int_num_two),
            )
except KeyError:
    print "Invalid Input"
Tobias
  • 2,481
  • 3
  • 26
  • 38