Learning Python

Working with variables

No programs works without variables to store data values in while the program runs. Variables in Python are strong dynamically typed which mean you can change a variable from a number to a string by assignment, but a variable will not become a number when a string contains a number for example. This also means you may have to cast variable from a number to a string in some cases or vice versa.

The basics about variables

Let start with basic example based on our Hello World. application where we have two lines. And in this example we still present print directly with a string telling about two people called John and their age.

def main():
    print("My name is John and I am 42.")
    print("My name is John and I am also 42.")

Output:

My name is John and I am 42.
My name is John and I am also 42

Lets put the name and age both in their own variable as a string and update the strings to concatenate the whole string together. Here we that Python used the +-sign to concatenate strings together.

def main():
    name = "John"
    age = "42"
    print("My name is " + name + " and I am " + age + ".")
    print("My name is " + name + " and I am also " + age + ".")

Output:

My name is John and I am 42.
My name is John and I am also 42
def main():
    name = "John"
    age = "42"
    print("My name is " + name + " and I am " + age + ".")
    name = "Jack"
    print("My name is " + name + " and I am also " + age + ".")

Output:

My name is John and I am 42.
My name is Jack and I am also 42

Different data types

Python has the following data types built-in by default, in these categories:

Category Data type
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

Casting variables

Python is flexible with its data types for variables, but Python does require type casting in some cases. Using a variable that contains a number that needs to concatenated with a string needs to be casted from an integer to a string. In the example below we forget to type cast a string and it fails.

def main():
    name = "John"
    age = 42
    print("My name is " + name + " and I am " + age + ".")

Output:

Traceback (most recent call last):
  File "/workspaces/python-examples/v03.py", line 10, in <module>
    main()
  File "/workspaces/python-examples/v03.py", line 6, in main
    print("My name is " + name + " and I am " + age + ".")
TypeError: can only concatenate str (not "int") to str

If we type cast the variable age from integer to string with the str() function it works perfectly. Other functions to type cast are int() and float().

def main():
    name = "John"
    age = 42
    print("My name is " + name + " and I am " + str(age) + ".")

Getting a variable type

Python can also determine the data type of a variable with type(). This can become useful when importing data from unknown source and needs validation.

def main():
    name = "John"
    age = 42
    print(type(name))
    print(type(age))

Output:

<class 'str'>
<class 'int'>

Variable scope

Variables are scope sensitive and in the example below we define the variable on a global level and can be read scopes of functions and methods. Having global variables isn’t a good idea as it leads to messy programming. For constants this is fine, but the variables should only be read from and not updated.

#!/usr/bin/env python3

phrase = "Hello World."

def main():
    print(phrase)


if __name__ == "__main__":
    main()

Output:

Hello World.

Variables can have a global and local scope. In the example below we set the variable on a global level, but override it with a different value as a local variable/

#!/usr/bin/env python3

phrase = "Hello World."

def main():
    phrase = "Hello People."
    print(phrase)


if __name__ == "__main__":
    main()

Output:

Hello People.

Python also has the option to turn local variables in global variables as in the example below. The extra function setup() uses the keyword global to make the variable x a global variable.

#!/usr/bin/env python3

phrase = "Hello World."

def setup():
    global phrase
    phrase = "Hello People."


def main():
    print(phrase)


if __name__ == "__main__":
    setup()
    main()

Output:

Hello People.

Using global variables is considert bad programming and a risk as it can have unforeseen effects.