Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop while loop if user inputs correct operator

Tags:

python

I just started learning Python yesterday and one of the programs I'm trying to write is a calculator. This segment of code is where I'm having problems. The while loop is supposed to stop when the user inputs any of the math operators but it still asks for input even when the user enters one the correct characters.

What do I need to do to fix this.

    op = None                                 
    while (op != "-" or op != "+" or op != "*" or op != "/"):
        op = input("Enter operator (-, +, *, /):  ")
    print(op)
like image 861
asdfghjkl Avatar asked Jul 19 '26 20:07

asdfghjkl


1 Answers

  op = None                                 
while op not in ["-","+","*","/"]:
    op = input("Enter operator (-, +, *, /):  ")
print(op)

or

op = None                                 
while (op != "-" and op != "+" and op != "*" and op != "/"):
    op = input("Enter operator (-, +, *, /):  ")
print(op)

your code isnt working because while "op" might be equal to one of your options, its not equal to all the others, and therefore continues the loop

like image 62
Christian Trujillo Avatar answered Jul 22 '26 11:07

Christian Trujillo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!