Hi all very new hear I have just started to learn python, unfortunately, my knowledge is very very basic so I was asked to create a BMI inside a function this is what I have so far the error I receive when trying to run the code is weight is not defined here is my code thanks in advance
def bmi(height, weight):
height = int(input("Input your height in meters: "))
weight = int(input("Input your weight in kilogram: "))
result = (weight + height)
return result
print("Your body mass index is: ", round(weight / (height * height), 2))
In your original code the height and weight variables exist only within the scope of the bmi function while your last print statement is outside the scope of said function.
A simple fix would be to put the last print before the return like so:
def bmi():
height = int(input("Input your height in meters: "))
weight = int(input("Input your weight in kilogram: "))
result = (weight + height)
print("Your body mass index is: ", round(weight / (height * height), 2))
return result
Since you had two parameters in your bmi function you could restructure your code to retain the origin function definition:
def bmi(height, weight):
result = (weight + height)
print("Your body mass index is: ", round(weight / (height * height), 2))
return result
def main():
height = int(input("Input your height in meters: "))
weight = int(input("Input your weight in kilogram: "))
result = bmi(height, weight)
...
Related
This function to calculate the area of a rectangle is not very readable. Can you refactor it, and then call the function to calculate the area with base of 5 and height of 6? Tip: a function that calculates the area of a rectangle should probably be called rectangle_area, and if it's receiving base and height, that's what the parameters should be called.
def f1(x, y):
z = x*y # the area is base*height
print("The area is " + str(z))
My Error:
def rectangle_area (x, y):
area = 5*6 # the area is base*height
print("The area is " + str(area))
(Python) - Code Style
The Answer:
def rectangle_area(base, height):
area = base*height
print("The area is " + str(area))
rectangle_area(5,6)
Accurate Answer :
given by the question base =5 and height=6
Python code Style :-
def rectangle_area(base,height):
area = base*height # the area is base*height
print(f"The area is :{str(area)}")
rectangle_area(5,6)
Output :-
The area is : 30
def rectangle_area(base, height):
area = base * height
print("The area is "+ str(area))
rectangle_area(5,6)
The code will be:
def rectangle_area(base,height):
area = base*height
return area
base = float(input("Enter the base length of the rectangle : "))
height = float(input("Enter the height of the rectangle : "))
print("The area is ",rectangle_area(base,height))
Then the output will be:
Enter the base length of the rectangle : 5
Enter the height of the rectangle : 6
The area is 30.0
I am trying to solve an issue when two rectangles intersect/overlap each other. when this happens, i want to know if intersection is True or False. I found a solution, however it is written in C or C++. I want to write these code in Python.
Here is the source: http://www.jeffreythompson.org/collision-detection/rect-rect.php
This is literally the first line of python code I've ever written (I do know C++ however)
def rectRect(r1x, r1y, r1w, r1h, r2x, r2y, r2w, r2h):
# are the sides of one rectangle touching the other?
return r1x + r1w >= r2x and \ # r1 right edge past r2 left
r1x <= r2x + r2w and \ # r1 left edge past r2 right
r1y + r1h >= r2y and \ # r1 top edge past r2 bottom
r1y <= r2y + r2h # r1 bottom edge past r2 top
IMHO rectRect is a really bad name for the function, I kept it from the linked code however.
Following is simple class that can perform both rectangle-rectangle intersection as well as point to rectangle intersection. The difference between earlier solution is that following snippet allows even detection of rotated rectangles.
import numpy as np
import matplotlib.pyplot as plt
class Rectangle:
def __init__(self, center: np.ndarray, dims: np.ndarray, angle: float):
self.corners = self.get_rect_points(center, dims, angle)
self.area = dims[0] * dims[1]
#staticmethod
def get_rect_points(center: np.ndarray, dims: np.ndarray, angle: float):
"""
returns four corners of the rectangle.
bottom left is the first conrner, from there it goes
counter clockwise.
"""
center = np.asarray(center)
length, breadth = dims
angle = np.deg2rad(angle)
corners = np.array([[-length/2, -breadth/2],
[length/2, -breadth/2],
[length/2, breadth/2],
[-length/2, breadth/2]])
rot = np.array([[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]])
corners = rot.dot(corners.T) + center[:, None]
return corners.T
def is_point_in_collision(self, p: np.ndarray):
"""
check if a point is in collision with the rectangle.
"""
def area_triangle(a, b, c):
return abs((b[0] * a[1] - a[0] * b[1]) + (c[0] * b[1] - b[0] * c[1]) + (a[0] * c[1] - c[0] * a[1])) / 2
area = 0
area += area_triangle(self.corners[0], p, self.corners[3])
area += area_triangle(self.corners[3], p, self.corners[2])
area += area_triangle(self.corners[2], p, self.corners[1])
area += area_triangle(self.corners[1], p, self.corners[0])
return area > self.area
def is_intersect(self, rect_2: Rectangle):
"""
check if any of the four corners of the
rectangle is in collision
"""
if not np.all([self.is_point_in_collision(c) for c in rect_2.corners]):
return True
return False
def plot_rect(p1, p2, p3, p4, color='r'):
ax.plot([p1[0], p2[0]], [p1[1], p2[1]], color)
ax.plot([p2[0], p3[0]], [p2[1], p3[1]], color)
ax.plot([p3[0], p4[0]], [p3[1], p4[1]], color)
ax.plot([p4[0], p1[0]], [p4[1], p1[1]], color)
mid_point = 0.5 * (p1 + p3)
plt.scatter(mid_point[0], mid_point[1], marker='*')
plt.xlim([-1, 1])
plt.ylim([-1, 1])
Following are two samples:
Sample 1:
ax = plt.subplot(111)
st = Rectangle((0.067, 0.476),(0.61, 0.41), 90)
gripper = Rectangle((-0.367, 0.476),(0.21,0.16), 45)
plot_rect(*st.corners)
plot_rect(*gripper.corners)
plt.show()
print(f"gripper and rectangle intersect: {st.is_intersect(gripper)}")
Sample 2:
ax = plt.subplot(111)
st = Rectangle((0.067, 0.476),(0.61, 0.41), 90)
gripper = Rectangle((-0.167, 0.476),(0.21,0.16), 45)
plot_rect(*st.corners)
plot_rect(*gripper.corners)
plt.show()
print(f"gripper and rectangle intersect: {st.is_intersect(gripper)}")
I just wrote up a program to ask the user to calculate the area, circumference, and the diameter of a circle based on a radius input. However, I'm stumped on how to ask which calculation they want to make between the 3 choices. which is step 1. I have completed 2-4 steps. Any help on this one? (I.e. Only allow them to make one calculation per run of the program) The bolded area is obviously what I tried and failed miserably at....
**Radius = float(input("What type of calculation would you like to
make? "))
if 1 = "area"
elif: 2 = "circumference"
else: 3 = "diameter"
return("num")**
PI = 3.14
radius = float(input(' Please Enter the radius of a circle: '))
area = PI * radius * radius
circumference = 2 * PI * radius
print(" Area Of a Circle = %.2f" %area)
print(" Circumference Of a Circle = %.2f" %circumference)
import math
circumference = float(input(' Please Enter the Circumference of a
circle: '))
area = (circumference * circumference)/(4 * math.pi)
print(" Area Of a Circle = %.2f" %area)
import math
diameter = float(input(' Please Enter the Diameter of a circle: '))
area1 = (math.pi/4) * (diameter * diameter)
# diameter = 2 * radius
# radius = diameter/2
radius = diameter / 2
area2 = math.pi * radius * radius
print(" Area of Circle using direct formula = %.2f" %area1);
print(" Area of Circle Using Method 2 = %.2f" %area2)
As per your requirement that to get calculate area, circumference and diameter of circle based on radius input and to make one calculation per one run with choice selected.
I have made a sample/example code for you!
import math
def CalculateArea(radius):
# r = float(input('Enter the radius of the circle :'))
area = math.pi * radius * radius
return area
def CalculateCircumference(radius):
circ = 2 * math.pi * radius
return circ
def DiameterOfCircle(radius):
return radius * 2
radius = input('Enter Radius: ')
radius = float(radius)
choice = input(" Enter 1 to get Area \n Enter 2 for Circumference \n Enter 3 for Diameter! \n")
if choice is '1':
print("Area of the circle is : %.2f" % CalculateArea(radius))
elif choice is '2':
print("Circumference of circle is: ", CalculateCircumference(radius))
elif choice is '3':
print("Diameter of circle is: ", DiameterOfCircle(radius))
else:
print("Wrong Input!")
I hope this helps you! :)
I can't get this to run correctly, and I have to use 3 functions with their purposes being those of which I have them set to.
def lw():
l = input("Enter the length of your rectangle: ")
w = input("Now enter the width of your rectangle:")
return l, w
def ap():
l,w = lw()
area = l * w
perimeter = 2*1 + 2*w
return area, perimeter
def main():
area,perimeter = ap()
print("With a length of", l ."and a width of", w)
print("the area of your rectangle is", area)
print("the perimeter of your rectangle is", perimeter)
if __name__ == "__main__":
main()
This should work
def lw():
l = input("Enter the length of your rectangle: ")
w = input("Now enter the width of your rectangle:")
return l, w
def ap():
l,w = lw()
area = l * w
perimeter = 2*1 + 2*w
return l, w, area, perimeter
def main():
l,w,area,perimeter = ap()
print("With a length of", l ,"and a width of", w)
print("the area of your rectangle is", area)
print("the perimeter of your rectangle is", perimeter)
if __name__ == "__main__":
main()
I've made two changes: passing l and w in ap() function and accessing them in main() function.
Heyo,
I can see a number of issues with your code:
The first print statement in your main function seems to be calling variables that don't exist within that function's scope. You'll need to return the values of l and w from ap() in addition to area and perimeter. There's also a slight typo in the parameters of this statement (a . where a , should be).
Your perimeter calculation is a bit off. It's multiplying 2 by 1 instead of 2 by l, rendering l useless.
The inputs your code is requesting only returns string values rather than numerical ones. You'll need to pass those into either an int() or float() and return the results of those functions if you want to be able to calculate anything.
Does anyone know why I keep getting this error? I'm really new and I'd appreciate someone's help. This is my code:
import turtle as t
import math as m
import random as r
raindrops = int(input("Enter the number of raindrops: "))
def drawSquare():
t.up()
t.goto(-300,-300)
t.down()
t.fd(600)
t.lt(90)
t.fd(600)
t.lt(90)
t.fd(600)
t.lt(90)
t.fd(600)
t.lt(90)
def location():
x = (r.randint(-300, 300))
y = (r.randint(-300, 300))
t.up()
t.goto(x, y)
return x, y
def drawRaindrops(x, y):
t.fillcolor(r.random(), r.random(), r.random())
circles = (r.randint(3, 8))
radius = (r.randint(1, 20))
newradius = radius
area = 0
t.up()
t.rt(90)
t.fd(newradius)
t.lt(90)
t.down()
t.begin_fill()
t.circle(newradius)
t.end_fill()
t.up()
t.lt(90)
t.fd(newradius)
t.rt(90)
while circles > 0:
if x + newradius < 300 and x - newradius > -300 and y + newradius < 300 and y - newradius > -300:
t.up()
t.rt(90)
t.fd(newradius)
t.lt(90)
t.down()
t.circle(newradius)
t.up()
t.lt(90)
t.fd(newradius)
t.rt(90)
newradius += radius
circles -= 1
area += m.pi * radius * radius
else:
circles -= 1
return area
def promptRaindrops(raindrops):
if raindrops < 1 or raindrops > 100:
print ("Raindrops must be between 1 and 100 inclusive.")
if raindrops >= 1 and raindrops <= 100:
x, y = location()
area = drawRaindrops(x, y)
area += promptRaindrops(raindrops - 1)
return x, y, area
def main():
t.speed(0)
drawSquare()
x, y, area = promptRaindrops(raindrops)
print('The area is:', area, 'square units.')
main()
t.done()
I'm assuming something is wrong with the "+=" but I have no idea what. I'm fairly certain that the area is correctly being returned. Help please. :)
Two things I noticed:
1. promptRaindrops returns a tuple
I am sure you didn't intend this, but when you say area += promptRaindrops(raindrops - 1), you are adding a tuple to area, which is an integer. To fix this, you should say area += promptRaindrops(raindrops - 1)[2] to get the area returned. However, your error is generated by
2. Your base case doesn't return a value
In promptRaindrops, you return a recursive call of the function whenever 1 <= raindrops <= 100. But, when it is outside that range, it returns nothing, only prints a message. Your function will always be outside of that range, because if you keep decreasing the value passed in to promptRaindrops, it will eventually go below 1. When it does, you return None (since you didn't return anything). That None bubbles up through every single recursion call made to that point, and you will inevitably be adding None to area. Add a return statement returning a tuple, and your error should vanish.
In promptRaindrops() you perform a += operation with a recursive call to promptRaindrops() which will not return anything (NoneType) if raindrops is outside the given range.
Depending on how the program should behave, either something should be returned there or it should not be called with values outside the given range.