-2

I'm trying to create a simple program using function and if else. Even though there is no errors, my program doesn't give expected result

value1 = float(input("Enter your first number:"))
value2 = float(input("Enter your second number:"))
question= input("choose mode:" )
add = True
def nor_cal(num1, num2):
    if question == add:
        total = num1+num2
        print("the total is: ")
        print(total)
    else:
        print("Invalid operator")
result1 = nor_cal(value1, value2)
print(result1)

when i run the program, it shows like this:

Enter your first number:2
Enter your second number:3
choose mode:add
Invalid operator
None

I don't know where i'm wrong please help !

  • 2
    Does this answer your question? [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – Silvio Mayolo Jul 21 '21 at 15:22
  • 5
    The variable named `question` has the value `"add"` while the variable named `add` has the value `True`. The two variables do not have the same value. – jarmod Jul 21 '21 at 15:23
  • 2
    Use a debugger and check what values it shows for each variable when you hit the line `if question == add` – DeepSpace Jul 21 '21 at 15:24
  • There's a difference between `add` and `"add"`. One is a variable (in your case holding a boolean value) and the other is a string (containing the ascii characters 'a,d,d'. – blackbrandt Jul 21 '21 at 15:24
  • Please read about [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). You can also use [Python-Tutor](http://www.pythontutor.com/visualize.html#mode=edit) which helps to visualize the execution of the code step-by-step. – Tomerikoo Jul 21 '21 at 15:31

2 Answers2

3

The bug is in the line if question == add:, what you're asking the program to do is to compare the variable question (which is "add") to the variable add (which is True).

You're going to want to use if question == "add": instead.

tripleee
  • 158,107
  • 27
  • 234
  • 292
AceKiron
  • 94
  • 7
0

Is this what you are looking for?

value1 = float(input("Enter your first number:"))
value2 = float(input("Enter your second number:"))
question= input("choose mode:" )
add = "add"
def nor_cal(num1, num2):
    if question == add:
        total = num1+num2
        print("the total is: ")
        print(total)
        return total
    else:
        print("Invalid operator")
result1 = nor_cal(value1, value2)
print(result1)

You are getting error Invalid operator because your if part is not getting evaluated because you are assigning true to add variable and you are comparing with a variable where you want to give input as string i.e, "add". So, question != add as question will contain string datatype whereas add will have string datatype.

Uttam
  • 621
  • 5
  • 16