pythontest automation

Python for test automation: variables

Variables are fundamental components used to store and manipulate data. They serve as placeholders for values that can change during the execution of a program. Think of variables as labeled containers that hold different types of information, such as numbers, text, or other more complex data structures. When a variable is created, it is allocated a specific memory location in the computer's memory, allowing the program to access and modify its value as needed. In essence, variables provide a way to store, retrieve, and manipulate data within a program, making them an essential concept to understand.

Dynamic typing

In Python variables are dynamically typed, meaning variables do not have an inherent data type. Instead, the type of a variable is determined by the value it holds. This allows for flexibility, but requires careful consideration to avoid unexpected behavior. The language supports type hinting, which tells us what type of variable is expected for example as a function argument. Python does not enforce these types, but using type hinting is a really good habit to get into, so we will be utilizing type hinting at all times.

Variable assignment

In Python specifically, assigning variables is done by using the = operator:

x = "hello"

Here we assign the string (or text) hello to the variable x. We can later refer to x to access the value. For example, we can use the built-in print function to display the variables value in the command line:

x = "hello"
print(x)
>>>hello

Variable naming

We name variables with a few guidelines in mind:

  • variables should be lowercase
  • words are separated by an underscore _: my_variable
  • variable names should be descriptive, but consice
  • for example loop variables can have really short name, even a single character, because they are used only within the loop
for i in range(10):
    ...

Variable scope

Variables in Python have scope, which determines where in the code they are accessible. Variables defined inside a function have local scope, while variables defined outside any function have global scope. Python also supports nonlocal variables within nested functions.

def my_function():
    x = "hello"
    print(x)

print(x)  # x is not available here because it was defined
          # in the local scope of my_function, therefore this
          # call will raise an exception

However, loop variables are available outside of the loop scope:

for i in range(10):
    print(i)

print(i)  # here i will have the last value that was
          # assigned to it by the loop: 9

Variable mutation

Python variables can hold mutable or immutable objects. Mutable objects, such as lists and dictionaries, can be modified after creation, while immutable objects, such as strings and tuples, cannot be modified.