Integers
An integer is a whole number, positive or negative, without decimals, of unlimited length.
In the example above we assign the integer 42 to a variable called number. The variable can be used to
reference the integer later in the code.
Converting data types¶
When working with user input, you need to be aware of the data type that the input function returns. For example, the input()
function returns a string. In general, everything that comes from the user is a string. Including JSON, YAML, and other data
formats from APIs, databases, and files. But for now let's focus on user input.
interface_int = input("Input port number: ")
portchannel = interface_int + 100 # raises a TypeError!
The code above will raise a TypeError because the input() function returns a string.
Instead, we need to cast (convert) the input to an integer.
interface_str = input("Input port number: ")
interface_int = int(interface_str)
portchannel = interface_int + 100
Casting data types
For each data type, there are functions that can be used to convert the data type to another data type, if valid. The int()
function can convert a string to an integer, but it will raise a ValueError if the string is not a valid integer.
Etherchannel configuration generator¶
Let us create a more complete example that takes an interface number as input and generates the configuration for an Etherchannel interface across a stack of switches.
interface_int = int(input("Interface number (last whole number only): "))
portchannel = interface_int + 100
# the small `f` in front of the string marks this as an f-string (FORMATTING STRING)
configuration = f"""!
interface Port-channel{portchannel}
switchport mode trunk
!
interface GigabitEthernet1/0/{interface_int}
channel-group {portchannel} mode active
!
interface GigabitEthernet2/0/{interface_int}
channel-group {portchannel} mode active
!
"""
# output to screen
print(configuration)
As a network engineer, numbers are indeed important. Python has integers for whole numbers. But what about floating-point numbers? You'll have to wait, because the next sections is about lists.