Skip to main content

Variables

Variables in Python are dynamically typed.  So what exactly does this mean?  In other languages you would first define a variable and assign it a type.  This type may be an integer, double, float, or string.  In Python you can define a variable name and immediately assign it a value.  The type of the variable doesn't matter to the programmer or the code unless you explicitly define that requirement.

A variable's scope however is important.  For instance, you can define a variable's name and assign it a value anywhere in your code however, if it's defined within a function, method, class, module or a package, it's scope is limited to within that respective location.  You can not access a variable defined within a function from outside the function.

# Defining a variable and it's scope

someVar = 0  # This variable can be accessed by anything within this script

# Some random function
def someFunction():
  someOtherVar = 1.0  # This variable can only be accessed within this function
  

# Some random class
 class someClass:
    """A Simple class to show variables"""
  yetAnotherVar = 'some string value'  # This variable can be accessed by anything within the class
  
  # Some random method which is a function within a class
  def someMethod(self):
    """Method contained within a class"""
    andAnotherVar = False  # This variable is only accessable within the method 'someMethod'