I need to add a loop to the code in order to allow the user to restart the programme and choose another of the available shapes.
import math
import time
shapearea = 0
pi = 3.14159
print("Select shape\n1.Square\n2.Circle\n3.Triangle")
shape = input("Enter shape(Square/Circle/Triangle):")
if shape == "square":
sideval = int(input("Enter side value of the shape:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(sideval ** 2)
elif shape == "circle":
circleradius = int(input("Enter radius value of the circle:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(pi * circleradius **2)
elif shape == "triangle":
height = int(input("Enter the height of the shape:"))
base = int(input("Enter the base of the shape:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(base*height/2)
else:
print("The given shape is invalid, give a valid shape to calculate the area")
print ("The area of the chosen shape is " "%.2f" % shapearea)
try this maybe this could help you:
import math
import time
def calculate():
shapearea = 0
pi = 3.14159
print("Select shape\n1.Square\n2.Circle\n3.Triangle")
shape = input("Enter shape(Square/Circle/Triangle):")
if shape == "square":
sideval = int(input("Enter side value of the shape:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(sideval ** 2)
elif shape == "circle":
circleradius = int(input("Enter radius value of the circle:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(pi * circleradius **2)
elif shape == "triangle":
height = int(input("Enter the height of the shape:"))
base = int(input("Enter the base of the shape:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(base*height/2)
else:
print("The given shape is invalid, give a valid shape to calculate the area")
print ("The area of the chosen shape is " "%.2f" % shapearea)
calculate()
while input("Do you want to continue?(Y/N)") == "Y":
calculate()
print("exiting from program...")
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
Floor tile cost
print("Hello this program will help you figure out the cost to tile your floor")
x = input("Please enter the length of the floor that's being tiled: ")
y = input("Next, please enter the width of the floor: ")
fltype = raw_input("Now enter a shape that best describes the room you are getting tiled: ")
fltype = fltype.lower()
if fltype is "circle" or "ellipse":
formula = ((x * y)*.5) * 3.14
elif fltype is "rectangle" or "square":
formula = x * y
elif fltype is "triangle":
formula = (x * .5) * y
else:
print("Sorry unrecognized floor type please contact admin to add shape or try again.")
Where I would like the program to loop if the floor type is unrecognizable I know a while would work but I can't seem to get it.
tuc = input("What is the cost per unit of the tile you'd like: ")
pobs = input("Please Enter 1 if you are tiling the floor by yourself, otherwise enter 2 for professional flooring: ")
if pobs == 1:
total = tuc * formula
elif pobs == 2:
labor = input("What is the contractor's hourly labor cost ")
total = (tuc * formula) + ((formula / 20) * labor)
else:
print("Invalid command please try again ")
Also would be cool to loop this part if they didn't do pobs correctly
print("The total cost of the tiling project is $" + str(total))
print("Thank you for using my program any feedback is appreciated!")
Any feedback is good feedback hopefully I followed all rules thank everyone in advance.
You have a few problems there:
if fltype is "circle" or "ellipse":
means
if (fltype is "circle") or "ellipse":
which will always be True. This might be why your attempt at the while loop failed
while True
fltype = raw_input("Now enter a shape that best describes the room you are getting tiled: ")
fltype = fltype.lower()
if fltype in {"circle", "ellipse"}:
formula = ((x * y) * .25) * 3.14
elif fltype in {"rectangle", "square"}:
formula = x * y
elif fltype == "triangle":
formula = (x * .5) * y
else:
print("Sorry unrecognized floor type please contact admin to add shape or try again.")
continue
break
If I was you I will put your all program in a function that you can recall after when you want to replay the program. For example :
def myprog():
print("Hello this program will help you figure out the cost to tile your floor")
x = input("Please enter the length of the floor that's being tiled: ")
y = input("Next, please enter the width of the floor: ")
fltype = raw_input("Now enter a shape that best describes the room you are getting tiled: ")
fltype = fltype.lower()
if fltype in ["circle","ellipse"]:
formula = ((x * y)*.5) * 3.14
elif fltype in ["rectangle" , "square"]:
formula = x * y
elif fltype == "triangle":
formula = (x * .5) * y
else:
print("Sorry unrecognized floor type please contact admin to add shape or try again.")
myprog()
return
print("Your cost is %d" % (formula))
if __name__ == '__main__':
#only call if you file is executed but not if your file is imported
myprog()
I also correct your mistake in your if, in fact
fltype is "circle" or "ellipse" == (fltype is "circle") or "ellipse" == True #it always true
Something cleaner you be to repeat only the code that ask for the shape :
print("Hello this program will help you figure out the cost to tile your floor")
x = input("Please enter the length of the floor that's being tiled: ")
y = input("Next, please enter the width of the floor: ")
formula = None
while not formula :
fltype = raw_input("Now enter a shape that best describes the room you are getting tiled: ")
fltype = fltype.lower()
if fltype in ["circle","ellipse"]:
formula = ((x * y)*.5) * 3.14
elif fltype in ["rectangle" , "square"]:
formula = x * y
elif fltype == "triangle":
formula = (x * .5) * y
else:
print("Sorry unrecognized floor type please contact admin to add shape or try again.")
print("Your cost is %d" % (formula))
This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 6 months ago.
I'm getting an Expected an indented block here's the code, thank you for any help.
#Given the menu the user will calculate the area of square, circle, rectangle
from math import pi
def main ():
#declare and initialize variables
#float radius = length = width = base = height = 0.0
radius = length = width = base = height = 0.0
#float areaCircle = areaRectangle = areaTriangle = 0.0
areaCircle = areaRectangle = areaTriangle = 0.0
#int menuChoice = 0
menuChoice = 0
#display intro
while menuChoice != 4:
#Display menu
print("Geometry Calculator")
print("1) Calculate the Area of a Circle")
print("2) Calculate the Area of a Rectangle")
print("3) Calculate the Area of a Triangle")
print("4) Quit")
#Prompt for menuChoice
if menuChoice == 1:
while radius < 0:
#prompt for radius
radius = eval(input("What is radius of circle: "))
if radius < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
#calculate areaCircle
areaCircle = pi*r**2
#display areaCircle
print("The area of the circle is: ", areaCircle)
elif menuChoice == 2:
while length < 0:
#prompt for length
length = eval(input("What is the length of the rectangle: "))
if length < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
while width < 0:
#prompt for width
width = eval(input("What is the width of the rectangle: "))
if width < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
#calculate areaRectangle
areaRectangle = length * width
#diplay areaRectangle
print("The area of the rectangle is: ", areaRectangle)
elif menuChoice == 3:
while base < 0:
#prompt for base
base = eval(input("What is the length of the base of the triangle:"))
if base < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
while height < 0:
#prompt for height
height = eval(input("What is height of triangle"))
if height < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
#calculate areaTriangle
areaTriangle = 1/2 * base * height
#display areaTriangle
print("The area of the triangle is: ", areaTriangle)
elif menuChoice == 4:
#display exit message
else:
#display invalid
print("You must choose a number between 1-4 from the menu")
The error pops up at else. I've tried indenting one at a time, probably something small i'm overlooking third week into programming.
You need some sort of placeholder for the final elif block. You may use the standard Python non-op, pass:
elif menuChoice == 4:
#display exit message
pass
I'm assuming this will eventually be replaced by some other code, so the problem would have resolved itself had you continued working. If you are not planning on putting anything in this block, omit it entirely. There is no need for a conditional branch that does nothing.
It's the last line (#display exit message). Add a correctly indented pass statement, until you know what to do here. You need an actual python statement here, not a comment.