Python Forum

Full Version: Beginner Help request: Calculator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am just starting to get my feet wet with Python and would like to ask for some insight as to why this script goes directly to the "else" line.

The code is as follows:

# adding two numbers
def add(x, y):
    return x + y

#subtracting two numbers
def subtract(x, y):
    return x - y

#multiplies two numbers
def multiply(x, y):
    return x * y

#divide two numbers
def divide(x, y):
    return x / y

print("Select operation")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

#take input from user
choice = input("Enter choice(1/2/3/4):")


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
    print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
    print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
    print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
    print(num1,"/",num2,"=", divide(num1,num2))

else:
    print("Invalid input")
Cheers,
J
you are converting the input into an integer and then testing in the if statement for a string. int('2') will be a number. '1' or '2' is a string. Does that help?
First of all write your code inside Python tags.
Your code is running correctly on my side.
what version of python do you use? If I guess - you are using Python2 to run the code, while it is intended for python3... And in python2 input actually evaluates the user input, so choice in converted to int.
If you are using python2, you should use raw_input, instead of input. Or simply use python3
Python 3 resolved it! Funny how there are differences with syntax between the two versions. Thank you all for the input.

Also, will heed the tags in future posts, thanks for the correction.

J
(Sep-20-2017, 12:40 AM)JinLee Wrote: [ -> ]Python 3 resolved it! Funny how there are differences with syntax between the two versions.

In python2, input() will call eval() on whatever you type in, which is incredibly bad. In python3, input() was removed completely, and replaced with what used to be raw_input(), since that's what 99.9% of people want to be using anyway.

That fixed it for you, because when you type a number, it'd get passed to eval() in python2, and would then be a number, instead of a string. In python3, anything from input() is always a string.