Sign in to follow this  
Fox76

Practice Program: Area Calculator

Recommended Posts

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

Practice Program: Area Calculator

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Requirement: Watch up to Tutorial 4

Everything you need to know to create this program is taught up to tutorial 4 the calculator program. This program is very similar to that one but is meant to give you practice creating programs on your own based on what you already know. This example is also one that was given as practice in my old programming class for python.

The goal is to create a program to calculate the area of four different shapes: triangles, squares, rectangles, and circles. You should use functions for this practice, these are the functions you should create:
 

areaCircle(radius)                  # takes one argument, returns the area of a circle

areaRectangle(length, width)        # takes two arguments, returns the area of a rectangle

areaSquare(side)                    # takes one argument, returns the area of a square

areaTriangle(base, height)          # takes two arguments, returns the area of a triangle

The program should give a menu to the user to choose which shape to calculate, then ask for the values (length, width, radius, ect). Then pass those values to the appropriate function and return them to display the result to the user.

Here are the shape formulas:
area of a square = side2 (you use ** in python  to express exponentiation, so this is side ** 2 in code)

area of a rectangle = length * width

area of triangle = 1/2 base * height (in code you could do (base / 2) * height)

area of a circle = pi * radius2 (in code you can do 3.14 * radius ** 2 note: another way would be to actually import pythons built in math function and use it for pi, but importing hasn't been covered yet so we'll stick to just using 3.14)

Here is an example of the output we're aiming for:
note: In this example the users input for the prompts is shown

Shape Area Calculator

----------------------------

1) Triangle

2) Rectangle

3) Square

4) Circle



Which shape: 1

Base: 5

Height: 6



The area is 15.0

Once you have the program running, try adding in error checking for the menu, if the user enters 5 as a menu choice have it state it's an invalid option. Hint: This is shown in tutorial 4 try to modify this code to have that error check.

Not sure how to start off or stuck and need some help look below for the basic code layout of this program:

# Area of triangle function

def areaTriangle(base, height):

    area = (base / 2) * height

    return area



def main():

    # Create menu and display choices to the user

    print("Shape Area Calculator")

    print("-=-=-=-=-=-=-=-=-=-=-=-=-=-")

    print("1) Triangle")

    print("") # This will print a blank line to space it out

    # Prompt user to enter a choice.

    choice = int(input("Which shape: "))



    # Determine the users choice and proceed.

    if choice == 1:

        # Prompt the user to enter the values needed by the function.

        base = int(input("Enter the base of the triangle: "))

        height = int(input("Enter the height of the triangle: "))

        # Output the result to the user.

        print("The area is", areaTriangle(base, height))

       

# Call the main function and run it

main()

Need more help or something just not working right for this practice program? Post it here for troubleshooting help.

Share this post


Link to post
Share on other sites

I've been looking at all of Kevins tutorials.

I haven't found any 5th tutorial yet, is there one or did he give up on this?

He was by far the best person I've ever witness to explain complicated things like coding.

Share this post


Link to post
Share on other sites

He's still here and he's still making them, he just took a break for awhile because he was busy. This was his post he stated it in on June 17th.

I've been quite busy lately... But my schedule will be freeing up in about 2-3 weeks at which point you can expect another volley of videos.

Thank you for your support.

I'll see if I can whip up another practice program, to keep everyone occupied till he can get back to making python videos again.

Share this post


Link to post
Share on other sites

Hi,
 
I made a little start with the code it works al fine now.

At this moment only Area and  Circumference for a circle

I imported pi from cmath as I can't live with just 3,14.

But I would love some feed back from how ever.
 
Many thanks,

 

#cal app

#imports

#get pi
from cmath import pi

#get sqrt
from math import sqrt




#def's

#Add
def add(num1, num2):
	return num1 + num2

#Subtract
def sub(num1, num2):
	return num1 - num2

#Divide
def dev(num1, num2):
	return num1 / num2

#multiply
def mul(num1, num2):
	return num1 * num2

#power of
def pow1(x, y):
	return pow(x, y)

#Square root
def sqrt1(num1):
	return sqrt(num1)

#Circle

#Area
def areaCircle(r):
	return pi * r**2

#Circumference
def circCircle(r):
	return 2 * pi * r





#main bit
def main():
	operation = input ("\t\tWhat would you like te do\n(+)Add \t\t\t\t\t(-)Subtraction\n(*)Multiply\t\t\t\t(/)Divide\n(pow)Power x, y\t\t\t\t(sqrt)Square root\n(A)Area/shapes Calculator\n\nPlease enter?: ")
	if(operation != '+' and operation != '-' and operation != '/' and operation != '*' and operation != 'sqrt' and operation != 'pow' and operation != 'A'):
		print("Enter a valid operation")

	#Add, Subtraction, multiply, Divide
	elif(operation == '+' or operation == '-' or operation == '/' or operation == '*'):
		num1 = int(input("Number please: "))
		num2 = int(input("Number please: "))
		if(operation == '+'):
			print(add(num1, num2))
		elif(operation == '-'):
			print(sub(num1, num2))
		elif(operation == '/'):
			print(dev(num1, num2))
		elif(operation == '*'):
			print(mul(num1, num2))
	#power of
	elif(operation == 'pow'):
			x = int(input("What is x:"))
			y = int(input("Times y:"))
			print(pow1(x, y))
	#Square root
	elif(operation == sqrt):
			num1 = int(input("Number please:"))
			print (sqrt1(num1))									
	#Area and shapes			  
	elif(operation == 'A'):
			operationArea = input ("What would you like to do \n(C)Circle\nPlease enter?")
			if(operationArea != 'C'):
				print("Enter a valid operation")
			#Circle
			elif(operationArea == 'C'):
				operationCircle = input ("what would you like te know about a circle\n(A)Area\t\t(C)Circumference\n\nPlease enter?")
				if(operationCircle != 'A' and operationCircle != 'C'):
					print("Enter a valid operation")

				#area Circle
				elif(operationCircle == 'A'):
					r = int(input("What is the radius?"))
					print(areaCircle(r))

				#Circumference Circle
				else:
									r = int(input("What is the radius?"))
									print(circCircle(r))
							  
				



#loop
goAgain = True
while(goAgain):
	main()
	userInput = input('Do another calculation?(y/n)')
	if(userInput == 'n'):
		 goAgain = False
				  


Share this post


Link to post
Share on other sites

I worked on it and this is the end result

 

#cal app

#imports

#get pi
from cmath import pi

#get sqrt
from math import sqrt

#get turtle
from turtle import circle
from turtle import write
from turtle import goto
from turtle import penup
from turtle import hideturtle
from turtle import clear
from turtle import done
from turtle import bye


#get time
from time import sleep

#random
from random import uniform
from random import sample



#def's

#Add
def add(num1, num2):
	return num1 + num2

#Subtract
def sub(num1, num2):
	return num1 - num2

#Divide
def dev(num1, num2):
	return num1 / num2

#multiply
def mul(num1, num2):
	return num1 * num2

#power of
def pow1(x, y):
	return pow(x, y)

#Square root
def sqrt1(num1):
	return sqrt(num1)

#Circle

#Area
def areaCircle(r):
	return pi * r**2

#Circumference
def circCircle(r):
	return 2 * pi * r

#Triangle
def areaTria(h, b):
        return 0.5 * b * h

#Square
def areaSqu(a):
        return a**2

#Rectangle
def areaRec(w, h):
        return w * h


#fun and random stuff

#random number between 0 and x
def randNumb(x):
        return uniform(0, x)

#add wrong
def addWrong(num1, num2):
	return num1 + num2 + uniform(0, 10)

#Sub wrong
def subWrong(num1, num2):
	return num1 - num2 - uniform(0, 10)

#Mul wrong
def mulWrong(num1, num2):
	return num1 * num2 + uniform(0, 10)

#dev wrong
def devWrong(num1, num2):
	return num1 / num2 + uniform(0, 10)



#main bit
def main():
	try:
		operation = input ('''
            What would you like to do    			
====================================================
|(+)Add                           (-)Subtraction   |
|(*)Multiply                      (/)Divide        |
|(pow)Power x, y                  (sqrt)Square root|
|(A)Area/shapes Calculator        (F)Fun           |
====================================================
Please enter: ''')
		if(operation != '+' and operation != '-' and operation != '/' and operation != '*' and operation != 'sqrt' and operation != 'pow' and operation != 'A' and operation != 'F'):
			print("\nEnter a valid operation")

		#Add, Subtraction, multiply, Divide
		elif(operation == '+' or operation == '-' or operation == '/' or operation == '*'):
			num1 = float(input("\nNumber please: "))
			num2 = float(input("Number please: "))
			if(operation == '+'):
				print(add(num1, num2))
			elif(operation == '-'):
				print(sub(num1, num2))
			elif(operation == '/'):
				print(dev(num1, num2))
			elif(operation == '*'):
				print(mul(num1, num2))
		#power of
		elif(operation == 'pow'):
				x = float(input("\nWhat is x:"))
				y = float(input("Times y:"))
				print(pow1(x, y))
		#Square root
		elif(operation == 'sqrt'):
				num1 = float(input("\nNumber please:"))
				print (sqrt1(num1))									
		#Area and shapes			  
		elif(operation == 'A'):
				operationArea = input ('''
             What would you like to do    			
====================================================
|(C)Circle                          (T)triangle    |
|(S)Square                          (R)Rectangle   |
====================================================
Please enter: ''')
				if(operationArea != 'C' and operationArea != 'T' and operationArea != 'S' and operationArea != 'R'):
					print("\nEnter a valid operation")
				#Circle
				elif(operationArea == 'C'):
					r = float(input("\nWhat is the radius?"))
					print("\nArea is:")
					print(areaCircle(r))

					#Circumference Circle
					print("\nCircumference is")
					print(circCircle(r))
					print(" ")

					print("Wait till Python Turtle Graphics window is closed")

					#draw circle
					circle(r)
					goto(0, r)
					penup()
					goto(0, -25)
					write("Radius is:", font=('Arial', 20, 'normal'))
					goto(0, -50)
					write(r, font=('Arial', 20, 'normal'))
					goto(0, -75)
					write("Area is:", font=('Arial', 20, 'normal'))
					goto(0, -100)
					write(areaCircle(r), font=('Arial', 20, 'normal'))
					goto(0, -125)
					write("Circumference is:", font=('Arial', 20, 'normal'))
					goto(0, -150)
					write(circCircle(r), font=('Arial', 20, 'normal'))
					hideturtle()
					sleep(5)
					bye()

					
				#Triaangle
				elif(operationArea == 'T'):
					h = float(input("\nWhat is the height?:"))
					b = float(input("What is the base?:"))
					print("\nArea is:")
					print(areaTria(b, h))
					print(" ")


				#Square
				elif(operationArea == 'S'):
					a = float(input("\nWhat is the length of side?:"))
					print("\nArea is:")
					print(areaSqu(a))
					print(" ")


				#Rectangle
				elif(operationArea == 'R'):
					w = float(input("\nWhat is the width?:"))
					h = float(input("what is the height?:"))
					print("\nArea is:")
					print(areaRec(w, h))
					print(" ")


		#Fun and random stuff
		elif(operation == 'F'):
			operationFun = input('''
            What would you like to do    			
====================================================
|(R)Get random number          (G)Guess number     |
|(H)Hello World                (P)What is pi       |
|(A)Always wrong Calculator    (W)Write random file|
====================================================
Please enter: ''')
			if(operationFun != 'R' and operationFun != 'G' and operationFun != 'H' and operationFun != 'P' and operationFun != 'A' and operationFun != 'W'):
				print("\nEnter a valid operation")

	        #random number
			elif(operationFun == 'R'):
				x = float(input("\nWhat is the max value?:"))
				print("\nYour random number is:")
				print(randNumb(x))
				print(" ")

			#Guess number
			elif(operationFun == 'G'):
				go = True
				while(go):
					numX = int(input("\nGuess a number between 1 - 10?"))
					
					x = sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1)
					if([numX] == x):
						print("\nGREAT YOUR CORRECT!")

						againGuess = input("\nAgain?(y/n)")
						if(againGuess == 'n'):
							go = False

					else:
						print("\nTo bad your wrong!")

						againGuess = input("\nAgain?(y/n)")
						if(againGuess == 'n'):
							go = False


			#Hello world
			elif(operationFun == 'H'):
				print("\nHello World")
				print(" ")

				#print Hello World
				write("Hello World", font=('Arial', 50, 'normal'))
				sleep(5)
				bye()

			#What is pi
			elif(operationFun == 'P'):
				print("\nPi is about")
				print(pi)
				print(" ")

			#Always wrong cal
			elif(operationFun == 'A'):
				operationWrong = input ('''
	       What would you like to do    			
====================================================
|(+)Add                           (-)Subtraction   |
|(*)Multiply                      (/)Divide        |
====================================================
Please enter: 

''')
				if(operationWrong != '+' and operationWrong != '-' and operationWrong != '*' and operationWrong != '/'):
					print("\nEnter a valid operation")

				elif(operationWrong == '+' or operationWrong == '-' or operationWrong == '/' or operationWrong == '*'):
					num1 = float(input("\nNumber please: "))
					num2 = float(input("Number please: "))
					if(operationWrong == '+'):
						print(addWrong(num1, num2))
					elif(operationWrong == '-'):
						print(subWrong(num1, num2))
					elif(operationWrong == '/'):
						print(devWrong(num1, num2))
					elif(operationWrong == '*'):
						print(mulWrong(num1, num2))


			#Write random file
			elif(operationFun == 'W'):
				x = sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,124,32,432,423,4,123,12,432,532,13,2,32,4,32,523,4,23,4,23,412,3,123,43,4,32,4,32423,
					234,34,324,324,523,1,768,456,0,9867,967785,212,324,57,46,235,234,345,235,80,79856,46,345,867,234,7,45,768,967,57,9,76,765], 4)
				
				fileName = str(x) + ".txt"

				y = sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,124,32,432,423,4,123,12,432,532,13,2,32,4,32,523,4,23,4,23,412,3,123,43,4,32,4,32423,
					234,34,324,324,523,1,768,456,0,9867,967785,214,34,785,356,7456,546,435,56,65,324,325,78,9,546,9767,24,75,234,56,7657,456], 4)
					
				text = "hi there\nGood to see you\n\n" + str(y)

				randFile = open(fileName, 'w')
				randFile.write(text)
				randFile.close()

				print("\ndone")
	except Exception as ex:
		print("\nThis went wrong\n\n")
		print(ex)
		print(" ")

#loop
goAgain = True
while(goAgain):
	main()
	userInput = input("\nDo another calculation?(y/n)")
	if(userInput == 'n'):
		 goAgain = False
				 
 

 

Share this post


Link to post
Share on other sites

Thanks a lot Kelvin and all members. I am very new to Python. Found Kelvin's Youtube yesterday night. Please Kelvin keep up the good work. You are really helping us a lot. Looking forward to more videos (Tutorial 5,6,7,8,.....). Also I like the idea of giving us something to work on. Here is my own code on the area calculator.

 

#Returns the area of shapes


def areacir(Radius):
return 3.14*Radius**2 #Returns the area of the circle

def arearect(Length, Width):
return Length * Width #Returns the area of the rectangle

def areasqu(Length):
return Length**2 #Returns the area of the square

def areatri(Base, Height):
return 0.5*Base*Height #Returns the area of the triangle


def main():
operation=input("what shape do you want to calculate its area (cir,rect,squ, tri):")
if (operation !='cir' and operation !='rect' and operation !='squ' and operation !='tri'):
#Invalid operation
print("I can only calculte for cir, rect, squ and tri")
else:

if (operation == 'cir'):
var3 = int(input("Enter Radius:"))
print(areacir(var3))

elif (operation == 'rect'):
var1 = int(input("Enter Length:"))
var2 = int(input("Enter Width:"))
print(arearect(var1,var2))
elif (operation == 'squ'):
var1 = int(input("Enter Length:"))
print(areasqu(var1))
else:
var4 = int(input("Enter Base:"))
var5 = int(input("Enter Height:"))
print(areatri(var4,var5))





main()
main()
main()
main()
main()

 

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this