0

This code is from a python lesson. I'm not interested in breaking out of loops. I need to understand what this code is actually doing - since I can't make it run. The correct code is irrelevant. I don't understand this code. (The lesson results don't make sense.)

def find_512():
    for x in range(100):
        for y in range(100):
            if x * y == 512:
                 break   # does not do what we want!
    return f"{x} * {y} == 512"
  • are you looking for something like [breaking out of multiple for loops at once](https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python)? – FObersteiner Jul 24 '19 at 16:07
  • First lesson with Break. According to lesson, it returns "99 * 99 =512" I don't understand how the code generates that. – Lynn L Crawford Jul 24 '19 at 16:13
  • Possible duplicate of [How to break out of multiple loops in Python?](https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python) – MisterMiyagi Jul 24 '19 at 16:17
  • 1
    @LynnLCrawford, `break` causes the program to exit the loop within which you call it. In the lesson example, `break` is called in the inner `for loop` - that would leave the outer `for loop` running and calling the inner one again. Actually, it is not needed at all since you exit any loop within a function if you `return` something, see @UmeshChaudhary 's answer. – FObersteiner Jul 24 '19 at 16:19
  • 1
    What part of the code are you having trouble to understand? The code should return ``'8 * 64 == 512'``, by the way. – MisterMiyagi Jul 24 '19 at 16:20
  • Thank you @MrFuppes – Lynn L Crawford Jul 24 '19 at 16:32

1 Answers1

1

If you are just looking for first values of x and y then try this

def find_512():
  for x in range(100):
    for y in range(100):
      if x * y == 512:
        print('breaking')
        return f"{x} * {y} == 512"

If you want to break out from all the loops then this is the best solution.

Umesh Chaudhary
  • 391
  • 1
  • 6