[英]Confused about Functions
所以我目前正在為我的 python 編碼 class 做一個作業,我必須得到一個圓柱體的面積,我應該使用函數,所以它看起來更干凈,但我不太確定如何准確地完成我的作業從頭開始,我看了很多視頻,但似乎無法真正理解函數,我的代碼目前看起來像這樣,但是每當我運行我的代碼時,我都無法讓“def calc():”部分運行,請問我可以得到一些指示嗎?
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()
不需要那么多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()
在這種情況下,我將半徑設置為 3,將高度設置為 6。您需要定義變量。 然后它應該工作。 在這種情況下,我使用 numpy 來導入精確的 pi 變量。
您必須將calc()
function 放在info()
function 上方。 您必須實際調用calc()
function 它將返回圓柱體的面積。 我提供了下面的代碼,應該可以解決您的問題。 希望你看懂代碼!
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")
您在評論中提到您想要輸入多個氣缸並確定哪個是較大的——我認為您希望讓輸入氣缸的 function 返回氣缸本身,以便可以使用體積 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.")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.