Python Variables

Variables

Instead of running a script, where I define each IP address as the 4 octets decimal representation we all know, using a variable allows me to define a variable called “ip_address” for example and change the value of it independently from changing the script.

1	ip_address = "172.16.10.1"
2	print(ip_address)
3	full_config = ("ip_address" + ip_address + "255.255.255.0")
4	print(full_config)

When I run my script, I will get 2 lines printed:

  1. 172.16.10.1
  2. ip address 172.16.10.1255.255.255.0

Variables comes in different types. In this example, we list 3 variables a, b & c and find out which type of variables they are, by using “type”

1	a = 3
2	b = 5.2
3	c = "router"
4	print(type(a))
5	print('############')
6	print(type(b))
7	print('############')
8	print(type(c))
9	print('############')

The result is printed and shows

  • a is an integer
  • b is a float
  • c is a string
<class 'int'>
############
<class 'float'>
############
<class 'str'>
############

Mixing variables

There instances when you may need to concatenate variables which are strings with others which are integers. This will not be possible and some formatting will be needed.

For example, in below script, “a” is an integer and “b” a string. My end result should be a print output of ” I have 3 routers”. However since I am mixing integers and strings, this will not work.

1 a = 3
2 b = " routers"
3 print ('I have ' + str(a) + b)

The correct way is to modify the integer to be treated as a string. This is achieved by simply changing the code from +a+b to str(a)+b as per below.

String Formatting

A more elegant and flexible way to print strings is to use the formatting option. Using the same above example, I will rewrite my code.
You will notice variables are written as they are, but inside “{}” and I am making use of f” at the beginning of my line to be printed.

1 a = 3
2 b = " routers"
3 #print ('I have ' + str(a) + b)
4 print(f"I have {a} {b}")

Here is another example of using variables and making use of print formatting.

#testing variables in Python
Router_type = "ASR9K"
SW_version = "6.4.2"
Number_Of_Nodes = 15

My_Network = f"Our network is made of {Number_Of_Nodes} {Router_type} running S/W image {SW_version}"
print(My_Network)

#Output:
Our network is made of 15 ASR9K running S/W image 6.4.2

Python crash course video

To learn more about Python for Engineers, watch this 1hr crash course video.
This course covers foundation topics:

  • Installing Python

  • Starting on Visual Studio Code

  • Hello World

  • Variables

  • Print and formatting

  • Built-IN method

  • Lists

  • Dictionaries

  • Working with files

  • Functions

  • Conditionals & Loops

  • Interacting with network devices