1

I am making a python calculator program that asks a user after completing one calculation whether they want to continue or not. If the user says Yes the loop should run or else it should stop. I am Facing a problem where a user says yes or no the loop still executes anyhow. Why is it so ???

print("This is a Calculator In Python. !!!")
print("I Can Do Addition, Subtraction, Multiplication and Division.!!")

def addition():
    print("Please Don't Enter Float Values Here.")
    num1 = int(input("Enter First Number.!!"))
    num2 = int(input("Enter Second Number. !!"))
    result = num1 + num2
    return result
def subtraction():
    print("Please Don't Enter Float Values Here.")
    num1 = int(input("Enter First Number.!!"))
    num2 = int(input("Enter Second Number.!!"))
    result = num1 - num2
    return result
def multiplication():
    print("You Can Enter Float Values Here.")
    num1 = float(input("Enter First Number.!!"))
    num2 = float(input("Enter Second Number.!!"))
    result = num1 * num2
    return result
def division():
    print("You Can Enter Float Values Here.")
    num1 = float(input("Enter First Number.!!"))
    num2 = float(input("Enter Second Number.!!"))
    result = num1 / num2
    return result


print("""1. a for Addition
2. s for subtraction
3. m for multiplication
4. d for Division""")
select = "Yes"

while select:
  choice = str(input("You Choose The Operation."))
  if choice == "a":
    print(addition())
  elif choice == "s":
    print(subtraction())
  elif choice == "m":
    print(multiplication())
  elif choice == "d":
    print(division())
  else:
    print("Invalid Input")
  select=str(input('Continue Yes or No '))
print("Thank you..!")

1 Answers1

2

You've defined your loop as while select, which means as long as select is considered to not be None, it will continue looping

In your loop, you assign the user input to select, which means as long as the user inputs anything, it will always keep looping.

To fix this, you should have the while loop check if select is "yes":

while select.lower().strip() == "yes":
    choice = input("You Choose The Operation. ")
    if choice == "a":
        print(addition())
    elif choice == "s":
        print(subtraction())
    elif choice == "m":
        print(multiplication())
    elif choice == "d":
        print(division())
    else:
        print("Invalid Input")
    select = input("Continue Yes or No ")
print("Thank you..!")

Also, input() returns a string so you don't need to wrap it in a str() call.

JoshuaMK
  • 104
  • 1
  • 6
  • 1
    When converting to a boolean (which is done in ```while select```), ```0, (), [], None, {}``` all evaluate to False, not only ```None``` as you have written. See this [answer](https://stackoverflow.com/a/100764/8359552). – StefanKssmr Jan 29 '21 at 10:14
  • 1
    I myself am aware of this, simply worded it poorly. Thanks for providing such a helpful link :) – JoshuaMK Jan 29 '21 at 10:26