Looping in Python - 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()

Related

if-else statement not running elif- or else- clauses [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 4 years ago.
I am using Python in an attempt to create an Area Calculator (similar to the one from Code Academy). Only my else statement seems to be running:
print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")
answer = input()
if answer == "Circle" or "C" or "c" or "circle":
radius = float(input("Input Radius: "))
area_c = (3.12159 * radius) * 2
print (area_c)
elif answer == "Triangle" or "T" or "t" or "triangle":
base = float(input("Input Base: "))
height = float(input("Input Height: "))
area_t = (.5 * base) * height
print (area_t)
else:
print ("error")
I edit texts using PyCharm and no syntax errors or errors of any other kind return. Regardless of what I respond into the answer input (whether they are integers or syntax) the code always displays line 8 [radius = float(input("Input Radius: "))]
I am sorry if this turns out to be an easy fix. I am just getting started with Python and have tried a variety of indentation and syntactical variations to no avail.
Use:
print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")
answer = input()
if answer.lower() in {"circle","c"}:
radius = float(input("Input Radius: "))
area_c = (3.12159 * radius) * 2
print (area_c)
elif answer.lower() in {"triangle","t"}:
base = float(input("Input Base: "))
height = float(input("Input Height: "))
area_t = (.5 * base) * height
print (area_t)
else:
print ("error")
The changes are the lines with or, use in instead so checks by the set
That's what's different.
Note use lower for simplifying the length
Note use set for speed, (it's faster)
You are using the == operator incorrectly. You have to use it this way:
if answer == "Circle" or answer == "C" or answer == "c" or answer == "circle":
An easier way to do this will be to using check whether your string matches any of the items in a tuple or list. So your code will need to be modified like this:
print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")
answer = input()
if answer in ("Circle", "C", "c", "circle"):
radius = float(input("Input Radius: "))
area_c = (3.12159 * radius) * 2
print (area_c)
elif answer in ("Triangle", "T", "t", "triangle"):
base = float(input("Input Base: "))
height = float(input("Input Height: "))
area_t = (.5 * base) * height
print (area_t)
else:
print ("error")
if answer == "Circle" or answer == "C" or answer == "c" or answer == "circle":

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!")

Triangle in python

I have problems with my program that I have to do... here are the instructions: Write a program named triangle.py that uses a value-returning function that takes the lengths of the sides of a triangle as arguments and returns both the area and perimeter of the triangle. Prompt the user to enter the side lengths from the keyboard in the main function and then call the second function. Display the area and perimeter accurate to one decimal place. NOTE: Use Heron's Formula to find the area. I did it and it worked but the thing is he wants us to use one function that returns both area and perimeter.. so I re-did the program using one function but I keep getting an error saying per is not defined... I tried literally everything to fix it, looked online and nothing works. :( here is my code:
def main():
a = float(input('Enter the length of the first side: '))
b = float(input('Enter the length of the second side: '))
c = float(input('Enter the length of the third side: '))
print('The perimeter of the triangle is: ', format(per(a, b, c),',.1f'))
print('The area of the triangle is: ', format(area(a, b, c),',.1f'))
def area_per(a, b, c):
per = a + b + c
s = per / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
return area_per
main()
The problem here is that the "per" variable you defined is local to the area_per function.
You'd need to create another function per that stands outside of that if you want the right scope.
def main():
a = float(input('Enter the length of the first side: '))
b = float(input('Enter the length of the second side: '))
c = float(input('Enter the length of the third side: '))
print('The perimeter of the triangle is: ', format(per(a, b, c),',.1f'))
print('The area of the triangle is: ', format(area_per(a, b, c),',.1f'))
def area_per(a, b, c):
p = per(a,b,c)
s = p / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
return area
def per(a,b,c):
return a+b+c
main()

Python Help. Code is going past if/Else Statement

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!!!

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()

Categories

Resources