简体   繁体   中英

How to code for a Greatest Common Denominator function that only takes positive integers? (Python)

Im trying to write a function that finds the greatest common divisor of two positive integers. I've gotten the math part right, only I'm having trouble getting the function to reject negative values. I need to have the function produce an error when a non positive integer is entered.

def divisor(x,y):


if (y==0) :
    return x
  else:
    return divisor(y,x%y)
  if (x or y) <0:
    raise ValueError("This function only takes positive integers!")

I dont get an error and my function still returns the GCD of two negative integers. I'm sure my code is off as I'm very new to this

Can you try this:

if(x < 0 or y < 0):
    raise ValueError("etc...")

Also what Barmar said, put the if statement first.

You can't combine multiple variables like that in a conditional expression. You need to compare each variable separately.

Also, you need to do that check before the other if statement. Otherwise, the function will return before you check for negative numbers.

def divisor(x,y):
    if x < 0 or y < 0:
        raise ValueError("This function only takes positive integers!")
    if (y==0):
        return x
    else:
        return divisor(y,x%y)

When you write (x or y) < 0 , it calculates the value of x or y , then compares that to 0 . x or y is the first truthy value of the two variables, and any non-zero value is truthy. So if x is not zero, then this is equivalent to x < 0 , and if x is zero it's equivalent to y < 0 . There's no automatic distribution of < over or .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM