Ok, maybe this is a bit of a dumb question, but my intention is to call for a variable of a function using another variable, something along this lines:
def fun():
var1 = 100
var2 = 'asdasd'
var3= 24+30
x = fun()
print(x.var1)
To which I get the error mentioned in the title, is there a way to make something like this work?
btw, working with python 3.9, if that helps.
>Solution :
Functions on their own don’t have this functionality the way you implemented it. However, there are at least 3 ways to achieve what you need (in no particular order):
1. Use scopes
Read: https://realpython.com/python-scope-legb-rule/
@quamrana gives a good TL;DR of this in their answer.
You can declare a variable in the global scope and have the function change its value.
var1 = 0
def fun():
global var1
var1 = 100
var2 = 'asdasd'
var3= 24+30
x = fun()
print(var1)
2. Create a class (lots of learning involved)
Read: https://docs.python.org/3/tutorial/classes.html
Your variables can be part of a class, and you can then use that to instantiate an object. Your function (known as a method in this case) can then modify those variables (typically called properties), and you can access those.
These concepts are the core of a paradigm called object-oriented programming, which is a concept central to Python.
class Test_class:
def fun(self):
self.var1 = 100
self.var2 = 'asdasd'
self.var3 = 24+30
test_object = Test_class()
test_object.fun()
print(test_object.var1)
3. Return the values
This is dependent on the concepts of scopes from above.
Functions can return values when control is passed back to the context calling them. With Python, you can return multiple values (using a data structure like a tuple), and choose which one to index.
def fun():
var1 = 100
var2 = 'asdasd'
var3= 24+30
return var1, var2, var3
x = fun()
print(x[0])
Any bolded term in this answer is a Googleable keyword you can use to better understand what I’m saying.