Python - Expressions and Operators (IV)

An expression in Python is a combination of values, variables, operators, and functions that, when evaluated, results in a single value. These expressions can be simple, like performing arithmetic operations, or more complex, involving nested expressions and functions. Expressions are crucial for writing efficient and readable code in Python, and they are used extensively in conditional statements, loops, and function calls.

In Python, 1 + 1 is called an expression, which is the most basic programming instruction in the language. An expression consists of values (such as 1) and operators (such as +) and they can always evaluate down to a single value.

1 + 1 evaluates down to a single value of 2. A single value with no operators is also considered an expression (it evaluates only to itself)

Explain this like I'm 5

In Python, when we talk about expressions, we're essentially discussing the way we tell the computer to do something with our data. Think of an expression as a simple instruction that combines things like numbers, text, or true/false values to produce a new result.

For example, the expression 1 + 1 tells Python to add two numbers together, which gives us 2. It's a straightforward way of giving the computer a small task, which it solves to give us an answer. And it's not just about numbers; we can mix together different types of data, like text (which we call "strings") or even decisions (true or false values, which we call "booleans").

Let's break down the types of expressions you'll use often:

  • Doing Math with Arithmetic Expressions: Just like in school, you can add (+), subtract (-), multiply (*), and divide (/) numbers in Python. For example, adding two numbers might look like sum = 3 + 5, which gives us 8.
  • Creating Text with String Operations: We can also put pieces of text together. If you have "Hello" and "World!", you can combine them into "Hello World!" using +.
  • Making Decisions with Boolean Expressions: Sometimes, we need to make choices based on certain conditions. For example, by comparing two values, we can decide if something is true or not, like is_equal = (5 > 3), which tells us True because 5 is indeed greater than 3.

Understanding Operators

Operators are just symbols or words that tell Python what kind of operation to perform on the data. Here are the basics:

  • Arithmetic Operators - Symbols like +, -, *, / do mathematical operations.
  • Comparison Operators - These help us compare values, with symbols like == (equals), != (not equals), > (greater than), and < (less than) telling us how two values relate to each other.
  • Boolean Operators - Words like and, or, not help us combine or modify true/false values.

Types of Expressions and Examples (I'm not 5 anymore)

Expressions in Python can be broadly categorized based on the operations they perform and the types of results they produce. Here, we'll explore some of the most common types of expressions, using simple examples.

Arithmetic Expressions

Arithmetic expressions perform mathematical operations like addition, subtraction, multiplication, and division. They are used with numeric data types (integers and floats) to calculate values.

# Calculating the sum of two numbers
sum = 7 + 3  # Evaluates to 10

# Multiplying two numbers
product = 4 * 5  # Evaluates to 20

String Operations

String expressions involve operations on strings (text data). The most common operation is concatenation, where two or more strings are joined together to form a new string.

# Concatenating strings
greeting = "Hello" + " " + "World!"  # Evaluates to "Hello World!"

print(greeting)

Boolean Expressions

Boolean expressions evaluate to either True or False. They are often used in conditions and involve comparison and logical operators.

# Comparing two values
is_equal = (10 == 10)  # Evaluates to True

# Using logical operators
is_valid = (5 > 3) and (10 < 12)  # Evaluates to True because both conditions are true

Basic Operators in Expressions

Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations as we've seen before.

Operator Operation Example Evaluates to
** Exponent 2 ** 3 8
% Modulus 16 % 3 1
// Integer division 16 // 3 5
/ Division 16 / 3 5.33
* Multiplication 3 * 2 6
- Subtraction 6 - 3 3
+ Addition 6 + 3 9

Comparison Operators

Comparison operators compare two values and return a Boolean value (True or False)

  • == Equal to - Checks if two values are equal.
  • != Not equal to - Checks if two values are not equal.
  • > Greater than - Checks if the left value is greater than the right value.
  • < Less than - Checks if the left value is less than the right value.
  • >= Greater than or equal to - Checks if the left value is greater than or equal to the right value.
  • <= Less than or equal to - Checks if the left value is less than or equal to the right value.

Please note comparison operators are very important and useful for Network Automation. For example, let's say I want to change the port descriptions on all the port that belongs to a specific VLAN 10. When you create your Python script, you would say something like "if VLAN == 10, description is USER-VLAN'. So, please take your time to practice this.

Boolean Operators

The following three Boolean operators can be used to compare Boolean values. Just like the comparison operators, they evaluate these expressions down to a Boolean value

  • and Returns True if both statements are True.
  • or Returns True if one of the statements is True.
  • not Reverses the result, returning False if the result is True.
Expression Evaluates to
True and True True
True and False False
False and True False
False and False False

Membership Operators

Membership operators test if a sequence is present in an object. The two membership operators are in and not in.

x = ["apple", "banana"]

print("banana" in x)  # True because "banana" is in the list x
print("cherry" not in x)  # True because "cherry" is not in the list x

Identity Operators

Identity operators check if two variables refer to the same object in memory. The two identity operators are is and is not.

x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is z)  # True because z is the same object as x
print(x is y)  # False because x and y are different objects with the same content
print(x is not y)  # True because x and y are not the same object
πŸ’‘
In Python, every object stored in memory has a unique identifier. The identity of an object is like its address in memory, and this is what the is operator compares. It's crucial to understand that identity comparison is not about the content of the objects, but whether they are the exact same object in memory.
  • The is operator checks for object identity, not equality. It's useful for determining if two variables point to the same object.
  • Use is not to check if two variables do not refer to the same object, ensuring that you are working with distinct entities.
  • Identity checks are crucial when your program logic depends on whether variables are pointing to the exact same instance of an object, especially in complex data structures and object-oriented programming.
  • From my personal experience, I don't really use this a lot.

Networking Examples

Let's see how we can apply these concepts in a simple networking scenario.

Imagine you're setting up a network and need to handle IP addresses as strings. You might use string expressions to format them or arithmetic expressions to calculate the number of hosts in a subnet.

# String expression for IP address formatting
subnet = "192.168.1."
host_id = 14
ip_address = subnet + str(host_id)  # Converts host_id to string and concatenates

print("IP Address:", ip_address)  # Outputs: IP Address: 192.168.1.14

# Arithmetic expression for calculating the number of hosts in a /24 subnet
subnet_mask = 24
hosts = 2 ** (32 - subnet_mask) - 2  # Calculates hosts in a subnet

print("Number of hosts:", hosts)  # Outputs: Number of hosts: 254

In this second example, we use arithmetic operators to calculate the total bandwidth required based on the number of users and bandwidth per user. Then, we use a comparison operator to check if the total bandwidth exceeds a predefined limit, and logical operators could be similarly applied to combine multiple conditions.

# Calculating the total bandwidth requirement
users = 50
bandwidth_per_user = 2.5  # in Mbps
total_bandwidth = users * bandwidth_per_user

print("Total bandwidth required:", total_bandwidth, "Mbps")

# Checking if the total bandwidth exceeds a certain limit
limit = 100  # Mbps
is_exceeding = total_bandwidth > limit

print("Is the bandwidth exceeding the limit?", is_exceeding)
πŸ’‘
Understanding basic operators and how expressions are evaluated is crucial for manipulating data and making decisions in your Python scripts. Experiment with these operators and the print() function to become more familiar with Python expressions and their outcomes.

Exercise

Task 1: Comparing Lists

  1. Create two lists with the same content, say list1 = [1, 2, 3] and list2 = [1, 2, 3], and a third list that is assigned the value of the first list, say list3 = list1.
  2. Use the identity operator is to compare list1 and list2, and then list1 and list3. Print the results.
  3. Reflect on why the results are different, considering how Python allocates memory for identical lists that are declared independently.

Task 2: Verify IP Address Match

Write a Python script that uses comparison operators to check if two IP addresses are the same or not. You'll print the result of the comparison directly.

Instructions:

  1. Assign two IP addresses to variables ip_address1 and ip_address2. For simplicity, let's use "192.168.1.1" for ip_address1 and "192.168.1.1" or "10.0.0.1" for ip_address2.
  2. Compare these IP addresses using the == operator and print the result. This will tell you if the IP addresses are the same.
  3. Additionally, compare the IP addresses using the != operator and print the result. This will indicate if the IP addresses are different.
Python - Flow Control (V)
In programming, flow control is all about making decisions in your code. It’s how you can tell your program to run different pieces of code based on certain conditions