-3

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
  • `question == add` is clearly a typo, and I assume `add = True` was added in to suppress an error message instead of actually thinking about the problem. The problem here that might actually involve conceptual difficulty is the now-linked duplicate. But this question shouldn't have been allowed to stay open in the first place, and certainly shouldn't have been answered. – Karl Knechtel Aug 15 '22 at 04:26

1 Answers1

2

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
  • 175,061
  • 34
  • 275
  • 318
AceKiron
  • 56
  • 11