Hello my friend,
We are slowly but surely start talking about more and more useful and interesting topics staying yet at a basic level. Today you will learn about variables in Python, as variables are obviously the basic building block of any tool.
Network automation training – boost your career
Don’t wait to be kicked out of IT business. Join our network automation training to secure your job in future. Come to NetDevOps side.
How does the training differ from this blog post series? Here you get the basics and learn some programming concepts in general, whereas in the training you get comprehensive set of knowledge with the detailed examples how to use Python for the network and IT automation. You need both.
What are we going to do today?
We will learn how to create and use in Python 3.8 several types of the variables such as:
- Numbers
- Strings
- Boolean
The different types of variables are used for the different purposes, that’s why the more variables’ type you know, the better code you can write. We must admit that this list of the variables isn’t complete. That is why in the next couple of blogposts you will see more new types in Python 3.8. However, from the network automation prospective these data types cover the vast majority of the necessary use cases.
Besides the variables, you will learn how to create a complex text strings using variables and fix texts and utilize them for printing or creation of new variables.
Why does it matter?
If your code doesn’t contain the variables in one or another shape or form, highly likely you can’t reuse it for other purposes without intense modifications. Variables give you a freedom to decouple the logic of your program from the actual values (e.g. textual or numerical data).
How are we doing that?
As usually, we start slowly with the script’s creation adding the data types one by one. For now, let’s create a new folder in our GitHub synchronised folder containing Python lessons:
1
2
3
4 $ cd CEX
$ mkdir 03
$ cd 03
$
Inside this folder we create a new file called variables.py, which we will work on in today’s blogpost:
1 $ touch variables.py && chmod a+x variables.py
Don’t forget, why we change the file’s permissions.
Regardless of the variable’s type, the assignment of the value to the variable in the Python is achieved using the following syntax: variable_name = value. There is no any specific character in front of the variable name, so you need to take the name you like and use that. In terms of the naming conventions, the following rules are applied:
- The variable’s name consists of small or capital Latin letters, digits and underscore character. All other characters are prohibited (especially dash).
- The first character in the variable’s name can be only letter or underscore (the latter is used typically in specific cases, so better to avoid).
- The variable’s name is a case sensitive, so pay attention to that.
Generally, it is recommended to create the names using the small letters and underscores. Let’s start with the examples.
#1. Textual data
In terms of the working with the network elements, or any applications, the string is one of the most popular data types. Perhaps, it is the most popular. Just think about the following examples: network functions hostnames, IPv4/IPv6 addresses, named of the routing policies, BGP neighbours, and so on. All of them are strings.
In terms of the string data in the Python, you must provide the value in single or double quotes:
1
2
3
4
5 $ cat variables.py
#!/usr/local/bin/python3.8
port_name = 'Ethernet1'
port_ip_address = '192.168.100.1'
If you have question to the first string, check the previous blogpost in CEX.
In this example we have created two variables:
- The variable port_name has value Ethernet1.
- The variable port_ip_address has value 192.168.100.1.
To verify the content of the variables, we use the print() function:
1
2
3
4
5
6
7 $ cat variables.py
#!/usr/local/bin/python3.8
port_name = 'Ethernet1'
port_ip_address = '192.168.100.1'
print(port_name, port_ip_address)
The previous session explains the print() function in-depth.
Let’s execute this script to see the content of the variables:
1
2 $ ./variables.py
Ethernet1 192.168.100.1
Hurray, you have created your first variables!
#2. Numerical data
In contrast to the string data, the value of the numerical data you don’t need to include in the quotes.
Actually, you can do that, but then the numerical data will be treated as a string, which sometimes is a desired logic.
Extending the initial example, we add some numerical variables:
1
2
3
4
5
6
7
8
9 $ cat variables.py
#!/usr/local/bin/python3.8
port_name = 'Ethernet1'
port_ip_address = '192.168.100.1'
port_speed = 10000
port_ip_prefix = 24
print(port_name, port_ip_address, port_speed, port_ip_prefix)
As you see, our print function got some more arguments to this input, as it now needs to show the values of more variables. Let’s execute the script once more:
1
2 $ ./variables.py
Ethernet1 192.168.100.1 10000 24
In the output of the function print there is no difference between the string or number.
#3. Boolean data
The Boolean is a specific data type, which has only one two values True or False. This is applicable to the cases, where there are no other shadows of grey: there is only black and white. For example:
- interface shutdown / no shutdown
- interface switchport / no switchport
- etc
In Python this data type is exactly like this: word True or False without the quotes:
1
2
3
4
5
6
7
8
9
10
11 $ cat variables.py
#!/usr/local/bin/python3.8
port_name = 'Ethernet1'
port_ip_address = '192.168.100.1'
port_speed = 10000
port_ip_prefix = 24
port_enabled = True
port_switch = False
print(port_name, port_ip_address, port_speed, port_ip_prefix, port_enabled, port_switch)
Verification is as follows:
1
2 $ ./variables.py
Ethernet1 192.168.100.1 10000 24 True False
By now you have mastered the basics of variables. You know how to create them and verify they have proper values. What’s next?
#4. Function format()
There is a sort of templating or text formatting tool, which is built-in in Python. This is fulfilled using the format() function. To better explain its operation, take a look on the example below:
1
2
3
4
5
6
7
8
9
10
11 $ cat variables.py
#!/usr/local/bin/python3.8
port_name = 'Ethernet1'
port_ip_address = '192.168.100.1'
port_speed = 10000
port_ip_prefix = 24
port_enabled = True
port_switch = False
print('Interface {} has an IP address {}/{}'.format(port_name, port_ip_address, port_ip_prefix))
And the execution of this Python’s script:
1
2 $ ./variables.py
Interface Ethernet1 has an IP address 192.168.100.1/24
Now we can provide the formal description of the format() function:
- It is provided in form ‘{}’.format(var_name), where {} defines the place, where var_name provided in arguments will be inserted.
- If there are multiple vars to be inserted, they are applied in a sequence format. E.g., the first {} will be related to the first variable inside format() arguments, second {} to the second variable and so on.
These two functions print() and format() are used together quite often to generate the meaningful reports. However, you can use format() separately as well to create a new string variable based on some others merged:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 $ cat variables.py
#!/usr/local/bin/python3.8
port_name = 'Ethernet1'
port_ip_address = '192.168.100.1'
port_speed = 10000
port_ip_prefix = 24
port_enabled = True
port_switch = False
print('Interface {} has an IP address {}/{}'.format(port_name, port_ip_address, port_ip_prefix))
port_ip = '{}/{}'.format(port_ip_address, port_ip_prefix)
print(port_ip)
Now, once we execute our script, we shall see the new variable port_ip created as a merger of two others:
1
2
3 $ ./variables.py
Interface Ethernet1 has an IP address 192.168.100.1/24
192.168.100.1/24
Well done, my friend! You have done first steps into the direction of becoming a network automation pro!
If you prefer video
If you prefer watching the video instead of reading blogpost, that is also wonderful. We value your time and want to create for you the best experience possible. Therefore, for all the blogposts associated with CEX series, we will record the video and post it to our YouTube channel.
And here is the video for this blogpost:
What else shall you try?
Programming is all around testing, trying, breaking and fixing the things. Try to do the following things to collect some more experience:
- Compose more complex constructions with format() function containing 4-5 variables in a single template.
- Apply math functions (+, -, /, *) to the variables (e.g. new_var = var1 + var2) and print the output of the newly generated variable.
Lessons in GitHub
You can find the final working versions of the files from this blog at our GitHub page.
Conclusion
Variables are one of the corner stones of the programming, so you need to collect as much experience as you can. Generally, you can find variables in any program, and all our next blogposts will be using the variables. Get stronger! Take care and goodbye!
Support us
P.S.
If you have further questions or you need help with your networks, I’m happy to assist you, just send me message. Also don’t forget to share the article on your social media, if you like it.
BR,
Anton Karneliuk