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.
Related
Hi I'm learning Python by myself and I'm tying to refactor this code. I need to use declaration and invoke of the function.
So the original code is:
while True:
length = int(input("Enter the length of your room: "))
if length > 0:
break
while True:
width = int(input("Enter the width of your room: "))
if width > 0:
break
while True
height = int(input("Enter the height of your room: "))
if height > 0:
break
print("The volume of your room is", length * width * height)
What I'm doing so far (I'm not sure if it's good or not). Any suggestions?:
def volume(length, width, height)
length= int(input("Enter the length of your room: "))
while (length = 0):
print(f"The length of your room is invalid)
return
width = int(input("Enter the width of your room: "))
while (width = 0):
print(f"The width of your room is invalid)
return
height = int(input("Enter the height of your room: "))
while (height = 0):
print(f"The height of your room is invalid)
return
print("The volume of your room is", length * width * height)
return
volume(length*width * height)
Code:
def volume(lenght, width, height):
if lenght > 0 and width > 0 and height > 0:
room_volume = lenght*width*height
return room_volume
return 'wrong input'
room_volume = volume(input('Length: '), input('Width: '), input('Height: '))
print(f'Room volume: {room_volume}')
You can check if argument value is greater than 0 just by one simple if statement, no need for these while loops.
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 am trying to make a program where it converts imperial to metric. The part I am having trouble with is that with any input that is an invalid number (any negative) I am supposed to terminate the program without using exit, break, or system exit.
print('Hello, Please input the Imperial values!')
#Miles
Miles = float(input('Miles to Kilometers: '))
totalKilometers = (1.6 * Miles)
if Miles < 0:
print('Please no negative numbers')
else:
if Miles > 0:
print("The metric conversion is ", totalKilometers)
#Fahrenheit
Fahrenheit = float(input('Fahrenheit to Celsius: '))
totalCelcius = ((Fahrenheit - 32) * 5/9 )
if Fahrenheit < 0 or Fahrenheit > 1000:
print('Please check your Fahrenheit number, It must be greater than 0 and
less than 1000')
else:
if Fahrenheit > 0 or Fahrenheit < 1000:
print("The metric conversion is ", totalCelcius)
#Gallons
Gallons = float(input('Gallons to Liters: '))
totalLiters = (3.9 * Gallons)
if Gallons < 0:
print('Please no negative numbers')
else:
if Gallons > 0:
print("The metric conversion is ", totalLiters)
#Pounds
Pounds = float(input('Pounds to Kilograms: '))
totalKilograms = (.45 * Pounds)
if Pounds < 0:
print('Please no negative numbers')
else:
if Pounds > 0:
print("The metric conversion is ", totalKilograms)
#Inches
Inches = float(input('Inches to Cenitmeters: '))
totalCentimeters = (2.54 * Inches)
if Inches < 0:
print('Please no negative numbers')
else:
if Inches > 0:
print("The metric conversion is ", totalCentimeters)
Since you can't exit out of the program, define all of the code you already have as a function and use return. The code would look something like this:
def imp-met():
print('Hello, Please input the Imperial values!')
#Miles
Miles = float(input('Miles to Kilometers: '))
totalKilometers = (1.6 * Miles)
if Miles < 0:
print('Please no negative numbers')
return
(rest of code using return when needed)
imp-met()
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