Python Forum

Full Version: Not sure why this works...
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm working on a project for class and I was not sure why this didn't work:

Input:
0
9
def hcf(a, b):
  
  for i in range(a):
    if a > b:
	    a -= b
    elif b > a:
    	b -= a
  print(a)

hcf(int(input()), int(input()))
Output:
0 (Answer should be 9)

I then started adding random things to my code and discovered that the following code worked:
Input:
0
9
def hcf(a, b):
  
  for i in range(a):
    if a > b:
	    a -= b
    elif b > a:
    	b -= a
  print(a or b)

hcf(int(input()), int(input()))
Output:
9

I know this is an odd question but I would like a better understanding of how that changed the code, making it work.
write your code like:
def hcf(a, b):
    print('at start: a: {}, b: {}'.format(a,b ))
    print('\nfor i in range: {}'.format(a))
    for i in range(a):
        if a > b:
            print('a > b')
            a -= b
            print('a -= b: {}'.format(a))
        elif b > a:
            print('b > a')
            b -= a
            print('b -= a: {}'.format(a))
    print('a or b: {}'.format(a or b))


hcf(int(input()), int(input()))
Get output like:
Output:
2 3 at start: a: 2, b: 3 for i in range: 2 b > a b -= a: 2 a > b a -= b: 1 a or b: 1