variable name in python code example

Example 1: how to use a string variable as a variable name in python

#works only inside classes
name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

Example 2: python variable

string = 'string'
integer = 5
boolean = True

Example 3: Use variables in python

x = 'Welcome'
print(x)

Example 4: python use variable name as variable

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>

Example 5: python how to write a variable

stringtext = 'lol' #One version of a string
stringtext2 = "xD" #You can also use quotes.
integer = 2 #An integer
float = 4.5 #A float
boolean = True #Can be True or False

Tags:

Sql Example