I'm very new to python and I have one question. In this code,
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)
In the function definition of abc, I passed the variable names as a, b,c but I used them as x, y, z only and the output is also correct. Why this isn't showing any error? Is this correct?
It is not giving you an error, because you declared x
, y
and z
as global variables and those are being used in your abc()
function.
Inside abc()
, the variables x
, y
and z
are not local, but module-global.
If you put the rest of your code in another function, eg:
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)
And then call tryit()
, you'll get a NameError: name 'x' is not defined
on the first line of abc()
. That's because, this way, x
, y
and z
are not global, but local to the tryit()
function, so abc()
has no visibility to them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.