Python Forum

Full Version: Beginner Question - Esaping the Escape Character correctly?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am working on some basic programming homework, a calculator. The code is below.

I would like for the user to be able to input / or \ for division. However, the code below does not work. If I remove the or "\\", the program runs fine. Any guidance is appreciated!

print("Acceptable operators include *, /, \, +, -")
math_num1 = input("Please enter the first number: ")
math_oper = input("Please enter the operator: ")
math_num2 = input("Please enter the second number: ")

if math_oper == "*":
    print(int(math_num1) * int(math_num2))
elif math_oper == "/" or "\\":
    print(int(math_num1) / int(math_num2))
elif math_oper == "+":
    print(int(math_num1) + int(math_num2))
elif math_oper == "-":
    print(int(math_num1) - int(math_num2))
else:
    print("Invalid Input! Please try again.")
read https://python-forum.io/Thread-Multiple-...or-keyword

the problem is on line 8, how you use/expect or to work
Note that you should also escape the backslash on the first line, when you print the instructions.
I observe that in else: clause you try to validate only operator. Code has no defence against user entering value which cannot be converted into int.

For 'calculator' it's more conventional to use dictionary of operators, you can save lot of typing.
Thank you! The program is now working. Strangely I did not have to escape the slash in the instructions... I'm not asking questions.