python expected an indented block - python

i don't know why that appears when i try to run. i tried to fix but i can't. is there any errors?
import math
print(" Hello....\n This program will ask you to enter 3 numbers \n (a, b and c) that will be used in the quadratic formula to \n calculate the roots of an equation ")
a=float(input("Enter a Value for a: "))
while(a <= 0):
print(" Please enter a number that is larger than 0.") <br/>
a=float(input("Please enter a value for A: "))
b=float(input("Enter a Value for b: "))
while(b <= a): <br/>
print(" Please enter a value that is larger than A.") <br/>
b=float(input("Enter a value for B: "))
c=float(input("Enter a Value for C: "))
root1 = float(-b + math.sqrt(b * b - 4 * a * c)/(2 * a)) <br/>
root2 = float(-b - math.sqrt(b * b - 4 * a * c)/(2 * a))
print("Root 1 is " , root1)<br/>
print("Root 2 is " , root2)<br/>
input("prompt: ")

First: In Python, indenting is a must. It is a syntactically feature to have nested code indented instead of spamming the source with paranthesis'.
Second: Obviously, you copy pasted HTML code from somewhere. Get rid of <br />.

Related

How to get variable values from a txt file with a specified format?

I am writing a program that solves quadratic equations, with the variables assigned from a .txt file, with this specific format:
The text file will contain lines of comma separated text – each line contains three floating point numbers. The first number is the value for A, the second number is the value for B, and the third number is the value for C.
Now I have my code mostly written out I am just unsure how I would assign these variables from a .txt file. Here is my current code:
print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
file = input("\nPlease input text file name: ")
file = file + ".txt"
text_file = open(file, "r")
import math
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print("There are two distinct roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print("There is one real root")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
# Driver Program
#<---------------Need these variables assigned to lines from .txt file
a = 1
b = 10
c = -24
# If a is 0, then incorrect equation
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
Note: Please note at the start of my code I have asked the user to input the file name, I still need to work on this as I need to create an error message for when the file does not exist. Just ignore this as I can fix that later.
with open('file.txt') as f:
content = f.read()
for line in content.splitlines():
a, b, c = map(float, content.split(','))
Complete program:
print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
import math
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print("There are two distinct roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print("There is one real root")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
filename = input("\nPlease input text file name: ")
with open(filename + '.txt') as f:
content = f.read()
for line in content.splitlines():
a, b, c = map(float, content.split(','))
# If a is 0, then incorrect equation
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
Try this:
I had to move some of your code around, but I left inline comments to explain what I changed. I also included a check to make sure the path exists.
import math # Python convention is to put imports at the top
import os
print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print("There are two distinct roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print("There is one real root")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
file = input("\nPlease input text file name: ")
file = file + ".txt"
if os.path.exists(file): # check if file exists
with open(file, "rt") as text_file: # using a with statement is
# preferred over directly
# opening the file
for line in text_file: # iterate through lines of file
# the next line splits the `line` by "," commas,
# removes whitespace and casts each item to float
a,b,c = [float(i.strip()) for i in line.split(',')]
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
else:
# print some message
you could read the file like this:
f = open(file_name,"r")
for line in f.readlines():
a,b,c = map(float,line.split(","))
# now call your function
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
we started by opening the file then we iterate over the lines using file.readlines() then for every line we splitted the values and converted all of them to a float using map()

why i am getting "ValueError: math domain error" exception in my code?

this is my first time posting here so I'm sorry if I mess anything up or format incorrectly. In an attempt to bring a lot of the very basic stuff I've learned together in Python, I'm trying to make a quadratic equation calculator where you can type in each of your 3 values and be given the horizontal intercepts. However, while this works with some problems, others will give me this message:
"Traceback (most recent call last):
File "quadeq.py", line 18, in <module>
result1 = ((float(ac)) + (sqrt((float(ab)) - (float(aa))))) / (float(ad))
ValueError: math domain error"
I'm pretty sure this is just an error with my math, but it could be a lot of other things too. Thanks much to anyone willing to check this out, it would be much appreciated.
from math import *
print("Please enter each of your values!")
a = input("Enter a value: ")
b = input("Enter b value: ")
c = input("Enter c value: ")
d = -4
aa = float(d) * ((float(a)) * (float(c)))
ab = ((float(b))) * ((float(b)))
ac = 0 - (float(b))
ad = (2) * (float(a))
result1 = ((float(ac)) + (sqrt((float(ab)) - (float(aa))))) / (float(ad))
result2 = ((float(ac)) - (sqrt((float(ab)) - (float(aa))))) / (float(ad))
print("Your values are: " + str(result1) + " and " + str(result2))
you have some corner cases that you need to take in mind:
ZeroDivisionError : since your code includes divisions, you need to cover this.
ValueError : math.sqrt cant accept negative numbers! in such case this will raise ValueError: math domain error
you can use try except to handle these corner case.now you can do it in the operations step (no nned to check inputs with if-else like old days. this is non pythonic!) see below:
import math
print("Please enter each of your values!")
a = input("Enter a value: ")
b = input("Enter b value: ")
c = input("Enter c value: ")
d = -4
aa = float(d) * ((float(a)) * (float(c)))
ab = ((float(b))) * ((float(b)))
ac = 0 - (float(b))
ad = (2) * (float(a))
try:
result1 = ((float(ac)) + (sqrt((float(ab)) - (float(aa))))) / (float(ad))
result2 = ((float(ac)) - (sqrt((float(ab)) - (float(aa))))) / (float(ad))
print("Your values are: " + str(result1) + " and " + str(result2))
except(ZeroDivisionError, ValueError):
#do some work here, e.g tell the user something
print("....")
you have already accounted for subtraction when you substituted d = -4
change this sqrt((float(ab)) - (float(aa)))) to sqrt((float(ab)) + (float(aa))))
also, you should consider using the try-except block because the quadratic equation might have imaginary roots.
on a side note, your code contains a lot of redundant parentheses ;)

Python Print statements don't work

a = input('enter a ')
b = input('enter b ')
c = input('enter c ')
def is_right_angled(a, b, c):
a, b, c = sorted([a, b, c]) #sort inputs smallest to largest
pathag=(a * a + b * b - c * c) #< 0.1 #a ^2 + b ^2 - c ^2 should = 0 approx
if pathag<0.1: # test "pathag" to to see if close
print ("This is a right triangle")
else: # if "pathag" not close, not "right"
print ("This is NOT a right triangle")
return abs(a * a + b * b - c * c) < 0.1
There could be a couple issues specific to the print function not working (I think you might also want to revisit some of the logical assumptions driving your is_right_angled function.)
1) An input function creates a string variable. You will need to explicitly convert this to an int or float variable in order for your function to correctly work with these variables.
a = float(input('enter a '))
2) You are not actually calling the function in the above code. Be sure to call it or the code won't run. Add this to the end of your script:
is_right_angled(a, b, c)

How do I print to the stdout in python 3?

The following code is there to add given integer, double and concatenate the string to the user's input integer, double and string respectively.
The code is given below, but it gives no output. What's the error in it.
i = 4
d = 4.0
s = 'Hackerrank'
a = int(input())
b = long(input())
c = raw_input()
print(a + i)
print(b + d)
print(s+c)
Kindly point out the errors and let me know the reason for it not working too!
Consider reading https://realpython.com/learn/python-first-steps/
And to quickly check your code use https://repl.it/languages/python3
You have several errors in your original code. here is the corrected version:
i = 4
d = 4.0
s = 'Hackerrank'
a = int(input())
b = float(input())
c = input()
print(a + i)
print(b + d)
print(s+c)
A little note: You can add a prompt to your calls to input() so the user knows what to type:
a = int(input("type int "))
b = float(input("type float "))
c = input("please type something")
Finally, if you want to run it with python3 in terminal do:
python3 name_of_file.py
Hello ANIRUDH DUGGAL
First read this best website before start Python 3,
1. https://www.tutorialspoint.com/python3/
2. https://docs.python.org/3/tutorial/
3. https://learnpythonthehardway.org/python3/
Difference between python 2 and python 3,
1. http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html
2. https://www.quora.com/What-are-the-major-differences-between-Python-2-and-Python-3
Your code perfectly works on version python 2 but if you use the Python 3 so it does not work because in Python 3 is something different syntax so first read Python 3 basic fundamentals(Syntex, inbuilt function,...etc).
Using python2:
#!/usr/bin/python
# Using python 2
i = 4
d = 4.0
s = 'Hackerrank'
a = int(input("Enter the integer number: "))
b = long(input("Enter the long number: "))
c = str(raw_input("Enter the string: "))
print("Output1: %d" % (a + i))
print("Output1: %f" % (b + d))
print("Output1: %s" % (s+c))
Using python3:
#!/usr/bin/python
# Using python 3
i = 4
d = 4.0
s = 'Hackerrank'
a = int(input("Enter the integer number: "))
b = float(input("Enter the long number: "))
c = str(input("Enter the string: "))
print("Output1: %d" % (a + i))
print("Output1: %f" % (b + d))
print("Output1: %s" % (s+c))
I hope my answer is useful for you.
in python 3 it is just input() and change the long to float

Showing input prompt in python

I am using IDLE for Python on a Mac OS. I wrote the following in a .py file:
import math
def main():
print "This program finds the real solution to a quadratic"
print
a, b, c = input("Please enter the coefficients (a, b, c): ")
discRoot = math.sqrt(b * b-4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "The solutions are: ", root1, root2
main()
IDLE now permanently displays:
This program finds the real solution to a quadratic
Please enter the coefficients (a, b, c):
When I enter 3 numbers (ex: 1,2,3) IDLE does nothing. When I hit enter IDLE crashes (no crash report).
I quit and restarted but IDLE is now permanemtly displaying the above and won't respond to other files.
There is no real solution to the equation X^2 + 2x + 3 = 0. You will get a ValueError when trying to take the square root of b * b-4 * a * c, which is negative. You should handle this error case somehow. For example, a try/except:
import math
def main():
print "This program finds the real solution to a quadratic"
print
a, b, c = input("Please enter the coefficients (a, b, c): ")
try:
discRoot = math.sqrt(b * b-4 * a * c)
except ValueError:
print "there is no real solution."
return
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "The solutions are: ", root1, root2
main()
Or you can detect that the discriminant is negative ahead of time:
import math
def main():
print "This program finds the real solution to a quadratic"
print
a, b, c = input("Please enter the coefficients (a, b, c): ")
discriminant = b * b-4 * a * c
if discriminant < 0:
print "there is no real solution."
return
discRoot = math.sqrt(discriminant)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "The solutions are: ", root1, root2
main()
Result:
This program finds the real solution to a quadratic
Please enter the coefficients (a, b, c): 1,2,3
there is no real solution.
The math module does not support complex numbers. If you replace import math with import cmath and math.sqrt with cmath.sqrt, your script should work like a charm.
EDIT: I just read "This program finds the real solution to a quadratic". Taking into consideration that you only want real roots, you should check for negative discriminants as the Kevin has pointed out.
The reason I see for your program failing is this:
a, b, c = 1, 2, 3
num = b * b - 4 * a * c
print num
It comes out as -8.
You normally can't have a negative number within a square root.
Like what the person above me says, import cmath should work.
http://mail.python.org/pipermail/tutor/2005-July/039461.html
import cmath
a, b, c = 1, 2, 3
num = cmath.sqrt(b * b - 4 * a * c)
print num
= 2.82842712475j

Categories

Resources