0

Hello I'm trying to add two natural numbers and I wanted the program to continue and have an option to break. This is my code:

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
   print(sum, "is Even")
else:
   print(sum," is Odd")

5 Answers 5

1

You can do this using a while loop. So for example:

while True:
   play = input("Do you want to play (type no to stop)?")
   if play == 'no':
      break
   num1 = int(input("Enter first number: "))
   num2 = int(input("Enter second number:"))
   sum = num1 + num2
   if (sum % 2) == 0:
      print(sum, "is Even")
   else:
      print(sum," is Odd")
Sign up to request clarification or add additional context in comments.

Comments

1

Put all of this code in a loop and add option to continue/ break before taking input from the user.

while(True):
    option = int(input("Enter 0 to break. Else, continue")
    if option == 0:
        break
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number:"))
    sum = num1 + num2
    if (sum % 2) == 0:
       print(sum, "is Even")
    else:
       print(sum," is Odd")

Comments

0
print('entry "quit" when you want toe terminate the program')

# infinite loop
while 1:
    # input validation
    try:
        num1 = int(input("Enter first number: "))
        num2 = int(input("Enter second number:"))
    except ValueError:
        print('Please entry a number')
        print()
        # continue would restart the while loop
        continue
    if(num1 == 'quit' or num2 == 'quit'):
        # break will terminate the while loop
        break
    sum = num1 + num2
    if (sum % 2) == 0:
       print(sum, "is Even")
    else:
       print(sum," is Odd")

Comments

0

You can always nest these statements in a while loop and break on some condition.

Comments

0
def process_results():
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number:"))
    sum = num1 + num2
    if (sum % 2) == 0:
        print(sum, "is Even")
    else:
        print(sum,"is Odd")


def get_choice():
    print("Enter R to run program or Q to quit:")
    choice = input()
    return choice


def main():
    while(True):
        choice = get_choice()
        if choice == 'R' or choice == 'r':
            process_results()
        elif choice == 'Q' or choice == 'q':
            print("This program has quit")
        else:
            print("You must enter R to run program or Q to quit")
main()

Comments

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.