0

Apologies if the question to this is worded a bit poorly, but I can't seem to find help on this exercise anywhere. I am writing a basic Python script which sums two numbers together, but if both numbers inputted are the same the sum will not be calculated.

while True:
   print('Please enter a number ')
   num1 = input()
   print('Please enter a second number ')
   num2 = input()

   if num1 == num2:
       print('Bingo equal numbers!')
       continue
   elif num1 == num2:
       print('It was fun calculating for you!')
       break
   print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
   break

If both numbers are equal I want the script to loop back once more and if the numbers inputted are equal again I want the program to end. With the code I have provided the issue I am having is that when I enter two equal numbers it keeps constantly looping until I enter two different numbers.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • IMO this sounds like a variation of (or is at least very similar to) [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). – martineau Apr 14 '20 at 19:26

3 Answers3

0

You can add give input code again inside first if statement or use some other dummy variable for loop so that you can break the loop, for e.g. use while j == 0 and increase it j += 1when you are inside the first if statement

jkhadka
  • 2,443
  • 8
  • 34
  • 56
0

You would likely want to have a variable keeping track of the number of times that the numbers were matching. Then do something if that counter (keeping track of the matching) is over a certain threshold. Try something like

matches = 0
while True:
    num1 = input('Please enter a number: ')
    num2 = input('Please enter a second number: ')

    if num1 == num2 and matches < 1:
        matches += 1
        print('Bingo equal numbers!')
        continue
    elif num1 == num2:
        print('It was fun calculating for you!')
        break
    print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
    break
jfogus
  • 32
  • 3
0

continue skips the execution of everything else in the loop. I don't see it much useful in your example. If you want to print the sum then just remove it.

How continue works can be demonstrated by this sample (taken from python docs)

for num in range(2, 10):
     if num % 2 == 0:
         print("Found an even number", num)
         continue
     print("Found a number", num)

Result

Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
mybrave
  • 1,662
  • 3
  • 20
  • 37