print ("Welcome to my Area Calculator")
i=raw_input("Please enter the shape whose Area you want to calculate(square/rectangle/right angled triangle/rhombus/parallelogram): ")
my_list=["square","rectangle","triangle","right angled triangle","rhombus","parallelogram"]
if i in my_list:
if i=="square":
s=float(input("What is the side of the square: "))
print "Area of the square is : ", s**2
elif i=="rectangle":
l=float(input("What is the length of the rectangle: "))
b=float(input("What is the breadth of the rectangle: "))
print "Area of the rectangle is : ", l*b
elif i=="right angled triangle":
base1=float(input("What is the base of the triangle: "))
height1=float(input("What is the height of the triangle: "))
print "Area of the triangle is : ", 0.5*base1*height1
elif i=="rhombus":
d1=float(input("What is the length of the 1st diagnol of the rhombus: "))
d2=float(input("What is the length of the 2nd diagnol of the rhombus: "))
print "Area of the rhombus is : ", 0.5*d1*d2
elif i=="parallelogram":
base=float(input("What is the length of 1 side of the parallelogram: "))
height=float(input("What is the length of the other side: "))
print "Area of the parallelogram is : ", height*base
print "Thank you so much for using my area calculator"
Make your entire program became a function, then execute it inside while loop.
while(option != 'yes'):
Program()
userInput()
Ask for the user if he wants to continue, put it in a boolean variable, put all your code in a while loop with this boolean as a condition
Don't forget to init this boolean to true
Related
I'm supposed to find a code that asks the user for the base, height, and side of a triangle and then tells the user "This (type) triangle has an area of (area)" and then keeps asking the user for more numbers until they decide to quit. The code I have so far is...
again = "y"
while again != "n":
base = int(input("Enter base: "))
height = int(input("Enter height: "))
side1 = int(input("Enter side 1: "))
side2 = int(input("Enter side 2: "))
side3 = int(input("Enter side 3: "))
area = (base*height) / 2
certain_type = []
if side1 == side2 == side3:
print("Equilateral triangle")
elif side1==side2 or side2==side3 or side1==side3:
print("isosceles triangle")
else:
print("Scalene triangle")
print('This %f of the triangle is %0.2f' %area, certaintype)
Well done, so a few comments...
(1) indentation throws it off because the entire code should be under the while loop, so that your entire game will repeat itself after every triangle
(2) Instead of directly printing the "isosceles", "scalene" etc, "certaintype" ...you can store the value (eg scalene) under the certaintype variable using certaintype='scalene'. That way, you can print the type of triangle in your sentence later.
(3) The final print should also be under the while loop as you want to tell your users the answer after every triangle information entry.
(4) The syntax for string interpolation is %s for string variables like certaintype while the syntax for number/decimals is %d for number variables like area. Check out how I rewrote the final print line.
Somethig like this should work:
while again != "n":
base = int(input("Enter base: "))
height = int(input("Enter height: "))
side1 = int(input("Enter side 1: "))
side2 = int(input("Enter side 2: "))
side3 = int(input("Enter side 3: "))
area = (base*height) / 2
certain_type = []
if side1 == side2 == side3:
certaintype = "Equilateral triangle"
elif side1==side2 or side2==side3 or side1==side3:
certaintype = "isosceles triangle"
else:
certaintype = "Scalene triangle"
print('This %d of the triangle is %s' % (certaintype, area) )
I'm kind of new to python or coding in general and I have run into a problem in my while-loop. I want to point out that the while-loop only works when the variable "loop" = True
loop = True #Makes the asking sequence work
def loop_again(): #Makes the program ask if you want to continue
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
When I write "No" when the program asks me if I want to do this again, it still loops the sequence, even though the variable "loop" is supposed to be false when i type "No" which is supposed to stop the loop.
Full code (while loop at the bottom of the code):
#Solving for the area in a shape automatically
import math
loop = True #Makes the asking sequence work
def loop_again(): #Makes the program ask if you want to continue
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
def sqr_area(): #Asking sequence for the area of the square
if choose == "Square":
a = float(input("Input the length of the side here: "))
print(a ** 2)
loop_again()
def rec_area(): #Asking sequence for the area of the rectangle
if choose == "Rectangle":
a = float(input("Input the length of the long sides here: "))
b = float(input("Input the length of the short sides here: "))
print(a * b)
loop_again()
def tri_area(): #Asking sequence for the area of the triangle
a = float(input("Input the length of the side: "))
b = float(input("Input the length of the height: "))
print((a * b) / 2)
loop_again()
def cir_area(): #Asking sequence for the area of the circle
r = float(input("Length of the radius: "))
print((r ** 2) * math.pi)
loop_again()
while loop == True: #While loop, asking sequence
choose = str(input("Input what shape that you want to figure out the area of here: "))
if choose == "Square":
sqr_area()
elif choose == "Rectangle":
rec_area()
elif choose == "Triangle":
tri_area()
elif choose == "Circle":
cir_area()
else:
print("Invalid shape, Input one of these shapes: Square, Rectangle, Triangle, Circle")
choose
Thanks in advance!
Don't use recursion when you should be using a loop, and loop_again should return a value instead of setting loop globally.
import math
# Returns true once the input is Yes or false once the input is No
def loop_again():
while True:
response = str(input("Do you want to do this again? Yes or No: "))
if response == "Yes":
return True
elif response == "No":
return False
else:
print("Please answer yes or no: ")
loop_again should be called after the relevant *_area function has returned, not inside each function. The functions don't need to know or care
about the value of choose; they are only called when they are intended to be called.
# Print the area of a square
def sqr_area():
a = float(input("Input the length of the side here: "))
print(a ** 2)
# Print the area of a rectangle
def rec_area():
a = float(input("Input the length of the long sides here: "))
b = float(input("Input the length of the short sides here: "))
print(a * b)
# Print the area of a triangle
def tri_area():
a = float(input("Input the length of the side: "))
b = float(input("Input the length of the height: "))
print((a * b) / 2)
# Print the area of a circle
def cir_area():
r = float(input("Length of the radius: "))
print((r ** 2) * math.pi)
The final loop can run indefinitely, until loop_again returns True.
# Loop until the user chooses to not run again
while True:
choose = input("Input what shape that you want to figure out the area of here: ")
if choose == "Square":
sqr_area()
elif choose == "Rectangle":
rec_area()
elif choose == "Triangle":
tri_area()
elif choose == "Circle":
cir_area()
else:
print("Invalid shape, Input one of these shapes: Square, Rectangle, Triangle, Circle")
continue
if loop_again():
break
In the loop_again() function you have to add this at the beginning:
global loop
Otherwise, the variable is considered local and won't have any effect on the other loop variable that's in the outer scope.
It's a context variable problem. The loop variable you have in loop_again() and the one inside the while loop are different ones.
Every variable inside a function, in python, is local variable, unless its an argument, or if you use global variable in the main and in inside the functions.
So make it global or pass and return it inside the functions
#Solving for the area in a shape automatically
import math
global loop
loop = True #Makes the asking sequence work
def loop_again(): #Makes the program ask if you want to continue
global loop
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
def sqr_area(): #Asking sequence for the area of the square
if choose == "Square":
a = float(input("Input the length of the side here: "))
print(a ** 2)
loop_again()
def rec_area(): #Asking sequence for the area of the rectangle
if choose == "Rectangle":
a = float(input("Input the length of the long sides here: "))
b = float(input("Input the length of the short sides here: "))
print(a * b)
loop_again()
def tri_area(): #Asking sequence for the area of the triangle
a = float(input("Input the length of the side: "))
b = float(input("Input the length of the height: "))
print((a * b) / 2)
loop_again()
def cir_area(): #Asking sequence for the area of the circle
r = float(input("Length of the radius: "))
print((r ** 2) * math.pi)
loop_again()
while loop == True: #While loop, asking sequence
global loop
choose = str(input("Input what shape that you want to figure out the area of here: "))
if choose == "Square":
sqr_area()
elif choose == "Rectangle":
rec_area()
elif choose == "Triangle":
tri_area()
elif choose == "Circle":
cir_area()
else:
print("Invalid shape, Input one of these shapes: Square, Rectangle, Triangle, Circle")
choose
you need to say in every function that loop is the global one, otherwise python you interpret it as a local variable.
the other way is:
import math
loop = True #Makes the asking sequence work
def loop_again(loop ): #Makes the program ask if you want to continue
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
return loop
def sqr_area(loop): #Asking sequence for the area of the square
if choose == "Square":
a = float(input("Input the length of the side here: "))
print(a ** 2)
loop = loop_again()
return loop
def rec_area(loop): #Asking sequence for the area of the rectangle
if choose == "Rectangle":
a = float(input("Input the length of the long sides here: "))
b = float(input("Input the length of the short sides here: "))
print(a * b)
loop = loop_again(loop)
return loop
def tri_area(loop): #Asking sequence for the area of the triangle
a = float(input("Input the length of the side: "))
b = float(input("Input the length of the height: "))
print((a * b) / 2)
loop = loop_again()
def cir_area(loop): #Asking sequence for the area of the circle
r = float(input("Length of the radius: "))
print((r ** 2) * math.pi)
loop = loop_again()
while loop == True: #While loop, asking sequence
choose = str(input("Input what shape that you want to figure out the area of here: "))
if choose == "Square":
loop = sqr_area(loop )
elif choose == "Rectangle":
loop = rec_area(loop )
elif choose == "Triangle":
loop = tri_area(loop )
elif choose == "Circle":
loop = cir_area(loop )
else:
print("Invalid shape, Input one of these shapes: Square, Rectangle, Triangle, Circle")
choose```
I wrote a simple program for class; it gives the user the choice of 5 different questions to solve, area of a circle, volume of a cylinder/cube, or surface area of cylinder/cube. The user has to decide which problem they want to solve, and if they make an invalid decision the program loops back to the start to let them try again. However, I can't figure out how to break the loop; after solving one of the problems it still loops back to the start of the program.
invalid_input = True
def start () :
#Intro
print("Welcome! This program can solve 5 different problems for you.")
print()
print("1. Volume of a cylinder")
print("2. Surface Area of a cylinder")
print("3. Volume of a cube")
print("4. Surface Area of a cube")
print("5. Area of a circle")
print()
#Get choice from user
choice = input("Which problem do you want to solve?")
print()
if choice == "1":
#Intro:
print("The program will now calculate the volume of your cylinder.")
print()
#Get radius and height
radius = float(input("What is the radius?"))
print()
height = float(input("What is the height?"))
print()
#Calculate volume
if radius > 0 and height > 0:
import math
volume = math.pi * (radius**2) * height
roundedVolume = round(volume,2)
#Print volume
print("The volume is " + str(roundedVolume) + (" units."))
invalid_input = False
else:
print("Invalid Inputs, please try again.")
print()
elif choice == "2":
#Intro:
print("The program will calculate the surface area of your cylinder.")
print()
#Get radius and height
radius = float(input("What is the radius?"))
print()
height = float(input("What is the height?"))
print()
#Calculate surface area
if radius > 0 and height > 0:
import math
pi = math.pi
surfaceArea = (2*pi*radius*height) + (2*pi*radius**2)
roundedSA = round(surfaceArea,2)
#Print volume
print("The surface area is " + str(roundedSA) + " units." )
invalid_input = False
elif radius < 0 or height < 0:
print("Invalid Inputs, please try again.")
print()
elif choice == "3":
#Intro:
print("The program will calculate the volume of your cube.")
print()
#Get edge length
edge = float(input("What is the length of the edge?"))
print()
#Calculate volume
if edge > 0:
volume = edge**3
roundedVolume = round(volume,2)
#Print volume
print("The volume is " + str(roundedVolume) + (" units."))
invalid_input = False
else:
print("Invalid Edge, please try again")
print()
elif choice == "4":
#Intro:
print("The program will calculate the surface area of your cube.")
print()
#Get length of the edge
edge = float(input("What is the length of the edge?"))
print()
#Calculate surface area
if edge > 0:
surfaceArea = 6*(edge**2)
roundedSA = round(surfaceArea,2)
#Print volume
print("The surface area is " + str(roundedSA) + (" units."))
invalid_input = False
else:
print("Invalid Edge, please try again")
print()
elif choice == "5":
#Intro
print("The program will calculate the area of your circle")
print()
#Get radius
radius = float(input("What is your radius?"))
if radius > 0:
#Calculate Area
import math
area = math.pi*(radius**2)
roundedArea = round(area,2)
print("The area of your circle is " + str(roundedArea) + " units.")
invalid_input = False
else:
print("Invalid Radius, please try again")
print()
else:
print("Invalid Input, please try again.")
print()
while invalid_input :
start ()
The preferred way for this kind of code is to use a while Truestatement like so,
while True:
n = raw_input("Please enter 'hello':")
if n.strip() == 'hello':
break
This is an example, that you can correctly change for your needs.Here is the link to documentation.
You can add an option to exit.
print('6. Exit')
...
if choice=='6':
break
Or you can break on any non-valid input.
else:
break
invalid_input = True is a global variable (outside any function).
Setting invalid_input = False in your function sets a local variable, unrelated to the global one. To change the global variable, you need the following (greatly simplified) code:
invalid_input = True
def start():
global invalid_input
invalid_input = False
while invalid_input:
start()
Global variables are best to be avoided, though. Better to write a function to ensure you have valid input:
def get_choice():
while True:
try:
choice = int(input('Which option (1-5)? '))
if 1 <= choice <= 5:
break
else:
print('Value must be 1-5.')
except ValueError:
print('Invalid input.')
return choice
Example:
>>> choice = get_choice()
Which option (1-5)? one
Invalid input.
Which option (1-5)? 1st
Invalid input.
Which option (1-5)? 0
Value must be 1-5.
Which option (1-5)? 6
Value must be 1-5.
Which option (1-5)? 3
>>> choice
3
Hey guys like the title said im not quite sure how to add a while True statement to my code. So far, after the program calculates the answer it goes back to the command prompt and not the menu which is what I want it to do. Any help is greatly appreciated. Thanks
1) Area (Square)
2) Area (Rectangle)
3) Area (Circle)
4) Perimeter (Square)
5) Perimeter (Rectangle)
6) Perimeter (Circle)
7) Exit Program
""")
Choice = input ("1,2,3,4,5,6 OR 7? ")
while True:
if Choice == "1":
print ("You have chosen area (Square)")
length = float(input("input Length?"))
print ("Area is:" , length**2.0)
elif Choice == "2":
print ("You have chosen area (Rectangle)")
length = float (input("input length?"))
width = float (input("input width?"))
print ("Area is:" , length*width)
elif Choice == "3":
print ("You have chosen area (Circle)")
radius = float (input("input radius?"))
print ("Area is:" , (radius**2.0)*3.14)
elif Choice == "4":
print ("You have chosen perimeter (Square)")
length = float(input("Input length?"))
print ("Perimeter is:" , length*4.0)
elif Choice == "5":
print ("You have chosen perimeter (Rectangle)")
width = float(input("Input width?"))
length = float(input("Input length?"))
print ("Perimeter is:" , width*2.0+length*2.0)
elif Choice == "6":
print ("You have chosen perimeter (Circle)")
radius = float(input("Input radius?"))
print ("Perimeter is:" , 2.0*3.14*radius)
elif Choice == "7":
print ("You have chosen to exit")
exit()
break
Your break is at the end of the loop, so here is what you're telling the program to do:
while True:
//Choice stuff
exit the loop
Move the break and exit() inside elif Choice == "7":and it will only execute that code when option 7 is chosen.
You only actually need 1 of the escaping functions too. I tend not to use exit() and just use break - if this is the end of your program, it will exit anyway. If you have more code below, it will be executed. Good practice to be consistent.
But you've got to put your exit into the else statement. And the break is not necessary.
I have an area calculator and I want the user in the beginning choose what thing to calculate instead of going down the list. is there a code for to ask the user, and stop the other code. And after the user chooses, take the user to that specific function. Then afterwards, take them back to the ask screen? Need some advice.
import math
def square():
print ("Area of Square")
print ("")
S = float(input("Enter Length of Square:"))
A = round((S**2),3)
print (A, "is the Area of the Square")
print("")
print("")
square()
def rectangle():
print("Area of Rectangle")
print ("")
L = float(input("Enter Length of Rectangle:"))
W = float(input("Enter Width of Rectangle:"))
A = round((L*W),3)
print (A, "is the Area of the Rectangle")
print("")
print("")
rectangle()
def paralelogram():
print("Area of Paralelogram")
print("")
B = float(input("Enter Base of Paralelogram:"))
H = float(input("Enter Height of Paralelogram:"))
A = round((B*H),3)
print (A, "is the Area of the Paralelogram")
print("")
print("")
paralelogram()
def triangle():
print("Area of Triangle")
print("")
B = float(input("Enter Base of Triangle:"))
H = float(input("Enter Height of Triangle:"))
A = round(((B*H)/2),3)
print (A, "is the Area of the Triangle")
print("")
print("")
triangle()
def circle():
print("Area of Circle")
print("")
r = float(input("Enter Radius of Circle:"))
A = round(math.pi*(r**2),3)
print (A, "is the Area of the Circle")
print("")
print("")
circle()
def trapezoid():
print("Area of Trapezoid")
print("")
B1 = float(input("Enter Base 1 of Trapezoid:"))
B2 = float(input("Enter Base 2 of Trapezoid:"))
H = float(input("Enter Height of Trapezoid:"))
A = round((((B1+B2)/2)*H),3)
print (A, "is the Area of the Trapezoid")
print("")
print("")
trapezoid()
def sphere():
print("Area of Sphere")
print("")
r = float(input("Enter Radius of Sphere:"))
A = round((((r**2)*4)*math.pi),3)
print (A, "is the Area of the Sphere")
print("")
sphere()
A more Pythonic way of doing this is to store references to the functions in a dictionary:
area_func = {'triangle': triangle, 'square': square, 'rectangle': rectangle,
'paralelogram': paralelogram, 'circle': circle, 'trapezoid': trapezoid,
'sphere': sphere}
while True:
shape = input('What shape do you want to calculate the area of ("stop" to end)?')
if shape == 'stop':
break
try:
area_func[shape]()
except KeyError:
print("I don't recognise that shape.")
continue
This works because functions, like everything else in Python, are objects. So you can store them as values in a dictionary, assign variable names to them, etc. The expression area_func[shape] is thus a reference to a function, for example, triangle, which can then be called (by appending (), an empty set of parentheses since your functions don't take any arguments).
As others have noted, you probably don't want the function calls after each definition. And, to be pedantic, parallelogram is the correct spelling.
You can do that with a while loop.
#your functions here
options="""1-)Square
2-)Rectangel
3-)Paralelogram
4-)Triangle
5-)Trapezoid
6-)sphere
"""
while True:
print (options)
user=input("Please choose a valid option: ")
if user=="1":
square()
continue
elif user=="2":
rectangel()
continue
..
..
.. #same codes with elif statement till 6.
..
else:
print ("It's not a valid choose.Please choose a valid one.")