简体   繁体   中英

How can I call only one variable in multi variable function?

I am trying to learn Python3 and I think I confused my self with the coding. Lets say I have a function using different variables.

How can I call just a single variable from it? how can I just print x value outside of function?

Basically I want to get the value of X in the function where I am going to use it outside of function, especially when there is lots of variables in the function.

thank you in advance.

def calculation():
  x = 0
  y = 1
  a = x * y
  b = x + y + y
  print(a)
  print(b)
  return x, y

print("testing")
print(calculation(x))

when I try to run this code it came back with a name error.

>Traceback (most recent call last):
  >>File "test.py", line 15, in <module>
    >>>print(calculation(x))

>NameError: name 'x' is not defined

Use the global keyword. This allows the variable to be used outside of the function it's defined in. However, you do have to call the function before you can use the variable(s) it defines, so you may have to modify your call to calculation .

def calculation():
  global x
  x = 0
  y = 1
  a = x * y
  b = x + y + y
  print(a)
  print(b)
  return x, y

A different way is to simply assign the first value calculation returns to a different variable, like this:

print("testing")
x, y = calculation()
print(x)

if I understand your question correctly (based on "how can I just print x value outside of function?")

x,y=calculation()
print(x)

if you don't care about the second reply you can also

x,_=calculation()
print(x)

Note that you don't have to name your external variables the same as the ones inside your function ie

a,_=calculation()
print(a)

would also work

You can make your print statements like:

print("testing")
print(calculation()[0])

Output:

testing
0
2
1

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.

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