繁体   English   中英

对函数感到困惑

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM