patternpythonMinor
Solve simple derivative questions
Viewed 0 times
derivativequestionssimplesolve
Problem
Built my first script and its function is to solve simple derivative questions. How can I improve this code? This is my first time posting.
#This is Simple Derivative Solver
def derivative():
print("This program will give you the first derivative.")
input("Press ENTER to continue...")
cf=int(input("Enter the coefficient of the term..."))
exp=int(input("Enter the exponent of the term..."))
if exp==1 and cf==1:
print("The answer is", 1)
elif exp0:
print("The answer is:", exp*cf, "x^", (exp-1))
elif exp==0:
print("The answer is:", 0)
elif exp<0:
print("The answer is:", abs(exp*cf), "x^", (exp-1))
elif cf==0:
print("The answer is:", 0)
elif cf<0:
print("THe answer is:", cf*exp, "x^", (exp-1))
derivative()Solution
-
Trust the math. If
Trust the math. If
exp
-
In any case, \$(ax^n)'\$ always equals to \$anx^{n-1}\$. Mathematically speaking there are no special cases. There are special cases when it comes to printing:
-
\$n = 0\$: you (correctly) print 0
-
\$n = 1\$: you print x^0, but it is better to omit it altogether
-
\$n = 2\$: you print x^1, but it is better to print just x.
-
\$n
-
Separate concerns. The derivative shall only compute the derivative. Input shall be handled separately.
-
The call to derivative should be conditionalized:
if __name__ == `__main__`:
derivative()
This enables you to import` your code in another project.Code Snippets
if __name__ == `__main__`:
derivative()Context
StackExchange Code Review Q#162415, answer score: 8
Revisions (0)
No revisions yet.