In this section, youโll learn how to perform calculations, make decisions, and repeat actions using Python’s core control flow tools โ essential for scripting and test automation.
๐ฏ Learning Objectives
- โ Master arithmetic, comparison, and logical operators
- โ Understand assignment and bitwise operators
- โ
Learn conditional statements (
if
,elif
,else
) - โ
Practice with loops (
for
,while
) - โ Apply operators and control flow to test automation scenarios
โ Arithmetic Operators in Python
Arithmetic operators are used to perform basic math operations in Python. These are fundamental when writing calculations, evaluating test values, or working with counters and loops.
Operator | Symbol | Description | Example |
---|---|---|---|
Addition | + |
Adds two numbers | x + y |
Subtraction | - |
Subtracts one from another | x - y |
Multiplication | * |
Multiplies two numbers | x * y |
Division | / |
Divides (float result) | x / y |
Modulus | % |
Remainder of division | x % y |
Floor Division | // |
Division, rounded down | x // y |
Exponentiation | ** |
Power of a number | x ** y |
๐งช Examples
x = 10
y = 3
print(x + y) # 13 โ addition
print(x - y) # 7 โ subtraction
print(x * y) # 30 โ multiplication
print(x / y) # 3.333... โ division (always returns float)
print(x % y) # 1 โ remainder when 10 is divided by 3
print(x // y) # 3 โ floor division (no decimals, rounded down)
print(x ** y) # 1000 โ 10 raised to the power of 3
๐ก When Are These Useful?
+
,-
,*
,/
โ Useful in general calculations, totals, and averages%
โ Often used to check even/odd (x % 2 == 0
), or for cycle logic//
โ Useful when you want an integer result (e.g., pagination, row/column division)**
โ Great for power-based formulas like squaring (x ** 2
) or exponentials (2 ** 3
)
๐งฎ Comparison Operators in Python
Comparison operators are used to compare two values. They always return a Boolean value: True
or False
.
These are essential when writing conditional logic โ especially for validating test results, user input, or control flow in automation.
Operator | Symbol | Description | Example | Result |
---|---|---|---|---|
Equal to | == |
Checks if two values are equal | 5 == 5 |
True |
Not equal to | != |
Checks if values are not equal | 5 != 3 |
True |
Greater than | > |
Checks if left is greater than right | 7 > 4 |
True |
Less than | < |
Checks if left is less than right | 3 < 2 |
False |
Greater or equal | >= |
Left is greater than or equal to right | 5 >= 5 |
True |
Less or equal | <= |
Left is less than or equal to right | 2 <= 5 |
True |
๐ก Where Are These Useful?
Comparison operators are widely used in Python โ especially in decision-making and testing logic.
โ In Conditionals
age = 20
if age >= 18:
print("Eligible to vote")
๐ In Loops or Filtering
for num in range(10):
if num % 2 == 0:
print(f"{num} is even")
๐ In Loops or Filtering
for num in range(10):
if num % 2 == 0:
print(f"{num} is even")
Use this pattern to filter or process items that meet a condition โ such as:
- Finding even numbers
- Validating user inputs
- Iterating through test data in automation scripts
๐ Logical Operators in Python
Logical operators are used to combine multiple conditions. They return either True
or False
and are commonly used in if
statements, loops, and assertions.
โ Available Logical Operators
Operator | Name | Description | Example |
---|---|---|---|
and |
Logical AND | True if both conditions are true | x > 0 and x < 10 |
or |
Logical OR | True if at least one condition is true | x == 0 or x == 1 |
not |
Logical NOT | Inverts the condition | not is_valid |
๐งช Examples
x = 5
print(x > 0 and x < 10) # True (both are true)
print(x < 0 or x == 5) # True (second condition is true)
print(not x == 5) # False (x == 5, so not True = False)
๐ก When to Use Logical Operators
โ In Conditionals with Multiple Rules
username = "admin"
password = "1234"
if username == "admin" and password == "1234":
print("Access granted")
๐ In Loops for Filtering
data = [5, -3, 8, 0, 2]
for number in data:
if number > 0 and number < 10:
print(f"{number} is a valid positive single-digit")
Use this approach to filter out values that meet multiple conditions โ for example, checking that a number is both positive and less than 10.
๐งช In Test Automation
response_code = 200
response_time = 0.8
assert response_code == 200 and response_time < 1.0 Combine assertions to enforce multiple test conditions at once
Helps ensure your code meets all expected criteria in a single check
๐๏ธ Assignment Operators
Assignment operators are used to assign values to variables. You already know the basic =
operator, but Python also supports compound assignment operators that combine arithmetic and assignment.
โ Basic Assignment
x = 10 # Assigns 10 to x
๐งฎ Compound Assignment Operators
Compound assignment operators combine an arithmetic operation with assignment in a single step. They make code shorter and more readable when you’re updating the value of a variable based on its current value.
Instead of writing:
x = x + 3
You can write:
x += 3
โ Example: Compound Assignment Operators
x = 5
x += 3 # Same as x = x + 3 โ x becomes 8
x -= 1 # x = x - 1 โ x becomes 7
x *= 2 # x = x * 2 โ x becomes 14
x /= 2 # x = x / 2 โ x becomes 7.0
+=
adds to the existing value-=
subtracts from it*=
multiplies it/=
divides it (always returns a float)
This works with most arithmetic operators
Practice yourself with the Google Colab examples:
๐ Colab Example
Or go to my GitHub examples repository to find the Operators & Conditions examples:
๐ Operators-Condition Examples
๐๏ธ Assignment and Bitwise Operators in Python
โ๏ธ Bitwise Operators (Intro)
Bitwise operators work on the binary representation of integers. These are mostly used in low-level programming, flags, and performance-critical applications, but understanding the basics helps deepen your knowledge of how data is handled at the bit level.
๐ง What Is a Bit?
A bit is a binary digit โ either 0
or 1
. Every integer in Python is stored in binary format behind the scenes.
For example:
5
in binary โ0101
3
in binary โ0011
๐งฎ Bitwise Operator Table
Operator | Symbol | Description | Example | Binary Operation |
---|---|---|---|---|
AND | & |
1 if both bits are 1 | 5 & 3 = 1 |
0101 & 0011 = 0001 |
OR | | |
1 if at least one bit is 1 | `5 | 3 = 7` |
XOR | ^ |
1 if bits are different | 5 ^ 3 = 6 |
0101 ^ 0011 = 0110 |
NOT | ~ |
Inverts all bits (returns negative) | ~5 = -6 |
~0101 = 1010 (2’s complement) |
Left Shift | << |
Shifts bits to the left, fills with 0 |
5 << 1 = 10 |
0101 โ 1010 |
Right Shift | >> |
Shifts bits to the right, drops bits | 5 >> 1 = 2 |
0101 โ 0010 |
๐งช Code Examples
a = 5 # Binary: 0101
b = 3 # Binary: 0011
print(a & b) # 1 โ AND
print(a | b) # 7 โ OR
print(a ^ b) # 6 โ XOR
print(~a) # -6 โ NOT
print(a << 1) # 10 โ Shift left (adds 0 on the right)
print(a >> 1) # 2 โ Shift right (drops rightmost bit)
๐ผ Real-World Use Cases for Bitwise Operators
-
๐ Permissions flags
Used to manage combinations of access rights (e.g., read, write, execute). -
โก Performance-optimized toggling
Quickly turn on/off specific bits for feature flags, settings, or status tracking. -
๐๏ธ Compression and cryptography
Operate on binary data at a low level for space-saving and security tasks. -
๐ง Hardware control and drivers
Bitwise operations are essential in interacting with hardware registers or embedded systems.
๐ Conditional Statements in Python
Conditional statements allow your program to make decisions and execute code only if a certain condition is met. They are essential for control flow, validation, automation logic, and test conditions.
โ
The if
Statement
Executes a block of code if the condition is True.
temperature = 25
if temperature > 20:
print("It's warm outside.")
๐งพ The else
Statement
Defines what to do when the if
condition is False.
temperature = 15
if temperature > 20:
print("It's warm outside.")
else:
print("It's cold outside.")
๐ The elif
(else if) Statement
Checks another condition if the previous one was False
.
You can use multiple elif
blocks to check different conditions.
temperature = 20
if temperature > 25:
print("It's hot.")
elif temperature > 18:
print("It's mild.")
else:
print("It's cold.")
๐ง How It Works
- Python checks each condition in order
- The first condition that is
True
gets executed - All remaining conditions are skipped once one matches
- If none of the conditions are
True
, theelse
block runs (if present)
Practice yourself with the Google Colab examples:
๐ Colab Example
Or go to my GitHub examples repository to find the Operators & Conditions examples:
๐ Operators-Condition Examples
๐ Practice with Loops (for
, while
)
Loops allow you to repeat a block of code multiple times, making your programs more efficient and dynamic. In Python, there are two main types of loops:
๐ for
Loop
Use a for
loop when you want to iterate over a sequence (like a list, string, or range of numbers).
# Print numbers from 0 to 4
for i in range(5):
print(i)
๐ก Common Use Cases
- Loop through lists or strings
- Repeat tests on sets of data
- Count or collect results
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
๐ while
Loop
Use a while
loop when you want to repeat code as long as a condition is true.
count = 0
while count < 3:
print("Counting:", count)
count += 1
๐ก Common Use Cases
- Wait for a condition to become true
- Retry logic in test automation
- Input validation loops
โ๏ธ Loop Control Statements
You can control loop execution using:
break
โ Exit the loop earlycontinue
โ Skip to the next iterationpass
โ Do nothing (used as a placeholder)
for i in range(5):
if i == 3:
break # Stop loop when i equals 3
print(i)
๐งช Apply Operators and Control Flow to Test Automation
In test automation, Pythonโs operators and control flow tools (if
, else
, loops
, etc.) help you build smart, flexible scripts that respond to real test conditions.
โ 1. Using Comparison and Logical Operators
Use these to check actual results against expected values:
expected_status = "Success"
actual_status = "Success"
response_time = 0.9
# Validate both response status and performance
if actual_status == expected_status and response_time < 1.0:
print("Test passed โ
")
else:
print("Test failed โ")
๐ Using Loops to Test Multiple Inputs
Automate tests for multiple data points using for
loops:
inputs = [5, -1, 0, 10]
for value in inputs:
if value > 0:
print(f"{value} is a valid positive number")
else:
print(f"{value} is invalid")
๐ Retry Logic with while
Loops
Use while
loops for retrying failed conditions, such as waiting for a page to load or a condition to become true.
attempts = 0
max_attempts = 3
success = False
while attempts < max_attempts and not success:
print(f"Attempt {attempts + 1}")
# Simulate a check
response = "fail" if attempts < 2 else "pass"
if response == "pass":
success = True
print("Test passed โ
")
else:
attempts += 1
๐ก Why It Matters
- Automate decision making (pass/fail logic)
- Handle dynamic test conditions
- Build data-driven tests
- Add flexibility and robustness to test scripts
Practice yourself with the Google Colab examples:
๐ Colab Example
Or go to my GitHub examples repository to find the Operators & Conditions examples:
๐ Operators-Condition Examples