PYTHON · PYTHON FOR EVERYONE · CHAPTER 3

Basic types

Get to know Python's numbers, strings and booleans, and operate on them without surprises.

10 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: you already run scripts and store data in variables, but you don't know what kind of data each one holds or which operations it supports. Point B: by the end of this chapter, you'll tell integers, floats and complex numbers apart, operate on them without surprises, work with text strings and use booleans to compare values.

Variables, types and comments

Python's basic types fall into 3 families:

  • Numbers: integers like 48, floats like 37.5 and complex numbers like 50 + 3j.
  • Text strings: like "R1-Lima".
  • Booleans: True and False.

To store a value, you assign it to a variable with =. You don't declare the type: Python infers it from the value. The type() function tells you the type of each value.

hostname = "R1-Lima"      # a string (str)
ports = 48                # an integer (int)
cpu_usage = 37.5          # a float (float)
impedance = 50 + 3j       # a complex number (complex)
active = True             # a boolean (bool)
for value in (hostname, ports, cpu_usage, impedance, active):
    print(type(value))
<class 'str'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'bool'>

Don't worry about the for in the last 2 lines: it repeats the print for each value, and you'll see it in its own chapter. Compare this with Java, where you'd write String hostname = "R1-Lima"; and int ports = 48;. In Python, you don't write the type.

The example also introduces comments. Python ignores everything after # up to the end of the line. Comments explain the why behind your code to whoever reads it later, including you 6 months from now.

Integers

Integers (int) are numbers without decimals: positive, negative and zero. In Python 3, they have no size limit beyond your machine's memory. That's handy in networking: an interface's 64-bit counters or the number of IPv6 addresses fit with no trouble.

byte_counter = 2 ** 64
print(byte_counter)              # → 18446744073709551616
print(type(byte_counter))        # → <class 'int'>
print(2 ** 128)                  # → 340282366920938463463374607431768211456

Besides base 10, you can write integers in other bases with a prefix. For long numbers, you can separate digits with underscores, which Python ignores:

print(0o27, 0x17, 0b10111)       # → 23 23 23  (octal, hexadecimal, binary)
print(0o755)                     # → 493  (the rwxr-xr-x permissions)
print(1_000_000_000)             # → 1000000000
print(bin(23), oct(23), hex(23)) # → 0b10111 0o27 0x17
print(int("ff", 16), int("11000000", 2))  # → 255 192

The bin(), oct() and hex() functions convert an integer to text in another base. int() goes the other way if you give it the base. You'll use this to read MAC addresses or masks in binary.

Python 3.14 update. The original book distinguished 2 integer types: int, limited to 32 or 64 bits depending on the platform, and long, with unlimited precision and the L suffix (23L). In Python 3, only int exists, and it has no limit. Also, octals no longer start with a zero (027) but with 0o (0o27). The old form raises SyntaxError. The 0b binary prefix arrived with that same change (PEP 3127), and the underscore as a digit separator came with Python 3.6 (PEP 515).

Floating-point numbers (float)

Numbers with decimals are of type float. You write them with a dot, never a comma: 12.75. They also support scientific notation with e, which means “times 10 to the power of”:

import sys

latency = 12.75
print(type(latency))                # → <class 'float'>
print(0.1e-3)                       # → 0.0001  (0.1 × 10⁻³)
print(1.5e9)                        # → 1500000000.0
print(sys.float_info.max)           # → 1.7976931348623157e+308
print(sys.float_info.min)           # → 2.2250738585072014e-308

Under the hood, a float is an IEEE 754 double-precision number, just like C's double: 64 bits, with 1 for the sign, 11 for the exponent and 52 for the mantissa. That's why Python has no separate double type. sys.float_info shows you the exact limits.

That binary format can't represent many decimals exactly, such as 0.1. The result is a small inaccuracy that surprises you the first time:

from decimal import Decimal

print(0.1 + 0.2)                        # → 0.30000000000000004
print(0.1 + 0.2 == 0.3)                 # → False
print(Decimal("0.1") + Decimal("0.2"))  # → 0.3

It isn't a Python bug: it happens in almost every language. For measuring latency or CPU usage, float is good enough. If you need decimal accuracy, for example with money or bandwidth billing, use the standard library's decimal module.

Complex numbers

Complex numbers have a real part and an imaginary part. If you've never used them, you probably don't need them, and you can skip to the next section. They show up in electrical engineering and signal processing, for example when calculating impedance.

Python includes them out of the box with the complex type. The imaginary part takes the j suffix. Internally, it stores 2 float values: one for each part.

z = 2.1 + 7.8j
print(type(z))      # → <class 'complex'>
print(z.real)       # → 2.1
print(z.imag)       # → 7.8
print(abs(3 + 4j))  # → 5.0  (the magnitude)

Arithmetic operators

These are the operators you can use with numbers. For more advanced functions, such as roots or logarithms, there's the math module.

OperatorOperationExampleResult
+Addition3 + 25
-Subtraction4 - 7-3
-Negation-7-7
*Multiplication2 * 612
**Exponentiation2 ** 664
/Division7 / 23.5
//Floor division (rounds down)7 // 23
%Modulo (remainder)7 % 21

The modulo returns the remainder of the division: 7 divided by 2 is 3 with 1 left over, so 7 % 2 is 1. Floor division returns only the quotient, rounded down. The divmod() function gives you both at once.

print(7 / 2)          # → 3.5
print(6 / 3)          # → 2.0   (/ always returns a float)
print(7 // 2)         # → 3
print(3.5 // 2)       # → 1.0   (with a float, the result is a float)
print(-7 // 2)        # → -4    (rounds down, not toward zero)
print(divmod(7, 2))   # → (3, 1)
print(3 + 2.0)        # → 5.0

The last line shows a general rule. When you mix numeric types, Python converts the operands to the “wider” type: an integer with a float gives a float, and a float with a complex number gives a complex number.

Python 3.14 update. In the original book, 3 / 2 gave 1 because dividing 2 integers returned an integer. You had to write 3.0 / 2 or float(3) / 2 to get 1.5. In Python 3, / is always true division (3 / 2 gives 1.5) and // is floor division.

A practical example with subnets and links:

# How many addresses are in a /26?
host_bits = 32 - 26
addresses = 2 ** host_bits
print(addresses)            # → 64
print(addresses - 2)        # → 62  (usable hosts)

# Seconds to transfer 1 GB over a 100 Mbit/s link
seconds = (1 * 8 * 1000) / 100
print(seconds)              # → 80.0

# 200 devices on 48-port switches: full switches and leftover devices
print(200 // 48, 200 % 48)  # → 4 8

Bitwise operators

These operators work on the binary representation of integers, bit by bit. Many fields barely use them, but in networking they're the foundation of subnet masks.

OperatorOperationExampleResult
&and: 1 if both bits are 13 & 22
|or: 1 if either bit is 13 | 23
^xor: 1 if the bits differ3 ^ 21
~not: flips every bit~3-4
<<Left shift3 << 16
>>Right shift3 >> 11

In binary, 3 is 11 and 2 is 10. When you apply &, only the first bit is 1 in both, so the result is 10, which is 2. Shifting one bit to the left is the same as multiplying by 2; shifting right is dividing by 2 and dropping the remainder.

Why does ~3 give -4? Python represents negative numbers in two's complement, so flipping every bit of n gives -n - 1. To keep only 8 bits, combine it with & 255.

This is how a router calculates the network and broadcast of an address. Take the last octet of 192.168.10.77 with a /26 mask (255.255.255.192):

octet = 77
mask = 192
print(bin(octet), bin(mask))       # → 0b1001101 0b11000000
print(octet & mask)                # → 64   (network 192.168.10.64)
print(octet | (~mask & 255))       # → 127  (broadcast 192.168.10.127)
print(f"{octet:08b}")              # → 01001101

In practice, you'll use the ipaddress module to work with full addresses. Understanding the bits helps you know what it does under the hood.

Text strings

A string (str) is text inside single or double quotes. Both are equivalent; pick the one that saves you from escaping inner quotes.

description = 'Link to "core-01"'
print(description)                     # → Link to "core-01"
print("interface\tstatus\nGi0/1\tup")
Link to "core-01"
interface	status
Gi0/1	up

The backslash \ starts escape sequences: \n is a newline, \t is a tab and \\ is a literal backslash.

Raw strings

If you put an r before the string, Python doesn't interpret escape sequences. They're useful for Windows paths and, later on, for regular expressions.

print("C:\\configs\\r1.txt")      # → C:\configs\r1.txt
path = r"C:\configs\new.txt"
print(path)                       # → C:\configs\new.txt
print(len("\n"), len(r"\n"))      # → 1 2

Without the r, the \n in \new would turn into a newline. And \c, which isn't a valid escape, triggers a SyntaxWarning in Python 3.14.

Unicode text and bytes

In Python 3, every string is Unicode. Accented letters, ñ and any alphabet work without special prefixes. When you need the raw bytes, for example to send them over a socket, you convert the string with encode() and get a bytes object.

print(len("ñandú"))              # → 5
data = "ñ".encode("utf-8")
print(data, type(data))          # → b'\xc3\xb1' <class 'bytes'>
print(data.decode("utf-8"))      # → ñ
Python 3.14 update. The book used the u prefix (u"äóè") to create Unicode strings, because regular strings were bytes in Python 2. In Python 3, every str is already Unicode: the u prefix is accepted for compatibility, but it does nothing. For binary data, there's the bytes type, with the b prefix.

Multi-line strings

With triple quotes, single or double, a string can span several lines. Line breaks are kept, and you can use quotes without escaping them. It's ideal for configuration snippets:

config = """hostname R1-Lima
interface GigabitEthernet0/1
 description Link to "core-01"
 no shutdown"""
print(config)

Concatenate and repeat

The + operator joins strings, and * repeats a string as many times as the number says. Remember that Python doesn't mix text and numbers: convert them with str() or, better yet, use an f-string.

prefix = "Gi"
number = "0/1"
print(prefix + number)           # → Gi0/1
print("-" * 20)                  # → --------------------
print("VLAN " + str(10))         # → VLAN 10
vlan = 10
name = "users"
print(f"VLAN {vlan}: {name}")    # → VLAN 10: users

An f-string has an f in front and replaces each expression inside braces with its value. It's the recommended way to build text in modern Python; you'll study it in depth later.

Booleans, logical operators and comparisons

The bool type has only 2 values: True and False. They're the foundation of the decisions (if) and loops you'll see in the control flow chapter.

A curious detail: bool is a subclass of int, so True behaves like 1 and False like 0 in numeric operations. The documentation advises against relying on that, but it's worth knowing.

print(issubclass(bool, int))   # → True
print(True + True)             # → 2

Logical operators

OperatorQuestionExampleResult
andAre both a and b true?True and FalseFalse
orIs a or b true?True or FalseTrue
notIs a false?not TrueFalse

Comparison operators

Comparisons (relational operators) always return a boolean:

OperatorQuestionExampleResult
==Are a and b equal?5 == 3False
!=Are a and b different?5 != 3True
<Is a less than b?5 < 3False
>Is a greater than b?5 > 3True
<=Is a less than or equal to b?5 <= 5True
>=Is a greater than or equal to b?5 >= 3True

Don't confuse = (assign) with == (compare). Python also lets you chain comparisons, like in math. It's perfect for validating ranges, such as valid VLAN IDs:

vlan = 150
status = "up"
print(1 <= vlan <= 4094)               # → True
print(status == "up" and vlan != 1)    # → True
print(bool(0), bool(""), bool("R1"), bool(48))  # → False False True True
print("" or "no description")          # → no description

The last 2 lines show 2 ideas you'll use a lot. First: zero and the empty string count as false, and almost everything else counts as true. Second: and and or return one of their operands, not necessarily True or False. They also stop evaluating as soon as they know the result.

Challenge

Answer before you open the solution.

1. What do 7 / 2 and 7 // 2 return in Python 3.14?

3.5 and 3. / is always true division; // is floor division, rounded down.

2. How do you write the octal number 755 in Python 3?

0o755. The old form with a leading zero (0755) raises SyntaxError in Python 3.

3. Why is 0.1 + 0.2 == 0.3 False?

Because float is binary and inexact for many decimals. The sum gives 0.30000000000000004. For decimal accuracy, use the decimal module.

4. What's the value of 200 & 192? Hint: think of octet 200 with a /26 mask.

192. In binary, 200 is 11001000 and 192 is 11000000. The shared bits form 11000000: the network starts at .192.

5. What does print(r"Gi0\n1") show?

Gi0\n1, on a single line. The r prefix creates a raw string: the backslash isn't treated as an escape.

Key takeaways

  • The basic types are int, float, complex, str and bool; type() tells you which one a value has.
  • Integers have no size limit and support the 0b, 0o and 0x bases.
  • / always returns a float; // gives the integer quotient and % the remainder.
  • Bitwise operators (&, |, ^, ~, <<, >>) are the foundation of subnet masks.
  • Every string is Unicode; r"" turns off escapes and f"" inserts values.
  • Comparisons return booleans and can be chained: 1 <= vlan <= 4094.

In chapter 4, you'll group these values into collections: lists, tuples and dictionaries.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate