How to Loop when no 'elif' conditions are met

I’ve just finished the Area Calculator excercise in Learn Python 2.

https://www.codecademy.com/courses/learn-python/projects/area-calculator

The code is as follows:

print 'Starting Calculator'

# User enters what shape we are calculating an area for

option = raw_input('Enter C for Circle or T for Triangle: ')

#Area Calculation for a circle and printing of result

if option == 'C':
  radius = float(raw_input('Enter radius: '))
  area = 3.14159*radius**2
  print 'The area of a circle of radius %s is %s square units.' % (radius,area)

#Area calculation for a Triangle and printing of result

elif option == 'T':
  base = float(raw_input('Enter base length: '))
  height = float(raw_input('Enter height: '))
  area = 0.5*base*height
  print 'The area of a triangle with a height, %s, and a base length, %s, is %s square units.' % (height,base,area)

#Termination of program and invalid entry message should user not enter a C or T

else:
	print '%s is an invalid entry. Please enter C for Circle or T for Triangle' % (option)
print 'End of program'

Currently, if the user enters neither C nor T for the shape (‘option’), the program merely tells them it is an invalid entry and terminates.

My question is, how would I instead prompt them to re-enter a raw_input value for ‘option’ and run through the if statement again (hopefully with the user now having entered a valid C or T)?

1 Like

you could use a while loop? This way, you can keep the program running until there is valid input, then you can break the loop

2 Likes