Solves monomials, might try to make one that solves polynomials in the future.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def deri():
coeff=eval(input("Enter the coefficient assuming there is one: "))
exp=eval(input("Enter the exponent of the coefficient: "))
if coeff<0 and exp<0:
print("The derivative is:", abs(coeff*exp),"/(x^", abs((exp-1)),")")
elif exp>1:
print("The derivative is:", coeff*exp,"x^", exp-1)
elif exp==1:
print("The derivative is:",coeff)
elif exp==0:
print("The derivative is: 0")
elif coeff<0:
print("The derivative is:", coeff*exp,"x^", exp-1)
elif coeff==0:
print("The derivative is: 0")
elif exp<0:
print("The derivative is:",coeff*exp,"/(x^",abs(exp-1),")")
deri()
|
A coefficient is the number next to the "x" for 3x^2 the coefficient would be 3 and the exponent would be 2.
I used wolframalpha.com to help me with debugging. I have not tested it with fractions, but feel free to do so.
Remember to check if the derivative equals to whatever you get, the notation might be different, but it gets the same value.
You're using
eval()
on untrusted input. That's a recipe for disaster, as it opens a huge security hole in your program. You might not care so long as it's only you using it, but someday you'll extend the program to accept input from the Internet, and bang your computer is under the complete control of anyone with access to your website. So it is best to learn good security habits now.The problem is these two lines:
Let's just look at the first line, the same applies to the second. What you intend is for the user to enter a number. They enter "1.23" (without the quotes) and you get coeff = 1.23. But if they type "abc", Python tries to eval "abc" as code. If you have a variable "abc", then they get coeff = abc.
But it gets worse: eval will run any Python code the user types. A clever attacker can use that to run code on your system. Suppose they wanted to delete files off your system, all they need do is enter the next line at the prompt don't do this, IT WILL DELETE FILES
I have made two deliberate errors in the above code, so that even if you ignore me and enter it, it won't delete anything, just raise an exception. But they're simple errors to fix and should be obvious. Try this instead for a less dangerous working example:
So that's why you shouldn't use eval() unless you're an expert. Instead, you should take the string returned by input, and turn it into a number using float or int.