This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I am very new to Python and I have written my first code to calculate the area of shapes. Each time I run it on Jupyter, it says
Type Error.
where I got things wrong? (I am using Python 3).
# Calculator code for the area of the shape
print("1 rectangle")
print ("2 squared")
print ("3 circle")
shape = input (">> ")
if shape ==1:
length = input ("What is the length of the rectangle?")
breadth = input ("What is the breadth of the rectangle?")
area = length * breadth *2
print ("the area of your rectangle", area)
elif shape == 2:
length = input ("what is the length of one side of the squared")
area = length *breadth
print ("the area of your square is ", area)
else shape ==3:
radius = input ("what is the radius of your circle")
area = radius *radius*3.14
print ("area of your circle is ", area)
You have some things wrong in your code:
You have not provided any type to your input. Replace it with float for better calculation.
You have written the wrong syntax of else. See the documentation
You have calculated the area of square wrongly.
Try below code:
print("1 rectangle")
print("2 squared")
print("3 circle")
shape = input (">> ")
if shape == 1:
length = float(input ("What is the length of the rectangle?"))
breadth = float(input ("What is the breadth of the rectangle?"))
area = length * breadth *2
print ("the area of your rectangle", area)
elif shape == 2:
length = float(input ("what is the length of one side of the squared"))
area = length * length
print ("the area of your square is ", area)
else:
radius = float(input ("what is the radius of your circle"))
area = radius *radius*3.14
print ("area of your circle is ", area)
Hope this answers your question!!!
Related
This is what I have to do; "Assume that you have the coordinates (x,y) of four points p1, p2, p3, and p4. Write a function name
check_is_square() that asks the user for the coordinates of those four points (total of eight integer inputs) and prints the message Yes – it is a Square if those four points can form a square on the coordinate plane and the message No – it is not a square otherwise. Call check_is_square()from the main() function."
This is the code I have currently;
import math
def check_square(x1,x2,y1,y2):
if (math.sqrt((x1 - x2)**2+(y1-y2)**2) % 2 == 0):
print("Yes - it is a square")
else:
print("No - it is not a square")
def main():
x1 = int(input("Enter coordinate 1: "))
x2 = int(input("Enter coordinate 2: "))
y1 = int(input("Enter coordinate 3: "))
y2 = int(input("Enter coordinate 4: "))
check_square(x1,x2,y1,y2)
main()
So I'm currently doing an assignment for my python coding class and I have to get the area of a cylinder and I'm supposed to be using functions so it looks cleaner, but I'm not so sure how to exactly do my assignment from scratch, I've watched a lot of videos but can't really seem to understand functions, my code looks like this currently, but whenever I run my code I can't get the "def calc():" part to run, could I get some pointers please?
def info():
r = float(input("What is the radius of the cylinder? "))
h = float(input("What is the height of the cylinder? "))
print("The cylinders area is", area)
def calc():
pi = 22/7
area = ((2*pi*r) * h) + ((pi*r**2)*2)
return pi, area
info()
Don't need so many funcatin .
def info():
r = float(input("What is the radius of the cylinder? "))
h = float(input("What is the height of the cylinder? "))
calc(r,h)
def calc(r,h):
pi = 22/7
area = ((2*pi*r) * h) + ((pi*r**2)*2)
print("The cylinders area is", area)
info()
in this case I put the radius as 3 and height as 6. You need to define you variables.
Then it should work. in this case I used numpy to import an exact pi variable.
You have to put the calc() function above the info() function. You have to actually call the calc() function which will return the area of cylinder. I have provided the code below which should solve your problem. Hope you understand the code!
def calc(r, h): # Calculates the area of cylinder
pi = 22/7
area = ((2*pi*r) * h) + ((pi*r**2)*2)
return area
def info(): # Takes the radius and height from user.
r = float(input("What is the radius of the cylinder? "))
h = float(input("What is the height of the cylinder? "))
return f"The area is {calc(r, h)}"
# r = 5
# h = 10
print(info())
# using parameters in functions instead of inputs:
def info2(r, h):
return f"The area is {calc(r, h)}"
r = 5
h = 10
print(info2(r, h))
# Comparing areas of cylinders
area1 = calc(5, 10)
area2 = calc(10, 15)
if area1>area2: #Area1 is greater than Area2
print("Area1 is greater than Area2")
elif area2>area1: #Area2 is greater than Area1
print("Area2 is greater than Area1")
else: #Both are equal
print("Both are equal")
You mentioned in a comment that you wanted to input multiple cylinders and determine which was the larger one -- I think for that you want to have your function that inputs a cylinder return the cylinder itself so that it can be compared using the volume function.
from dataclasses import dataclass
from math import pi
#dataclass
class Cylinder:
radius: float
height: float
name: str
def volume(c: Cylinder) -> float:
return (2*pi*c.radius) * c.height + (pi*c.radius**2)*2
def input_cylinder(name: str) -> Cylinder:
r = float(input(f"What is the radius of the {name} cylinder? "))
h = float(input(f"What is the height of the {name} cylinder? "))
return Cylinder(r, h, name)
if __name__ == '__main__':
cylinders = [input_cylinder(name) for name in ('first', 'second')]
for c in cylinders:
print(f"The {c.name} cylinder's volume is {volume(c)}")
print(f"The bigger cylinder is the {max(cylinders, key=volume).name} one.")
This question already has answers here:
Print Combining Strings and Numbers
(6 answers)
Closed 2 years ago.
I'm a very beginner and know only the very basic syntax. I am trying to make a circumference calculator, with the user inputting the radius. This is what I have right now, but I want to be able to have a text answer like "The circumference of this circle is ____". Right now I can only output the answer.
rad = input("Enter the radius of circle: ")
radius = float(rad)
circumference = 2 * 3.14 * radius
print(circumference)
Python 3
Use f-string to format result:
rad = input("Enter the radius of circle: ")
radius = float(rad)
circumference = 2 * 3.14 * radius
print(f'The circumference of this circle is {circumference}')
Python 2
Format string:
rad = input("Enter the radius of circle: ")
radius = float(rad)
circumference = 2 * 3.14 * radius
print('The circumference of this circle is {0}'.format(circumference))
Another Option: Concatenating String Directly
Less elegant, yet still works:
rad = input("Enter the radius of circle: ")
radius = float(rad)
circumference = 2 * 3.14 * radius
print('The circumference of this circle is ' + str(circumference))
You can use
print(f"The circumference of this circle is {circumference}")
But also you do not want to use 3.14 for pi. You can do
import math
and then use math.pi for a more accurate number.
#Python program when involved with maths
import math
def areaOfcircle(x):
#Calculate the area
area=(math.pi)*math.pow(x,2)
print(area,"is the area of your circle")
#Input used to find x
areaOfcircle(int(input("What is the radius of your circle?")))
def areaOftriangle(b,h):
area=(b+h)/2
print(area,"is the area of your triangle")
areaOftriangle(int(input("What is the base of your triangle")),int(input("What is the hight of your triangle")))
def areaOfsquare(x):
area=math.pow(x,2)
print(area,"is the area of your square")
areaOfsquare("What is the length of your square?")
flag="f"
while flag=="f":
shape=input("Which of the following shapes, Circle, Triangle or Square do you want to calculate the area of: ")
if shape=="Triangle" or "triangle":
area=areaOftriangle
print(area)
elif shape=="Square" or "square":
area=areaOfsqaure
print(area)
elif shape=="Circle" or "circle":
area=areaOfcircle(x)
print(area)
Im feeling in the mood today. I fixed your code to the desired functionality you require. :)
Mainly, you have multiple errors.
1) indentation error with your elifs.
2) argument passing error with area=areaOfcircle(x).
3) areaOfsquare("What is the length of your square?") is trying to pass a string and calculate the string.
4) Design-wise, you should be asking user input for shape first before asking for measurements.
5) if shape=="Triangle" or "triangle": should be changed to if shape.lower() == 'triangle':
import math
def areaOfcircle(x):
area=(math.pi)*math.pow(x,2)
print(area,"is the area of your circle")
def areaOftriangle(b,h):
area=(b+h)/2
print(area,"is the area of your triangle")
def areaOfsquare(x):
area=math.pow(x,2)
print(area,"is the area of your square")
flag="f"
while flag=="f":
shape=input("Which of the following shapes, Circle, Triangle or Square do you want to calculate the area of: ")
if shape.lower() == "triangle":
areaOftriangle(float(input("What is the base of your triangle? ")),float(input("What is the height of your triangle? ")))
break
elif shape.lower() == "square":
areaOfsquare(float(input("What is the length of your square? ")))
break
elif shape.lower() == "circle":
area=areaOfcircle(float(input("What is the radius of your circle? ")))
break
else:
print('No such shape, please try again')
I'm trying to make this program in Python which asks for the surface area and volume of a cylinder. At the end, it asks the user if it wants to calculate volume/surface area. However, if they do type in Yes, nothing happens. What is wrong with my code?
Secondly, I tries using math.pi but it didn't work, what should I do.
The code is long so only scroll down to the important parts:
print("Welcome to the volume and surface area cylinder calculator powered by Python!")
response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")
if response=="vol" or response =="SA":
pass
else:
print("Please enter a correct statement.")
response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")
if response=="vol":
#Below splits
radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
volume = PI*radius*radius*height
decimal_places = int(input("How many decimal places do you want it to?: "))
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))
verify = input("Do you want to find out the surface area (type in Yes or No): ")
verify = verify.capitalize
if verify == "Yes":
radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
SA = int(2)*PI*radius*radius+int(2)+radius*radius*height
decimal_places = int(input("How many decimal places do you want it to?: "))
print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))
if verify == "No":
pass
if response =="SA":
#Below splits
radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
SA = int(2)*PI*radius*radius+int(2)+radius*radius*height
decimal_places = int(input("How many decimal places do you want it to?: "))
print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))
verify = input("Do you want to find out the volume (type in Yes or No): ")
verify = verify.capitalize
if verify == "Yes":
radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
volume = PI*radius*radius*height
decimal_places = int(input("How many decimal places do you want it to?: "))
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))
if verify == "No":
pass
You replaced verify with a method:
verify = verify.capitalize
This'll never match either 'Yes' or 'No' because it is no longer a string. Call the method instead:
verify = verify.capitalize()
Note that your test for "No" can just be dropped, there is little point in testing for a string then just passing.
Using math.pi instead of PI otherwise works just fine:
>>> import math
>>> math.pi
3.141592653589793
>>> radius, height = 32, 15
>>> 2 * math.pi * radius ** 2 + 2 * math.pi * radius * height
9449.910701998098
>>> math.pi * radius ** 2 * height
48254.86315913922
This is my tweaked version. It avoids a lot of repetition.
from math import pi
print("Welcome to the volume and surface area cylinder calculator powered by Python!")
response = raw_input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ").lower()
while response not in ["vol", "sa"]:
print("Please enter a correct statement.")
response = raw_input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ").lower()
radius, height = [float(part) for part in raw_input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
r2 = radius ** 2
SA = 2 * pi * r2 + 2 + pi * radius * height
volume = pi * r2 * height
decimal_places = int(raw_input("How many decimal places do you want it to?: "))
if response=="vol":
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))
verify = raw_input("Do you want to find out the surface area (type in Yes or No): ")
if verify.lower() == "yes":
print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))
if response =="sa":
print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))
verify = raw_input("Do you want to find out the volume (type in Yes or No): ")
if verify.lower() == "yes":
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))