Home Python Course #2: Variables and Primitive Datatypes for Absolute Beginners
Post
Cancel

Python Course #2: Variables and Primitive Datatypes for Absolute Beginners

After you have written your first Python Hello World program (find the article over here: Python Lesson 1: Your First Python Program (Complete Beginners Guide) ) it is time to talk about variables in Python and programming languages in general.

What are variables?

Variables in computer programs are used to store, manipulate and label data. You can imagine a variable as a container labeled with a specific name. Inside this container is your data which can be a text, a number, or even more complex things. When you store data in a variable you can retrieve it at later stages in your program by stating the variable name.

The following program shows how to store, retrieve and change data in a variable:

1
2
3
4
5
6
7
8
if __name__ == "__main__":
    a = 42
    b = 23
    c = a * b
    print("c:", c)
    a = 89
    print("a:", a)
    print("c:", c)
  • In line 2 42 is stored in variable a, and in line 3 23 is stored in variable b. Storing data in a variable is also called assigning a value to a variable. When assigning a variable in Python you use = on the left-hand side of the equal sign is the variable name and on the right-hand side is the value you want to assign the variable. In other programming languages such as C or Java, you might have to declare a variable before you can assign a value to it. However, Python tries to keep things simple, and therefore you don’t need to declare variables.

  • In line 4 you see another variable assignment; however, the value of variable c is not explicitly stated. The value assigned to c is the result of a multiplied by b. And here, you can see how to retrieve a value from a variable; you just type the variable name.

  • The print(...) statement in line 5 first prints the text c:, followed by the data stored in the variable, which again shows that you access the data stored in a variable by using its name in a statement.

  • Throughout a program, the value assigned to a variable can be changed as often you like. In line 6 a is assigned to 89, and the former assignment 42 is discarded. However, this assignment does not change the value stored in c because c stores the result of the calculation when a stored the value 42, and c does not store the calculation itself.

When you run this program, you will see the following output:

1
2
3
c: 966
a: 89
c: 966

which shows that c was not modified when a new value was assigned to a .

Naming variables

Now is the time to talk about naming variables. Naming things in computer science and programming is one of the most challenging tasks. A variable name should precisely describe what a variable contains. Make sure to pick your variable names such that someone else or yourself can understand what they represent after you haven’t looked at your code for some time.

British Shorthair Cat If you want to store information on your pet, your code and variable names could look like this:

1
2
3
4
5
6
7
8
9
10
11
if __name__ == "__main__":
    species = "cat"
    breed = "british shorthair"
    color = "chocolate"
    name = "Mr. Fluffers"
    sex = "male"
    age_years = 7
    weight_kg = 6.1
    favorite_toy = "plush mouse"
    favorite_food = "tuna"
    sleeping = True

In this code example, you can see that all variable names represent what is stored in those variables. Secondly, you see that different types of data are stored. In line 7 the age in years is stored in age_years as an integer number. However, the weight in kg in weight_kg is a decimal number and in line 11 sleeping represents a state that is either True or False. All the other variables are text. Extend your program with the following lines and run it:

1
2
3
4
    print(name, "is a", sex, breed, species)
    print(name, "has a", color, "color, is", age_years, "years old, and weights", weight_kg, "kgs")
    print(name, "loves to eat", favorite_food, "and enjoys playing with a", favorite_toy)
    print("Is", name, "sleeping?", sleeping)

This is another example of how you can access the values stored in variables and generate text blocks with them. However, there are some rules about naming variables:

  • A variable name must start with a letter or an underscore _
  • A variable name can’t start with a number.
  • A variable name can only contain the following characters A-Z, a-z, 0-9, and _
  • Variable names are case-sensitive, which means cat, Cat, and CAT are different variables.
  • A variable name can’t be a reserved keyword of the Python language, for which you can find a complete list over here: Python Reserved Keywords

Comments

Precise variable names are one crucial way to improve the readability of your code. But even more critical are comments. Comments are statements in your code that aren’t executed. If you want to insert a comment that fits in one line in Python, start the line with a # (called pound sign or hash). For example, you can add a comment in front of the print statements that clarifies what is being printed.

1
2
3
4
5
    # prints text block describing your pet
    print(name, "is a", sex, breed, species)
    print(name, "has a", color, "color, is", age_years, "years old, and weights", weight_kg, "kgs")
    print(name, "loves to eat", favorite_food, "and enjoys playing with a", favorite_toy)
    print("Is", name, "sleeping?", sleeping)

If you want to add a comment that spans over multiple lines, write your comment between two triple quotes """ like this:

1
2
3
4
5
6
7
8
if __name__ == "__main__":
    """
    This program stores the data of your pet
    and generates a text block describing your pet
    """
    species = "cat"
    breed = "british shorthair"
    color = "chocolate"

You can also use comments to temporarily disable (comment out) certain parts of your code. This is extremely useful if you got an error in your code and can’t directly pinpoint the source of the error. For example, you could comment out parts of the variable assignments and parts of the text blocks using single- and multi-line comments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
if __name__ == "__main__":
    """
    This program stores the data of your pet
    and generates a text block describing your pet
    """
    species = "cat"
    breed = "british shorthair"
    color = "chocolate"
    name = "Mr. Fluffers"
    sex = "male"
    age_years = 7
    weight_kg = 6.1
    """
    favorite_toy = "plush mouse"
    favorite_food = "tuna"
    """
    sleeping = True

    # prints text block describing your pet
    print(name, "is a", sex, breed, species)
    print(name, "has a", color, "color, is", age_years, "years old, and weights", weight_kg, "kgs")
    #print(name, "loves to eat", favorite_food, "and enjoys playing with a", favorite_toy)
    print("Is", name, "sleeping?", sleeping)

In this code, your pet’s favorite toy and food is commented out with a multi-line comment, and the last print statement is commented out using a single-line comment. When you now run the code, you can see that the previous print statement isn’t showing up in the command line output. But be aware that if you comment out a variable assignment and later want to use this variable, your program will probably fail or give the wrong output.

Data types

In the above examples, you have seen how to store and retrieve integer numbers, decimal numbers, text, and true or false statements. Those four represent the primitive data types of Python:

  • Integer int are all integer numbers: 1, -2304, 0, etc.
  • Float float are all decimal numbers: 23.5, -0.52, 3525.252, etc. (the name float is derived from how a computer stores such decimal numbers I will discuss in another article soon).
  • String str are all single letters and texts: "a", "This is a text. And another sentence.", etc.
  • Boolean bool is a either True or False.

In other programming languages like C or Java, the type of a variable has to be stated explicitly, and a variable can only store data of that type. However, Python is a dynamically typed programming language in which the type of a variable doesn’t have to be explicitly stated. The type of a Python variable is decided (or inferred to sound extra fancy) when a value is assigned to a variable. You can check and print the type of a variable by using type(...). By extending your program storing information on your fluffy friend with the following will show the data type of the variables species, age_years, weight_kg, and sleeping:

1
2
3
4
    print(type(species))
    print(type(age_years))
    print(type(weight_kg))
    print(type(sleeping))

which will result in an output including the following lines:

1
2
3
4
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

Converting (casting) data types

Values of different data types can also be converted into others. The technical term for converting a value of one data type to another is casting. Casting an int into a float in Python almost always happens implicitly, so you don’t have to write any code to make the cast happen. You can run the following code snipped in the Python interactive mode:

1
2
3
4
5
6
a = 1
b = 2
c = a/b
type(a)
type(b)
type(c)

The variables a and b are integers because the numbers assigned to those variables don’t include a decimal point. The variable c results from a divided by b which is 1/2 = 0.5 which is a real number and therefore stored as a float. When using type(...) for all three variables, you can see a and b are int, and c is a float.

1
2
3
<class 'int'>
<class 'int'>
<class 'float'>

Implicit casts also work when combining booleans and numbers. In computer science the values for True and False are usually abbreviated with 1 and 0, where 1 represents True and 0 stands for False. Due to this you can include booleans in calculations:

1
2
3
4
5
6
7
8
9
10
t = True
f = False
i = 10
i_t = 10 * t
i_f = 10 * f
type(t)
type(f)
type(i)
type(i_t)
type(i_f)

In the example above, the booleans t and f are cast to int when used in the multiplications that are stored in i_t and i_f, and this results in i_t and i_f also being of type int:

1
2
3
4
<class 'bool'>
<class 'bool'>
<class 'int'>
<class 'int'>

You can even merge string and int. When you multiply a variable of type str with an int the result is a string that repeats itself. In the example below you can see this behavior:

1
2
3
4
5
6
7
l = "a"
x = 10
s = l * x
s
type(l)
type(x)
type(s)

l which contains "a" is multiplied by x = 10 which results in the string s = "aaaaaaaaaa".

1
2
3
4
'aaaaaaaaaa'
<class 'str'>
<class 'int'>
<class 'str'>

But you don’t have to, and in most programming languages, you shouldn’t rely on implicit casts because bugs resulting from those implicit casts are very hard to find. And therefore, explicit casts exist. An in accordance with the Zen of Python explicit is better than implicit. And for those reasons you should always use explicit casts to improve the readability of your code. The explicit casts available for the primitive Python data types are pretty easy to remember because they are named after the data types:

  • int(...) to cast a variable into an integer,
  • float(...) to cast a variable into a float,
  • str(...) to cast a variable into a string,
  • bool(...) to cast variable into a boolean.

Integers, floating-point numbers and booleans can be cast into any other data type due to the fact they are all represented as a number internally:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
i = 10
float(i)
str(i)
bool(i)

f = 23.42
int(f)
str(f)
bool(f)

b = True
int(b)
float(b)
str(i)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# i
10.0
'10'
True

# f
23
'23.42'
True

# b
1
1.0
'True'

However, casting str into an int or float won’t work because there is no obvious one-to-one relation between texts and numbers. Therefore a string can only be cast into bool while an empty string ("") will result in False and any other string will result in True:

1
2
3
4
e = ""
s = "This is a string"
bool(e)
bool(s)
1
2
False
True

Casting variables into different data types concludes this article. You have learned what variables are, how to assign values to variables, how to retrieve the stored data from a variable, what Pythons primitive data types are, and how to convert data types into each other using casts. I encourage you to play around with the things you learned because trying things out yourself is one of the best ways of learning. If you have any questions about this article, feel free to join our Discord community to ask them over there.

This post is licensed under CC BY 4.0 by the author.