I'm trying to get the userinput for a,b,c using a function and it doesn't seems to work
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
print("The equation root of the numbers is" quadratic)
equationroots()
You have not used the proper intents, This is what your code supposed to be.
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
quadratic = equationroots()
print("The equation root of the numbers is", quadratic)
Indentation is very important in Python to separate block statements. It appears your indentation is off, leading to some lines not being executed when you intend.
For example, the variables my, sqrt_val, and quadratic are only calculated if the except label is reached. This means they are only attempted to be calculated if there is an input error, which wouldn't work anyways.
It's possible you also pasted in your code and the formatting was adjusted, and that isn't the issue. If that is the case, please edit the question to reflect the formatting and indentation you are using.
You need to fix your indentations from the except portion. Indentations are very important in python
fix this portion:
except ValueError:
print("Not a number!")
my = (b*b)-(4*a*c)
sqrt_val = math.sqrt(abs(my))
quadratic = ((-b)+sqrt_val)/(2*a)
return quadratic
then call your function first then use that to print your statement. Like,
quadratic = equationroots()
print(f"The equation root of the numbers is {quadratic}")
Related
Here is the question my teacher gave us:
Write a program to find the sum of the following series (accept values of x and n from user). Use functions of the math library like math.pow and math.factorial:
1 + x/1! + x2/2! + ……….xn/n!
This is the code I've come up with. I calculated it on paper with simple numbers and there's clearly some logic errors because I can't get a correct answer. I think I've been looking at it for too long to really grasp the issue, so I could use some help.
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
for i in range (n):
power = math.pow(x,i)
ans = 1 + (power / math.factorial(i))
print(ans)
Note: This is an entry level class, so if there's an easier way to do this with a specific function or something I can't really use it because I haven't been taught it yet, although appreciate any input!
I would not recommend using those functions. There are better ways to do it that are within the grasp of entry level programmers.
Here's what I recommend you try:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
sum = 1
term = 1.0
for i in range (1,n+1):
term *= x/i
sum += term
print(sum)
You don't need those functions. They're inefficient for this case.
I believe the following will work for you:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 1
for i in range (1,n+1):
power = math.pow(x,i)
ans += (power / math.factorial(i))
print(ans)
We start the ans variable at 1 and we add the new term to ans through each iteration of the loop. Note that x+=n is the same as x=x+n for integers.
I also changed the range that your loop is going through, since you start at 1 and go up to n, rather than starting at 0 and going to n-1.
Output:
Input x: 2
Input n: 5
7.266666666666667
For people familiar with the mathematical constant e:
Input x: 1
Input n: 15
2.718281828458995
Your ans only includes (the 1 and) the latest term. You should instead Initialize it before the loop and then add all the terms to it. The first term 1 doesn't deserve ugly special treatment, so I compute it like all the others instead:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 0
for i in range(n + 1):
ans += math.pow(x, i) / math.factorial(i)
print(ans)
And a preview how you'll likely soon be taught/allowed to write it:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
print(sum(math.pow(x, i) / math.factorial(i)
for i in range(n + 1)))
I am experimenting with classes for the first time, and I wanted to create a program that asks the user for an input a,b, and c, and then solves for x for the equation forms stated in the print statements. However, I am having issues with the class, giving me an error that I am not using the variables in the class, missing the 5 positional arguments. Any help would be amazing, thanks so much.
class EquationSolver:
def MonomialSolver(self,a,b,c,x):
a = input("Enter Input for a:")
b = input("Enter Input for b:")
c = input("Enter input for c:")
x = (c+b)/a
print("For the equation in the format ax-b=c, with your values chosen x must equal", x)
def PolynomialSolver(self,a,b,c,x):
a = input("Enter Input for a:")
b = input("Enter Input for b:")
c = input("Enter input for c:")
x = (c^2 + b) / a
print("For the equation in the format sqrt(ax+b) = c, with your values chosen x must equal", x)
MonomialSolver()
PolynomialSolver()
The problem I see is the inputs for the functions. You do not need the self parameter or any other parameter. The functions should run outside the loop. The edited version should loop something like this:
class EquationSolver:
def MonomialSolver():
# Uses float() to turn input to a number
a = float(input("Enter Input for a:"))
b = float(input("Enter Input for b:"))
c = float(input("Enter input for c:"))
x = (c+b)/a
print("For the equation in the format ax-b=c, with your values chosen x must equal", x)
def PolynomialSolver():
a = float(input("Enter Input for a:"))
b = float(input("Enter Input for b:"))
c = float(input("Enter input for c:"))
x = (c^2 + b) / a
print("For the equation in the format sqrt(ax+b) = c, with your values chosen x must equal", x)
EquationSolver.MonomialSolver()
EquationSolver.PolynomialSolver()
I'm new to python and attempting to write a linear equation using Cramer's Rule. I've entered the formula and have code prompting user to enter a,b,c,d,e and f but my code is getting a syntax error. I'd like to fix the code and also have a system for researching and correcting future errors.
a,b,c,d,e,f = float(input("Enter amount: ")
a*x + by = e
cx + dy = f
x = ed-bf/ad-bc
y=af-ed/ad-bc
if (ad - bc == 0)print("The equation has no solution")
else print ("x=" x, "y=" y,)
Basically, your code was one giant syntax error. Please read some basic tutorial, as was suggested in the comments. Hopefully this will help in the learning process (I didn't go through the actual math formulas):
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
d = float(input("Enter d: "))
e = float(input("Enter e: "))
f = float(input("Enter f: "))
##a*x + by = e
##cx + dy = f
if (a*d - b*c == 0):
print("The equation has no solution")
else:
x = (e*d-b*f)/(a*d-b*c)
y = (a*f-e*d)/(a*d-b*c)
print ("x=%s" % x, "y=%s" % y)
You have to put * between the numbers you want to multiply. You had one parenthesis missing from your input statement. The equations themselves are commented out, because otherwise Python takes them as a code (incorrectly written one). You have to enclose the denominator in parentheses because math. You have to end the if, else, elif, for, while and such with :. Indentation is VERY important in Python.
So say I have the lower value and an upper value of an integral that's from the user input. I ask for the lower limit first then I check for its validity. Then in order to compare the value of my upper limit with my lower I made a nested function, so that I can also ask for user input of the upper limit, checks its validity and making sure that my upper limit is bigger than my lower(cuz u know integration), shown with the code below.
def LowLimCheck():
while True:
try:
a = float(input("Please enter the lower limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
print("You have chosen the lower limit: ", a)
def UppLimCheck():
b = -1
while b <= a:
while True:
try:
b = float(input("Please enter the upper limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
if b <= a:
print("The upper limit must be bigger than the lower limit!")
print("You have chosen the upper limit: ", b)
return b
UppLimCheck()
return a
Now this is all well and fine until I actually need to use the values a and b because I need to put those values into an integral that I've set up. It's basically a general integral made by the Simpson's rule, that is trivial to get into right now. So I defined the function as:
def simpsonsRule(func, a, b, N):
<insert code here>
<insert code here>
return d
OK so my function basically lets user insert any arbitrary function, the upper limit(a), the lower limit(b) and N(number of strips in Simpson's rule) and it spits out d which is the evaluation of the integral of the arbitrary function above by Simpson's Rule. My problem now is that when I'm trying to print the answer, I can take the variable a out and put in into the integral but I can't take the variable b out because it's in a function! For example if I now print the integrated value(say in this case of sin(x) and N = 20)
print(simpsonsRule(lambda x:np.sin(x), a, b, 20)
So I know that a and b values are local within their own functions. Now for the value of a I could easily just do this to get the value a
k = 0 #initialising the variable
k = LowLimCheck()
print(simpsonsRule(lambda x:np.sin(x), k, b, 20)
Because since k invokes LowLimCheck() which returns the value for a which I can put into my function. But how can I get my value of b which is nested within the first function? I want to use b basically. Is there a way round this?
Apologies for the lengthy question and thanks in advance!
You can return a tuple from LowLimCheck():
def LowLimCheck():
...
b = UppLimCheck()
return (a,b)
then unpack them when calling LowLimCheck()
a, b = LowLimCheck()
UPDATE:
In the most direct answer to your question, LowLimCheck() becomes:
def LowLimCheck():
while True:
try:
a = float(input("Please enter the lower limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
print("You have chosen the lower limit: ", a)
def UppLimCheck():
b = -1
while b <= a:
while True:
try:
b = float(input("Please enter the upper limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
if b <= a:
print("The upper limit must be bigger than the lower limit!")
print("You have chosen the upper limit: ", b)
return b
b = UppLimCheck() # Storing the b
return (a,b) # Passing b out with a in a tuple
then call
a, b = LowLimCheck()
finally,
print(simpsonsRule(lambda x:np.sin(x), a, b, 20)
ALTERNATIVE SOLUTION (more substantial changes, but better code structure - as described in the original comments; flatter, more readable, fewer scope considerations):
def LowLimCheck():
while True:
try:
a = float(input("Please enter the lower limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
print("You have chosen the lower limit: ", a)
return a
def UppLimCheck(a):
b = -1
while b <= a:
while True:
try:
b = float(input("Please enter the upper limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
if b <= a:
print("The upper limit must be bigger than the lower limit!")
print("You have chosen the upper limit: ", b)
return b
then:
lowLim = LowLimCheck()
upLim = UppLimCheck(lowLim) # pass in lowLim as an argument
print(simpsonsRule(lambda x:np.sin(x), lowLim, upLim, 20)
Figured out the errors except for this last one, Im now getting this error message, and can't figure out why, I'm using the exact formulas for x1 and x2 that my teacher gave us to use and i'm not able to figure the error out.
# Quadratic Formula
# Import the math library to use sqrt() function to find the square root
import math
print("This equation solves for x in the binomial equation: ax^2 + bx + c = 0")
# Get the equation's coefficients and constant from the user
a = 0
while a == 0:
try:
a = float(input("Enter the first coefficeint, or a, value: "))
if a == 0:
raise ValueError
except ValueError:
print("The value you entered is invalid. Zero is not allowed")
else:
break
while (True):
try:
b = float(input("Enter the Second coefficeint, or b, value: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
while (True):
try:
c = float(input("Enter the last coefficeint, or c, value: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
d = (b**2) - (4*a*c)
x1 = ((-b) + math.sqrt(b**2 - 4*a*c)) / (2*a)
x2 = ((-b) - math.sqrt(b**2 - 4*a*c)) / (2*a)
print("X is: ", x1, " or ", x2)
do_calculation = True
while(do_calculation):
another_calculation = input("Do you want to perform another calculation? (y/n):")
if(another_calculation !="y"):
This equation solves for x in the binomial equation: ax^2 + bx + c = 0
Enter the first coefficeint, or a, value: 2
Enter the Second coefficeint, or b, value: 3
Enter the last coefficeint, or c, value: 4
Traceback (most recent call last):
File "/Users/cadenhastie/Downloads/Jtwyp6QuadraticEqnCalc/improvedquadraticeqncalc.py", line 34, in
x1 = ((-b) + math.sqrt(b**2 - 4*a*c)) / (2*a)
ValueError: math domain error
You have try statements with no corresponding except statement. You should generally avoid while True:. The indentation in your code has many issues
To get one value from the user with error handling, you could do something like the code below. You would then repeat this for each coefficient you want the user to enter. You probably want to wrap this in a function at some point so you are not writing duplicate code.
a = 0
while a == 0:
try:
a = float(input("Enter the first coefficeint, or a, value: "))
if a == 0:
raise ValueError
except ValueError:
print("The value you entered is invalid. Zero is not allowed")