Python Help. Code is going past if/Else Statement - python

The assignment is to write a code that can do triangles (find the perimeter, area, if it is an equilateral, right, etc.)
I believe my code is on target, but it doesn't render an error like it should when the numbers don't form a triangle. Any help would be greatly appreciated.
import math
A = int (input ("Type in your first integer that you would like to test:"))
print ("Your first integer to be tested is:", A)
B = int (input ("Type in your second integer that you would like to test:"))
print ("Your second integer to be tested is:", B)
C = int (input ("Type in your third integer that you would like to test:"))
print ("Your third integer to be tested is:", C)
if (A > B):
largest = A
else:
largest = B
if (C > largest):
largest = C
print ("The largest number is:", largest)
if A<=0 or B<=0 or C<=0:
print("The numbers don't form a triangle")
else:
print("The Triangle's Perimeter is:")
print(int(A+B+C))
print("The semiperimeter is:")
print(int((A+B+C)/2))
print("The Area of the triangle is:")
print (int (math.sqrt((A+B+C)/2)*(((A+B+C)/2)-A)*(((A+B+C)/2)-B)*(((A+B+C)/2)-C)))
if int(A != B and A != C and B != C):
print("The triangle is a scalene")
else:
print ("The triangle is not a scalene")
if int(A == B and B == A or A == C and C == A or C == B and B == C):
print ("The triangle is an isosceles")
else:
print ("The triangle is not an isosceles")
if int(A == B == C):
print("The triangle is an equilateral")
else:
print("The triangle is not an equilateral")
if int(C*C == A*A + B*B):
print("The triangle is a right triangle")
else:
print("The triangle is not a right triangle")

Try this code:
import math
def chkRectr(x1,x2,x3):
if (x1**2==x2**2+x3**2)or(x2**2==x1**2+x3**2)or(x3**2==x2**2+x1**2):
return True
else:
return False
def fHigh(aa,bb,cc):
d=math.sqrt(3)/2
if (aa==bb):
return math.sqrt(aa**2-(cc/2)**2)
elif (aa==cc):
return math.sqrt(aa**2-(bb/2)**2)
elif (bb==cc):
return math.sqrt(bb**2-(aa/2)**2)
def trikind():
if (a==b)or(b==c)or(a==c):
if a==b==c:
print("And it's kind: Equilateral triangle")
else:
if chkRectr(a,b,c)==True:
print("And it's kind: Isosceles rectanglar triangle")
else:
print("And it's kind: Isosceles triangle")
print("And its height is "+str(fHigh(a,b,c)))
elif chkRectr(a,b,c)==True:
print("And it's kind: Rectanglar triangle")
print("In this program I will tell you about existence of a triangle and kind of it.")
a,b,c=[float(x) for x in input("Enter three sides lenth(Split with ','): ").split(",")]
if a+b>c:
if b+c>a:
if c+a>b:
print("\nIt's a triangle!\n")
trikind()
else:
print("\nSorry but It's not a triangle!!!! :((")
It's different from what you mean but if you notice it's good at understanding a triangle!!!

Related

Input triangle sides's length and output triangle type. Doesn't work

so, this is my code and python doesn't seem to run the lines in bold. Basically, it's a code where the user inputs the three lengths of the three triangle sides and it outputs the type of the triangle (equilateral, isosceles, scalene( that isn't working. Help me please) or right).
x= input (" Length of side 1 = ")
y= input ("Length of side 2 = ")
z= input ("Length of side 3 = ")
x= float (x)
y= float (y)
z= float (z)
flag=0
if x==y==z:
print ("This is an equilateral triangle")
flag=1
if x>y and x>z and (x**2) == ((z**2) + (y**2)):
print ("This is a right triangle")
flag=1
if z>y and z>x and (z**2) ==((x**2) + (y**2)):
print ("This is a right triangle")
flag=1
if y>z and y>x and (y**2) == ((z**2) + (x**2)):
print ("This is a right triangle")
flag=1
**if x!=z!=y and flag==0:
print("This triangle is scalene")**
if x==z and x!= y:
print ("This triangle is isosceles")
if x==y and x!= z:
print ("This triangle is isosceles")
if z==y and z!= x:
print ("This triangle is isosceles")
Some minor improvements to help you learn:
def identify_triangle(x, y, z):
def tri_print(tri_type):
print("This is an {} triangle".format(tri_type))
if all([x==y, x==z]):
triangle_type = "equilateral"
elif any([
all([x>y, x>z, (x**2)==((z**2)+(y**2))]),
all([z>y, z>x, (z**2)==((x**2)+(y**2))]),
all([y>z, y>x, (y**2)==((z**2)+(x**2))]),
]):
triangle_type = "right"
elif all([x!=z, z!=y, x!=y]):
triangle_type = "scalene"
elif any([
all([x==z, x!=y]),
all([x==y, x!=z]),
all([z==y, z!=x]),
]):
triangle_type = "isosceles"
else:
triangle_type = "Unknown"
tri_print(triangle_type)
return triangle_type
x= float(input("Length of side 1 = "))
y= float(input("Length of side 2 = "))
z= float(input("Length of side 3 = "))
print()
identify_triangle(x, y, z)

Looking for a more efficient way to write my python program

In my Trigonometry class, we were assigned to find the discriminant and conic section of an equation..
I wrote a function that calculates the discriminant, and then based on the value of the discriminant, prints the conic section...
I'm just curious if there is a better, more effective way to write this:
def disc():
a_disc = raw_input("Please enter the value of A: ")
b_disc = raw_input("Please enter the value of B: ")
c_disc = raw_input("Please enter the value of C: ")
disc = b_disc**2-4*(a_disc)*(c_disc)
print ("The discriminant is: %s") % (disc)
if disc < 0:
if a_disc != c_disc:
print ("The conic is an Ellipse!")
elif a_disc == c_disc:
print ("The conic is a Circle!")
elif disc > 0:
print ("The conic is a Hyperbola!")
elif disc == 0:
print ("The conic is a Parabola!")
else:
print ("Something went wrong...")
disc()
I don't fully understand using arguments inside of functions, but I feel like doing something like:
def disc(a,b,c):
would be the more clean approach I guess.
I would really appreciate any feedback anyone has to offer. Thanks in advance!
Yeah you could move disc into a function that just calculates the value, and then have all of the input and output logic as separate code. Some of your if statements are redundant too. Here's a slightly simpler version:
def disc(a, b, c):
return b ** 2 - 4 * a * c
a = raw_input("Please enter the value of A: ")
b = raw_input("Please enter the value of B: ")
c = raw_input("Please enter the value of C: ")
val = disc(int(a), int(b), int(c))
print ("The discriminant is: %s") % (val)
if val == 0:
print ("The conic is a Parabola!")
elif val > 0:
print ("The conic is a Hyperbola!")
elif a != c:
print ("The conic is an Ellipse!")
else:
print ("The conic is a Circle!")

Looping in Python

I'm trying to figure a way to loop this code so that it restarts once all three of the calculations are complete. I have figured a way to restart the program itself, however I can't manage to restart it so that it returns back to the first calculation step. Anyone can help a brother out? Thanks in advance.
The code that I have used to restart the program:
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
answer = input("Do you want to restart this program?")
if answer.lower().strip() in "y, yes".split():
restart_program()
My program without the restart code:
import math
import sys
import os
print ("This program will calculate the area, height and perimeter of the Triangles: Scalene, Isosceles, Equilateral and a Right Angled Triangle.")
# calculate the perimeter
print ("Please enter each side for the perimeter of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
perimeter = (a + b + c)
print ("The perimeter for this triangle is: " ,perimeter)
# calculate the area
print ("Please enter each side for the area of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
s = (a + b + c) / 2
sp = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 #area = math.sqrt(sp*(sp - a)*(sp - b)*(sp - c))#
print ("The area for this triangle is %0.2f: " %area)
# calculate the height
height = area / 2
print ("The height of this triangle is: ", height)
You could put everything in a while loop which could repeat forever or until a user types a certain phrase.
import math
import sys
import os
print ("This program will calculate the area, height and perimeter of the Triangles: Scalene, Isosceles, Equilateral and a Right Angled Triangle.")
while True:
# calculate the perimeter
print ("Please enter each side for the perimeter of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
perimeter = (a + b + c)
print ("The perimeter for this triangle is: " ,perimeter)
# calculate the area
print ("Please enter each side for the area of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
s = (a + b + c) / 2
sp = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 #area = math.sqrt(sp*(sp - a)*(sp - b)*(sp - c))#
print ("The area for this triangle is %0.2f: " %area)
# calculate the height
height = area / 2
print ("The height of this triangle is: ", height)
or
while answer.lower() in ("yes", "y"):
//code
answer = input("Would you like to repeat?")
You could also put it all into a function def main(): and then do some form of recursion (calling a function in itself).
Those are just a few ways. There are a ton of ways you can get what you want.
Just Have the function loop on itself. Restarting the shell isn't necessary.
import math
import sys
import os
def calc():
print ("This program will calculate the area, height and perimeter of the Triangles: Scalene, Isosceles, Equilateral and a Right Angled Triangle.")
# calculate the perimeter
print ("Please enter each side for the perimeter of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
perimeter = (a + b + c)
print ("The perimeter for this triangle is: " ,perimeter)
# calculate the area
print ("Please enter each side for the area of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
s = (a + b + c) / 2
sp = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 #area = math.sqrt(sp*(sp - a)*(sp - b)*(sp - c))#
print ("The area for this triangle is %0.2f: " %area)
# calculate the height
height = area / 2
print ("The height of this triangle is: ", height)
if __name__ == "__main__":
answer = input("Do you want to restart this program?")
if answer.lower().strip() in "y, yes".split():
calc()
else:
exit()
calc()
If the answer is yes, then the function is called and everything repeats. If the answer is not yes then the program exits.
This should do.
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
while input("Do you want to restart this program?").lower().strip() in "y, yes".split():
restart_program()

Text menu doesn't print properly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The Problem has been solved. However, my account is new, so it won't let me answer the question. It seems that changing the instances of input() with raw_input() makes it work. I honestly have no clue why, but it may have something to do with the differences between 2 and 3.
I'm supposed to make a program that can calculate area and circumference. That part hasn't been so difficult.
However, the menu isn't working. The first part of the menu works just fine, but after you make a selection, it doesn't print what it's supposed to.
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if ans == "1":
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == "2":
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == "0":
print("Thanks for hanging out with me!")
quit()
After indenting properly, change if ans == "1" to str(ans) == "1" or ans == 1 and it should be fine.
This should work:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if str(ans) == "1":
diameter = input("Enter the diameter: ")
print diameter
if float(diameter) > 0.0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
....
PS: As mentionned in the comments, it works, but it is disgusting. We should only use ans == 1 or modify input to input_raw if you use python < python 3
Your code's indentation shows the span of control of each 'if', 'for', or 'while'.
You need to further indent the instructions under each major 'if' statement so that
they only get executed when that 'if' statement is selected. Otherwise, everything
that is at the leftmost indentation gets executed every time through the loop. For example, you should have something like:
if answer == '1':
....<statements that execute under condition 1>
elif answer == '2':
....<statements that execute under condition 2>
where I have emphasized the indentation with '....'.
The second if statement is not within the brackets of the first. this is true for both 1 and 2.
if ans == "1";
diameter = float(input("enter the diameter: "))
if diameter ....
for me treating ans as integer worked. What I mean by treating ans as integer is instead of writing ans=="1" ,I wrote ans==1.it print corret cvalue. Check this code:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
print ans
if ans ==1:
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == 2:
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == 0:
print("Thanks for hanging out with me!")
quit()

python calculator program [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I wrote a simple calculator program by using functions, I don't know what exactly wrong with this code, its showing error. I did possible steps to debug this, but I couldn't.
#!/usr/bin/python
def add():
print "Enter the two numbers to Add"
A=int(raw_input("Enter A:"))
B=int(raw_input("ENter B:"))
c = A + B
def sub():
print "Enter the two numbers to Subtract"
A=int(raw_input("Enter A:"))
B=int(raw_input("Enter B:"))
c = A - B
def Mul():
print "Enter the two numbers to Multiply"
A=int(raw_input("Enter A:"))
B=int(raw_input("Enter B:"))
c = A * B
def Div():
print "Enter the two number to Divide"
A=float(raw_input("Enter A:"))
B=float(raw_input("Enter B:"))
c = A / B
print "1: ADDITION"
print "2: SUBTRACTION"
print "3: MULTIPLICATION"
print "4: DIVITION"
print "0: QUIT"
while true:
CHOICE = int(raw_input(("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
add(c):
elif CHOICE == "2":
print 'SUBTRACTING TWO NUMBERS:'
sub(c):
elif CHOICE == "3":
print 'MULTIPLYING TWO NUMBERS:'
Mul(c):
elif CHOICE == "4":
print "DIVIDEING TWO NUMBERS"
Div(c):
elif CHOICE == "0":
return 0:
else
Print "The value Enter value from 1-4"
Error:
File "cal_fun.py", line 44
if CHOICE == "1":
^
SyntaxError: invalid syntax
I've have tried to cover all of the problems with your code, of which there are numerous.
Starting with syntax errors:
# true needed a captial T
while True:
# Brackets were mismatched
CHOICE = int(raw_input("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
# Calling a function shouldn't have trailing :
add(c)
elif CHOICE == "2":
print 'SUBTRACTING TWO NUMBERS'
# Calling a function shouldn't have trailing :
sub(c)
elif CHOICE == "3":
print 'MULTIPLYING TWO NUMBERS'
# Calling a function shouldn't have trailing :
Mul(c)
elif CHOICE == "4":
print "DIVIDEING TWO NUMBERS"
# Calling a function shouldn't have trailing :
Div(c)
elif CHOICE == "0":
# can only return from a function use exit here instead
exit()
# else needs a trailing :
else:
# No capital P for print
print "The value Enter value from 1-4"
The code now has no syntax errors but still has many problems.
You pass c to your function, c is never initialized, what is c?
Your function doesn't take arguments def add(): (even though pass the mysterious c value).
Your function doesn't print or return the result it just computes.
You store CHOICE as an int are do comparisons with strings so the else case is always executed and there is no way to exit the loop (infinite looping).
Fixed code:
#!/usr/bin/python
def add():
print "Enter the two numbers to Add"
A=int(raw_input("Enter A: "))
B=int(raw_input("Enter B: "))
return A + B
def sub():
print "Enter the two numbers to Subtract"
A=int(raw_input("Enter A: "))
B=int(raw_input("Enter B: "))
return A - B
def mul():
print "Enter the two numbers to Multiply"
A=int(raw_input("Enter A: "))
B=int(raw_input("Enter B: "))
return A * B
def div():
print "Enter the two number to Divide"
A=float(raw_input("Enter A: "))
B=float(raw_input("Enter B: "))
return A / B
print "1: ADDITION"
print "2: SUBTRACTION"
print "3: MULTIPLICATION"
print "4: DIVITION"
print "0: QUIT"
while True:
CHOICE = int(raw_input("ENTER THE CORRESPONDING NUMBER FOR CALCULATION "))
if CHOICE == 1:
print 'ADDING TWO NUMBERS:'
print add()
elif CHOICE == 2:
print 'SUBTRACTING TWO NUMBERS'
print sub()
elif CHOICE == 3:
print 'MULTIPLYING TWO NUMBERS'
print mul()
elif CHOICE == 4:
print "DIVIDEING TWO NUMBERS"
print div()
elif CHOICE == 0:
exit()
else:
print "The value Enter value from 1-4"
The code is now functional.
Output:
1: ADDITION
2: SUBTRACTION
3: MULTIPLICATION
4: DIVITION
0: QUIT
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 1
ADDING TWO NUMBERS:
Enter the two numbers to Add
Enter A: 2
Enter B: 5
7
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 2
SUBTRACTING TWO NUMBERS
Enter the two numbers to Subtract
Enter A: 2
Enter B: 5
-3
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 3
MULTIPLYING TWO NUMBERS
Enter the two numbers to Multiply
Enter A: 2
Enter B: 5
10
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 4
DIVIDEING TWO NUMBERS
Enter the two number to Divide
Enter A: 2
Enter B: 5
0.4
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 0
Functional but not perfect, for instance no error handling for erroneous input.
You're missing an end parenthesis on the previous line (a common cause of mysterious syntax errors), change:
CHOICE = int(raw_input(("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
to
CHOICE = int(raw_input("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
This is not the only syntax error in the program- you end many lines with : when you shouldn't, like:
add(c):
sub(c):
Mul(c):
Div(c):
You also
have no : for an else statement (it's required)
capitalize Print when it should be print
have a return statement outside of any function
There are also errors that are not syntax errors:
misspell True as true
compare CHOICE, an int, to a string like "1" or "2"
are passing a non-existent variable c to a function that takes no arguments
You are passing a variable c to your functions add() sub() etc. but they are defined to take no arguments.
on top of the syntax errors already mentioned what I think you actually want is for each function to return values to the main programme loop, which will then display them:
def add():
A=int(raw_input("Enter A:"))
B=int(raw_input("ENter B:"))
return A + B
...
while true:
CHOICE = int(raw_input(("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
answer = add()
print answer
...
or alternatively make the programme shorter by inputting A and B in the main loop then passing those as parameters to the calculating functions:
def add():
return A + B
...
while true:
CHOICE = int(raw_input(("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
A=int(raw_input("Enter A:"))
B=int(raw_input("ENter B:"))
if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
answer = add(A, B)
print answer
...

Categories

Resources