Calling function teething variable

Asked

Viewed 51 times

0

How I call a variable created outside a function within a Python function For example:

variavel=2

def test():
   variavel=variavel+1
   if variavel==3:
      print(variavel)
test()
  • 3

    In Python the variables already declared are visible within the scope of the function for reading, however. The best thing you can do is declare the variables you want to use as arguments of the function, def test(val2):print(var2) and indicate the variable already declared as argument of this: test(variavel).

  • i didn’t understand...

  • @Giovanninunes edited the code for you to understand what I want to do

  • @bfavaretto I fixed

  • Now the code is different than what I had seen. As @Giovanninunes said, the outside variables would be visible for reading, but at the time you try to do attribution there needs to be a local variable - which you did not declare, so the error. It would be better to receive an argument and return a value.

  • @bfavaretto then. There is no way to "call" this variable inside the function without declaring it inside the function?

  • Has how, if you declare the variable as global within the function. But in general it’s a bad choice to do this. I suggest you read the manual (in EN): https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html

  • the global only works if it is declared within the function?

Show 3 more comments

2 answers

1

You could do:

def test(variavel):
   variavel=variavel+1
   if variavel==3:
      print(variavel)

test(2)

0


you can pass your variable as function parameter:

variavel=2

def test(variavel):
   variavel=variavel+1
   if variavel==3:
      print(variavel)

test(variavel)

I noticed that you are starting in python, so explaining what I did, instead of you accessing your variable within the function, you will pass a variable so that the function works with it. So your function will not try to access anything that is out of its "reach". I hope I’ve helped!

  • ENTEDIIII!! Damn man, big help,!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.