''' Purpose: continue introduction to functions ''' def is_factor( x, y ) : ''' Parameters x and y are integers. The function returns whether y is a factor of x. ''' # compute remainder of x divided by y rem = x % y # check it out if ( rem == 0 ) : # check whether remainder is 0 result = True # if it is, return value is True else: result = False # if it is not, return value is False # return determination return result def is_prime( x ) : ''' Parameter x is am integer. The function returns whether x is prime; i.e., its only factors are 1 and itself. ''' # We want to check all possible factors from 2 to n - 1 because # for a number to be prime, its only factors are 1 and n! for i in range( 2, x ): # range(2,x) will go from 2 to x - 1! if ( is_factor(x, i) == True ): # check if i is a factor of x # is factor(x,i) is a function that returns True/False so we can # either do if (is_factor(x,i)) or if (is_factor(x,i) == True) return False # The minute we find another factor besides 1 and n, # we know x is not prime! Just return False right here! else: continue # go onto the next value of the for loop return True # This says we checked all the numbers in the for loop and # if we never returned False (none were a factor), then we know # that x is prime! - indented into the function but outside the for loop # else: (indented into for loop) # return True # We can't return True right off the bat because # once you hit a return statement, the function is done! # it doesn't check the rest of the numbers in the for loop! # It only checked 2 as a factor and either returned True/False def are_relative_primes( x, y ) : ''' Parameters x and y are integers. The function returns whether x and y are relatively prime; i.e., whether y is not a factor of x and vice-versa. ''' # You can use functions within other functions! x_is_factor_y = is_factor( y , x ) # tells you if x is a factor of y y_is_factor_x = is_factor( x , y ) # tells you if y is a factor of x if ( x_is_factor_y == True ): result = False elif ( y_is_factor_x == True ): result = False else: # x is not a factor of y and y is not a factor of X (both are False) result = True return result if __name__ == "__main__": import primal a1, b1 = 6, 2 a2, b2 = 7, 3 a3, b3 = 4, 5 f1 = primal.is_factor( a1, b1 ) f2 = primal.is_factor( a2, b2 ) f3 = primal.is_factor( a3, b3 ) print( 'is_factor(', a1, ',' , b1, ') = ', f1 ) print( 'is_factor(', a2, ',' , b2, ') = ', f2 ) print( 'is_factor(', a3, ',' , b3, ') = ', f3 )