0

I wanted to have some sort of thing that if the user inputs "Quit", the program breaks. I think that I could achieve that with a do while loop but I don't understand how to implement it. Please help me.

num1 = float(input("Enter First Number: "))
num2 = float(input("Enter second number: "))
op = input("Enter Operator: ")

if op == "*":
    print(num1 * num2)

elif op == "+":
    print(num1 + num2)

elif op == "-":
    print(num1 - num2)

elif op == "/":
    print(num1 / num2)

elif op == "%":
    print(num1 % num2)

else:
    print("Invalid Operator")
2

2 Answers 2

1
while True:
    try:
        #insert your "loop" here
        [.....]
        
    except ValueError:
        #restart the loop
        continue

    else:
        #exit the loop
        break
Sign up to request clarification or add additional context in comments.

Comments

0
while True:
    while True:
        num1 = input("Enter First Number: ")
        if num1.lower() == "quit":
            quit()
        try:
            num1 = int(num1)
            break
        except ValueError:
            print(f"{num1} is not an integer.")

    while True:
        num2 = input("Enter second number: ")
        if num2.lower() == "quit":
            quit()
        try:
            num2 = int(num2)
            break
        except ValueError:
            print(f"{num2} is not an integer.")

    op = input("Enter Operator: ")
    if op.lower() == "quit":
        quit()

    if op == "*":
        print(num1 * num2)
    elif op == "+":
        print(num1 + num2)
    elif op == "-":
        print(num1 - num2)
    elif op == "/":
        print(num1 / num2)
    elif op == "%":
        print(num1 % num2)
    else:
        print("Invalid Operator")

2 Comments

explanation please? I don't understand do while loops.
@BrainGym a while loop runs while a condition is met. In this case, while True: is effectively an infinite loop (while True will always be True). What I've done is have each step run until the input is valid, or until the user enters "quit." break will break the program out of the infinite loop. So this program runs each step until it receives a valid input or the user enters "quit." I recommend reading ATBSWP Chapter 2 for a more thorough explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.