I’m doing the Python College Algebra course and I’m trying to complete the assignment to write a python function to convert from a decimal to a fraction. I’m getting errors on collab and I’m a bit stuck on where my thinking is going wrong. I’ll post my code below along with a link to the lesson in question.
My suspicion is that I’ve got variables in the wrong place and this is messing up the algorithm up. I’d like to use f(x) to do the function (like in the example). Where am I wrong?
x = int(digits)
y = numerator/denominator
digits = input("Enter a decimal number to convert")
exponent = int(len(digits))-1
n = float(digits)
#use exponent to get numerator
numerator = int(n * 10**exponent)
denominator = exponent * 10
print(x, "\t", y)
Link to the lesson: https://www.freecodecamp.org/learn/college-algebra-with-python/learn-functions-and-graphing/functions
I am not sure whether the codes shown here are in correct indentations of the original code in your notebook, but what is seen here is the function f only have two statements, and the first statement reassigns the value of the argument provided to the function!
I think before writing codes for the function, you have to get the correct codes of doing decimal fraction conversion first, then think about what should be the argument of the function. In this case, you may put all the codes of input value and conversion into a function without argument, or if you want to write a f(x) style function, you may leave the input statement out of the function, and use the input value as the argument to the function which does the conversion.
You might want to complete the “Scientific computing with Python” course first, or at least the “Python for Everyone” part at the beginning which has a more fundamental into to Python and functions.
Here you are mixing up variables which are internal to the function (indented after def) and global variables (not indented).
You’re also never calling your function. f(5) would call your function with a value of 5 for x, for example.
Your function also would need to have a return statement (return y). The function also can’t access numerator and denominator because they are not indented and therefore outside the function.
First of all the function
f(x) doesn’t return any value. You need to modify it to return the
denominator values and the variables
denominator are not defined within the function
f(x). You need to pass these variables as arguments to the function or define them inside the function.
x in the print statement at the end is not defined or assigned any value. It seems like you want to print the
denominator values instead.
exponent = int(len(x)) - 1
n = float(x)
numerator = int(n * 10 ** exponent)
denominator = exponent * 10
return numerator, denominator
digits = input("Enter a decimal number to convert: ")
numerator, denominator = f(digits)
print(numerator, "\t", denominator)