''' Purpose: continue introduction to functions Name: Email id: Who checked your code: Whose code did you check: ''' def is_factor( x, y ) : ''' Parameters x and y are integers. The function returns whether y is a factor of x. ''' # You can use functions within other functions. # If you defined is_factor() you can use it in the function definition # of is_prime() # 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 ( y is a factor of x) else: result = False # if it is not, return value is False # y is not a factor of x # return determination return result # Parameter and Argument is different! # Parameter is in the function definition. # def functionname( parameters ): # Parameters are going to be replaced by arguments. # Arguments are in the function call. # x = functionname( arguments ) # Arguments are the explicit values that are passed in to start up the function so it can run. # SO PARAMETER IS IN FUNCTION DEFINITION ARGUMENT IS IN FUNCTION CALL # 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. ''' for f in range( 2, x ): # We only want to check values 2 to x - 1 because 1 and x are already factors! check = is_factor( x, f ) # Let's go through each potential factor f (number from 2 to x - 1) and see if it's a factor if ( check == True ): # or if ( check ) - THIS CHECKS OTHER FACTORS TO SEE IF F IS A FACTOR OF X return False # If I find another factor then we want to return False because then it's not prime else: pass return True # We return True outside the for loop because we're done checking all factors # so we can return True (the number is prime) # If the loop finishes, none of the other factors were factors so that means # the number is prime (only had factors 1 and itself aka x)! 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. ''' if ( is_factor( x , y ) == False and is_factor( y, x ) == False): return True else: return False 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 )