【问题标题】:Python: using different variable names in function definationPython:在函数定义中使用不同的变量名
【发布时间】:2020-12-04 12:49:34
【问题描述】:

我对 python 很陌生,我有一个问题。 在这段代码中,

def abc(a,b,c):
        s = x+y+z
        q=(x+y+z)/2
        a = (q*(q-x)*(q-y)*(q-z))**0.5
        return (s,a)
  

print("Enter sides of a triangle")
x = float(input("a: "))
y = float(input("b: "))
z = float(input("c: "))
if x+y>z and x+z>y and y+z>x :
        print("Triangle is valid")
        tuple = abc(x,y,z)
else:
        print("Triangle is invalid")
print("PERIMETER and AREA OF TRIANGLE", tuple)

在 abc 的函数定义中,我将变量名称传递为 a、b、c,但我只使用它们作为 x、y、z,并且输出也是正确的。为什么这没有显示任何错误?这是正确的吗?

【问题讨论】:

  • 因为您忽略了您的参数,而是使用了全局变量。

标签: python python-3.x function


【解决方案1】:

这不会给您错误,因为您将 xyz 声明为全局变量,并且这些变量正在您的 abc() 函数中使用。

【讨论】:

    【解决方案2】:

    abc() 内部,变量xyz 不是本地的,而是模块全局的。

    如果您将其余代码放在另一个函数中,例如:

    def tryit():
        print("Enter sides of a triangle")
        x = float(input("a: "))
        y = float(input("b: "))
        z = float(input("c: "))
        if x+y>z and x+z>y and y+z>x :
                print("Triangle is valid")
                tuple = abc(x,y,z)
        else:
                print("Triangle is invalid")
        print("PERIMETER and AREA OF TRIANGLE", tuple)
    

    然后调用tryit(),你会在abc()的第一行得到一个NameError: name 'x' is not defined。这是因为,这样一来,xyz 不是全局的,而是 tryit() 函数的本地函数,因此 abc() 对它们不可见。

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多