I have problems with my program that I have to do... here are the instructions: Write a program named triangle.py that uses a value-returning function that takes the lengths of the sides of a triangle as arguments and returns both the area and perimeter of the triangle. Prompt the user to enter the side lengths from the keyboard in the main function and then call the second function. Display the area and perimeter accurate to one decimal place. NOTE: Use Heron's Formula to find the area. I did it and it worked but the thing is he wants us to use one function that returns both area and perimeter.. so I re-did the program using one function but I keep getting an error saying per is not defined... I tried literally everything to fix it, looked online and nothing works. :( here is my code:
def main():
a = float(input('Enter the length of the first side: '))
b = float(input('Enter the length of the second side: '))
c = float(input('Enter the length of the third side: '))
print('The perimeter of the triangle is: ', format(per(a, b, c),',.1f'))
print('The area of the triangle is: ', format(area(a, b, c),',.1f'))
def area_per(a, b, c):
per = a + b + c
s = per / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
return area_per
main()
The problem here is that the "per" variable you defined is local to the area_per function.
You'd need to create another function per that stands outside of that if you want the right scope.
def main():
a = float(input('Enter the length of the first side: '))
b = float(input('Enter the length of the second side: '))
c = float(input('Enter the length of the third side: '))
print('The perimeter of the triangle is: ', format(per(a, b, c),',.1f'))
print('The area of the triangle is: ', format(area_per(a, b, c),',.1f'))
def area_per(a, b, c):
p = per(a,b,c)
s = p / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
return area
def per(a,b,c):
return a+b+c
main()
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
Trying to find the area of a triangle, the code is pretty simple but whenever I run the code nothing happens, not even the first line of print("width of the base").
print("width of the base")
width = input()
print("height")
height = input()
variable1 = width*height
area = variable1/2
print("area = {0}".format(area))
What you are doing will only work for a right angled triangle, regardless, i agree with #BuddyBoblll that you need to type a number.
Instead of using the (height*base/2) formula, you can use the Heron's formula, which will need only one or two additional lines of code. Furthermore, it will find area for all types of triangles, and is not restricted to right angled ones.
# Three sides of the triangle is a, b and c:
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
The output that i am getting for this code is:
Enter first side: 5
Enter second side: 12
Enter third side: 13
The area of the triangle is 30.00
Side note, i am working on mac osx on a Python 3.8.0 version.
I am creating a code for L & W in Python. However, after I enter the L & W that is asks me to enter, it just gives me an error of "too many values to unpack" but I do not know what I may be doing wrong!
def main():
l,w = input("Enter length and width:")
result = rectangleAP(float(l), float(w))
print("The area is", result[0])
print("The perimeter is", result[1])
def rectangleAP(length, width):
Area = length * width
Perimeter = (length + width) * 2
return [Area, Perimeter]
if __name__ == "__main__":
main()
The input() function returns a singular value, a string. However, you are trying to assign one value (the return value of input()) to two variables, l and w. So, you probably want to split the string at some delimiter using the str.split() method:
length, width = input("Enter length and width ('length,width')").split(",")
Alternatively, you could do two input() calls:
length, width = input("Enter the length:"), input("Enter the width:")
(Which could also be separated out into two lines.)
Taking input of length and width separately can help you,
As well as using .split() as suggest by #quamrana can also help to take input using a separator such as comma(',')
def main():
l = input("Enter length:")
w = input("Enter width:")
#or
#l,w = input("Enter length and width:").split(',')
result = rectangleAP(float(l), float(w))
print("The area is", result[0])
print("The perimeter is", result[1])
def rectangleAP(length, width):
Area = length * width
Perimeter = (length + width) * 2
return [Area, Perimeter]
if __name__ == "__main__":
main()
Closest thing to what your are trying to do:
As Jacob Lee said, input() only returns one value, and you are giving it 2 variables to unpack.
Answer:
l, w = input("length: "), input("width")
Write a program that contains ADD and AVERAGE user defined functions. On execution your program prompts for three numbers from user and call the AVERAGE function. Send the entered three numbers to AVERAGE function. The AVERAGE function call ADD function and send the three user entered numbers to it. The ADD function accepts the numbers from AVERAGE function and calculate sum. Send this sum value back to calling point (AVERAGE function). The AVERAGE function receive the sum value and calculates average for that sum of three numbers. The AVERAGE function send the average value to its calling point (outside of both functions). At the end display the average value from outside these functions.
The output should be:
a: 2
b: 3
c: 4
Average: 3.0
def add(a,b,c):
return a+b+c
def average(a,b,c):
d = add(a,b,c)
e = d/3
return e
f = average(2,3,3)
print(f)
Output:
f = 2.6666666666666665
Generic way of doing this :
def adder(num):
return sum(num)
def avg(*num):
return adder(num)/len(num)
print("Average: ",avg(1,2,3,4))
Now you can pass as much numbers as you want.
The best practice tactics will solve it, like;
n1 = int(input("Enter Number 1: " ))
n2 = int(input("Enter Number 2: " ))
n3 = int(input("Enter Number 3: " ))
def ADD(a,b,c):
return a+b+c
def AVERAGE(a,b,c):
X = ADD(a,b,c)
Y = X/3
return Y
F = AVERAGE(n1, n2, n3)
print(F)
Good luck!
Regards: Khairullah Hamsafar
I'm trying to figure a way to loop this code so that it restarts once all three of the calculations are complete. I have figured a way to restart the program itself, however I can't manage to restart it so that it returns back to the first calculation step. Anyone can help a brother out? Thanks in advance.
The code that I have used to restart the program:
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
answer = input("Do you want to restart this program?")
if answer.lower().strip() in "y, yes".split():
restart_program()
My program without the restart code:
import math
import sys
import os
print ("This program will calculate the area, height and perimeter of the Triangles: Scalene, Isosceles, Equilateral and a Right Angled Triangle.")
# calculate the perimeter
print ("Please enter each side for the perimeter of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
perimeter = (a + b + c)
print ("The perimeter for this triangle is: " ,perimeter)
# calculate the area
print ("Please enter each side for the area of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
s = (a + b + c) / 2
sp = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 #area = math.sqrt(sp*(sp - a)*(sp - b)*(sp - c))#
print ("The area for this triangle is %0.2f: " %area)
# calculate the height
height = area / 2
print ("The height of this triangle is: ", height)
You could put everything in a while loop which could repeat forever or until a user types a certain phrase.
import math
import sys
import os
print ("This program will calculate the area, height and perimeter of the Triangles: Scalene, Isosceles, Equilateral and a Right Angled Triangle.")
while True:
# calculate the perimeter
print ("Please enter each side for the perimeter of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
perimeter = (a + b + c)
print ("The perimeter for this triangle is: " ,perimeter)
# calculate the area
print ("Please enter each side for the area of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
s = (a + b + c) / 2
sp = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 #area = math.sqrt(sp*(sp - a)*(sp - b)*(sp - c))#
print ("The area for this triangle is %0.2f: " %area)
# calculate the height
height = area / 2
print ("The height of this triangle is: ", height)
or
while answer.lower() in ("yes", "y"):
//code
answer = input("Would you like to repeat?")
You could also put it all into a function def main(): and then do some form of recursion (calling a function in itself).
Those are just a few ways. There are a ton of ways you can get what you want.
Just Have the function loop on itself. Restarting the shell isn't necessary.
import math
import sys
import os
def calc():
print ("This program will calculate the area, height and perimeter of the Triangles: Scalene, Isosceles, Equilateral and a Right Angled Triangle.")
# calculate the perimeter
print ("Please enter each side for the perimeter of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
perimeter = (a + b + c)
print ("The perimeter for this triangle is: " ,perimeter)
# calculate the area
print ("Please enter each side for the area of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
s = (a + b + c) / 2
sp = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 #area = math.sqrt(sp*(sp - a)*(sp - b)*(sp - c))#
print ("The area for this triangle is %0.2f: " %area)
# calculate the height
height = area / 2
print ("The height of this triangle is: ", height)
if __name__ == "__main__":
answer = input("Do you want to restart this program?")
if answer.lower().strip() in "y, yes".split():
calc()
else:
exit()
calc()
If the answer is yes, then the function is called and everything repeats. If the answer is not yes then the program exits.
This should do.
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
while input("Do you want to restart this program?").lower().strip() in "y, yes".split():
restart_program()
I'm writing a code for my class but I'm having a little trouble at one part. I'm having the user input a number and then I need a loop to print specific statements based off the number the user inputted. So for example:
def main():
totalnumber = input("Enter the number of circles: ")
i = 0
for i in totalnumber:
i = 0 + 1
value = input("Enter the radius of circle",str(i)+":")
So I basically need the output to look like:
Enter the number of circles: 3
Enter the radius of circle 1:
Enter the radius of circle 2:
Enter the radius of circle 3:
I'm getting the error
TypeError: input expected at most 1 arguments, got 2
Is what I'm doing above okay to do or should I use a different approach?
If its okay what is wrong within my code that would be giving me that sort of error?
Try:
def main():
total_number = input("Enter the number of circles: ")
for number in range(1, int(total_number) + 1):
value = input("Enter the radius of circle {}: ".format(number))
main()
First: you need to convert the input to int, then iterate it by the number.
Notes:
use python pep-8 when naming your parameters user _ between the names
string formating is best with format try to use it.
Your for loop doesn't look correct.
Try
for number in range(int(totalnumber)):
i = number+1
value = input("Enter the radius of circle"+str(i)+":")