使用函数计算

2024-05-29 11:53:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我对此有点困惑。你知道吗

我有一个函数。在该函数中,它会问很多问题,其中一个问题是基于他们拥有的花园数量的以下问题-因此,如果他们说他们有2个花园,它会问这个问题两次,并且应该在计算中加上100两次:

gardens = int(input("How many gardens do you have: "))

    def gard():

    calc = 0

    gardener = input("Do you need a gardener? Y or N ")
    if gardener == "Y" or gardener == "y":
        calc = calc + 100
    else:
        calc = calc + 0

for i in range(gardens):
    gard()

我如何保持函数外的运行总计?当我把print(calc)放在函数中时,每次他们说Y时它只显示100,但不加在一起。你知道吗


编辑以包含更新的代码:

eMake部分(IF语句)返回一个值—但它只在最后返回计算中的第一个值?你知道吗

由于有大量的ws,所以也很难做区域部分。它只存储变量的最后一个值。你知道吗

noGard = int(input("Enter number of gards which require cleaning: "))

#Defining variables
Calc = 0
Area = 0
emCalc = 0

#Room information
def GInfo():

    global Calc
    global Area

    gName = input("Enter gard name: ")
    noW = int(input("How many w are in the "+gName + "? "))

    #Repeats the questions for each W
    for i in range(noW):
        Height = float(input("What is the w height of in metres? "))
        Width = float(input("What is the w width in metres? "))
        Area = Height * Width

    #Asks if w needs to be removed
    w = input("Does w need removing? Y or N ")
    if w == "Y" or w == "y":
        Calc = Calc + 70
    else:
        Calc = Calc + 0
    print (" ")

    #Returns the values
    return Calc
    return Area

#Calculate Sarea

#Identifying e
def e():

    global emCalc

    #eMake
    eMake = input("What make of e - HH or NN? ")
    if eMake == "HH" or "hh":
        emCalc = emCalc + 200
    elif eType == "NN" or "nn":
        emCalc = emCalc + 50
    else: print("You have entered an invalid e make")

    #Returns the values
    return emCalc

#Repeats the g information questions for each g
for i in range(noGard):
    GInfo()
# Runs the E function
e()

#Print total without VAT
total = Calc + emCalc
print(total)
print(Area)

Tags: orthe函数inforinputifcalc
3条回答

函数应该返回计算值。你知道吗

def gard():
   ...
   return calc

total = 0
for _ in range(gardens):
    total += gard()

print 'Total: ', total

函数的全部要点,实际上,就是它们接受参数和返回值。(有些语言,虽然不是Python,但将执行此操作的函数称为“过程”。)

这就是您在这里需要做的:您的gard函数需要返回calc的值。您可能不希望实际在函数本身内部进行加法,但是如果您这样做了,您还需要接受calc的当前值作为参数,您将从for循环传入该参数。你知道吗

函数in the strictest sense没有状态。在编写函数程序时,通常要保持它们的函数pure,这意味着函数的结果只依赖于它的输入,不会引起明显的副作用。你知道吗

但是Python并不是一种纯粹的函数式语言。它是一种object-oriented过程语言,将函数建模为对象,对象可以是有状态的。所以你可以做你想做的事,如果你不把“功能”这个词看得太过字面的话。你知道吗

正确的事情™你知道吗

创建一个类,对数据及其操作进行建模:

>>> class F(object):
...     def __init__(self):
...             self.x = 0
...     def f(self):
...             self.x += 1
...             return self.x
...
>>> my_f = F()
>>> my_f.f()
1
>>> my_f.f()
2

有趣和顽皮的方式

向函数对象添加状态,利用函数体在函数被调用之前不会执行的事实:

>>> def f():
...     f.x += 1
...     return f.x
...
>>> f.x = 0
>>> f()
1
>>> f()
2

如果要透明地执行此操作(即,使其在定义后不必立即将此状态添加到函数),可以通过让函数创建函数来关闭状态:

>>> def g():
...     def func():
...             func.x += 1
...             return func.x
...     func.x = 0
...     return func
...
>>> f = g()
>>> f()
1
>>> f()
2

更进一步,创建一个decorator,这样在定义函数之后就不必执行任何赋值:

>>> def with_x(func):
...     func.x = 0
...     return func
...
>>> @with_x
... def f():
...     f.x += 1
...     return f.x
...
>>> f()
1
>>> f()
2

或者您可以使用global让函数引用其本地范围之外的内容,而不利用函数是对象的事实:

>>> x = 0
>>> def f():
...     global x
...     x += 1
...     return x
...
>>> f()
1
>>> f()
2
>>> x
2

为您的编辑更新

既然你用的是global,我先给你提一个好问题来解释globalUsing global variables in a function other than the one that created them

至于你的特殊问题:

The eMake section (the IF statement) returns a value - but it only ever returns the first in the calculation at the end?

当然,这里有几个问题,其中一个对于初学者来说是很常见的。or的优先级高于==,因此您的条件解析如下:

if (eMake == "HH") or ("hh"):

这一直吸引着人们。在Python中,如果一个值不是布尔值,并且您将它放在一个条件语句中,那么它将使用一系列truthiness规则作为布尔值进行计算。在本例中,一个非空字符串被认为是True,所以您基本上是说if (eMake == "HH") or True。你知道吗

要解决此问题,请解决条件的右侧:

if (eMake == "HH") or (eMake == "hh"):

顺便说一下,您可能是指elif (eMake == "NN") or (eMake == "nn"):而不是elif eType == "NN" or "nn":,因为您从未定义过eType(出于上述原因),如果您在那里键入nn,您将得到一个异常。你知道吗

Also struggling to do the area section since there are numerous ws. It only stores the last value for the variable.

这是因为您使用Area = Height * Width重复赋值给同一个变量。因为Areaglobal,所以每次调用GInfo()时它都是相同的变量。如果它不是global,那么每次调用函数时它都是一个新变量,但是需要返回它并将返回值赋给一个变量才能保存该值。否则,它将消失,因为它从来没有分配给任何东西。你知道吗

现在,我不知道你想用你计算的面积做什么。你想把它们分开还是加在一起?你知道吗

如果要将它们分开,则需要使用数据结构。在本例中,您肯定希望使用list。使用列表的^{}方法,可以向列表中添加一个项。所以它看起来像这样:

areas = []    # empty list

def GInfo():
    global areas
    # the stuff before the loop
    for i in range(noW):
        Height = float(input("What is the w height of in metres? "))
        Width = float(input("What is the w width in metres? "))
        areas.append(Height * Width)
    # the stuff after the loop

如果要将它们相加,只需确保将每个单独的面积计算添加到上一个结果中,就像对Calc所做的那样:

Area += Height * Width

还有一件事:GInfo()函数只返回Calc,不返回Area。函数只能返回一个值。在数学意义上,函数是两个集合之间的many-to-one映射。因此在Python中,函数以return语句结束。在那之后就没有其他人被处决了。你知道吗

为了从GInfo()的返回值中获得Calc的值和Area的值,您必须返回data structure。通常这是一个tuple。你知道吗

return (Calc, Area)

但是您的代码不会将返回值GInfo()赋给任何对象。相反,它使用global声明来更改全局变量的值。所以不应该有这里有个问题。你知道吗

相关问题 更多 >

    热门问题