IF statements and Input

Question:

I am just practising basic python and attempting to build a calculator with only addition, subtraction, and multiplication functions. When I run the code and input 1, 2, or 3, I get no output.

Here is my code:

question1 = input("Enter 1 to add, 2 to substract, or 3 to multiply: ")
if question1 == 1:
    num1 = input("Enter a number: ")
    num2 = input("Enter another number: ")
    result = float(num1) + float(num2)
    print(result)
elif question1 == 2:
    num1 = input("Enter a number: ")
    num2 = input("Enter another number: ")
    result = float(num1) + float(num2)
    print(result)
elif question1 == 3:
    num1 = input("Enter a number: ")
    num2 = input("Enter another number: ")
    result = float(num1) + float(num2)
    print(result))
Asked By: cameronleemc

||

Answers:

You are well on your way! As mentioned in the comments, all your statements are False because input() just by itself returns string type which will never be equal to an integer.

You just have to change the all the input() of your code to convert it as an int to be stored. Below is an example:

question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))
Answered By: BernardL

When you get some input with input() in Python3, you get a string.

Test it with following:

foo = input()
print(type(foo))

The result will be <class 'str'>(it means foo‘s type is string) regardless of your input. If you want to use that input as a integer, you will have to change the type to int(integer).

You should use int(input()) to get a integer like the following:

question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))

You have to change the number inputs in each of the if-else blocks too:

if question1 == 1:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 + num2
    print(result)

Or, you can just change it when you want to calculate:

num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
...
result = int(num1) + int(num2)
Answered By: Junho Yeo

You need to convert your input to the integer. Try this code:

question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))
if question1 == 1:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 + num2
    print(result)
elif question1 == 2:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 - num2
    print(result)
elif question1 == 3:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 * num2
    print(result)
Answered By: PushpikaWan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.