Python for Testers: Fundamentals Module

Welcome to the first step in your test automation journey using Python!

This module will help you build a solid foundation before we dive into tools like Selenium, Pytest, and Requests for API testing. A strong grasp of Python fundamentals is essential for writing clear, reliable, and maintainable test scripts.


πŸ“˜ What You’ll Learn in This Module

  1. Hello World & Basic Syntax

    • Understand how to write and run your first Python program using print().
    • Get comfortable with indentation and structure.
  2. Data Types & Type Checking

    • Learn about core data types: int, float, str, bool.
    • Use type() to inspect data and handle type conversions.
  3. String Manipulation

    • Practice slicing, concatenation, formatting, and useful string methods.
    • Handle web element text, API responses, and logs effectively.
  4. Variable Assignment & Conversion

    • Assign and reassign variables.
    • Convert between types with int(), str(), float() and more.

🧩 Why These Basics Matter for Testers

Python Skill Relevance in Testing
print() and syntax Debugging test cases and script execution
String methods (split(), replace()) Parsing API responses, DOM elements
Type checking Writing robust test assertions
Variables and loops Creating reusable, data-driven test cases

πŸ–οΈ Hello World & Basic Syntax

Your first Python program is traditionally used to print a simple message to the screen. It’s a great way to confirm that Python is working and to understand basic syntax and structure.

Basic Hello World

print("Hello, World!")

This command:

  • Uses the print() function to display output
  • Passes a string enclosed in double quotes
  • Adds a new line automatically after printing

Python, and almost in any other program lanaguage, any text you want to represent as textual data (not code) must be written as a string β€” and strings are always enclosed in quotes.if you do not do that it sees it as variable and in this case you get an error

Hello World in Different Ways

print("Hello, World!")              # Standard message
print('Hello, World!')              # Using single quotes
print("Hello,", "World!")           # Printing multiple strings
print("Hello, World!", end="!!!")   # Custom end character
  • Using commas lets you print multiple strings with spaces between
  • The end argument changes what gets printed at the end (default is a newline)

As mentioned for the first module I mostly use google colab to show/display the most basic python examples

Open the examples notebook in Jupyter Notebook

You can run an example by pressing the play button play button

When running the notebook in Google Colab, you’ll see a warning:
warning
You do not need to worry about this warning β€” it’s standard in Colab.


πŸ’» Run Locally (Alternative)

As an alternative, you can run the examples locally.
They are available in the GitHub repo,
so you don’t have to deal with Google Colab at all.

2️⃣ Data Types in Python and How to Get the Type at Runtime

Python has several built-in data types that allow you to store and manipulate different kinds of data. Understanding these is essential for writing reliable and bug-free code β€” especially when validating data from user input, APIs, or web pages.


πŸ”’ Common Data Types in Python

Type Example Description
int 42, -3, 1000 Integer numbers
float 3.14, -0.5, 2.0 Decimal (floating point) numbers
str "hello", 'abc' Text (strings)
bool True, False Boolean values
list [1, 2, 3] Ordered, mutable collection
tuple (1, 2, 3) Ordered, immutable collection
dict {"key": "value"} Key-value pairs (dictionary)
set {1, 2, 3} Unordered collection of unique items
NoneType None Represents the absence of a value

πŸ” How to Check the Type of a Variable

Use the built-in type() function to inspect the type of a variable at runtime.

x = 10
print(type(x))  # Output: <class 'int'>

name = "Alice"
print(type(name))  # Output: <class 'str'>

price = 3.99
print(type(price))  # Output: <class 'float'>

active = True
print(type(active))  # Output: <class 'bool'>

## πŸ§ͺ Practice Yourself

Open the [examples notebook](<https://colab.research.google.com/drive/1Qgcztcc2O7_CcG8Ze6hzGBeheHenqu_W>) in **Jupyter Notebook** or your favorite IDE.
or your favorite IDE.

 Practicing code in a live environment is the best way to reinforce what you’ve learned.

# βœ‚οΈ String Manipulation and Printing

Strings are one of the most commonly used data types in Python. In this section, you'll learn how to create, format, and manipulate strings to prepare for real-world test automation tasks like logging, validation, and parsing.



### πŸ”€ String Creation

```python
name = "Alice"
greeting = 'Hello'
empty = ""

You can use either single or double quotes. An empty string is simply two quotes with nothing inside.

βž• String Concatenation

Concatenation means joining two or more strings together to make a single string.

You can concatenate strings using the + operator:

first = "Hello"
second = "World"
combined = first + " " + second
print(combined)  # Output: Hello World
    • joins strings
  • Be careful: all parts must be strings If you try to concatenate a string with a number, Python will raise an error.

🎯 String Formatting

String formatting lets you insert variables into a string in a cleaner and more readable way β€” especially useful for long or dynamic messages.


name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
  • Place variable names inside {} brackets
  • Very readable and modern approach

Using .format()

print("My name is {} and I am {} years old.".format(name, age))
  • Braces {} act as placeholders
  • Values are filled in order or by index

Using % (Old style)

print("My name is %s and I am %d years old." % (name, age))
  • %s for string, %d for integer
  • Older syntax, still used but less common

🧹 Common String Methods

String methods allow you to modify, clean, analyze, and test strings in Python. These methods are built into Python and can be used directly on any string variable.

Here are some of the most commonly used string methods:


πŸ”  .upper() and .lower()

Convert a string to uppercase or lowercase.

text = "Python for Testers"

print(text.upper())  # Output: PYTHON FOR TESTERS
print(text.lower())  # Output: python for testers

.strip(), .lstrip(), .rstrip(),replace()

Remove whitespace (spaces, tabs, newlines) from the string.

text = "  Hello  "

print(text.strip())   # 'Hello'        (removes both sides)
print(text.lstrip())  # 'Hello  '      (removes left only)
print(text.rstrip())  # '  Hello'      (removes right only)
text = "I love Java"
print(text.replace("Java", "Python"))  # I love Python (replace)

Open the examples notebook in Jupyter Notebook or your favorite IDE to try these methods and more

πŸ“¦ Variable Assignment and Types

In Python, you can assign values to variables without declaring their type. Python uses dynamic typing, which means the type of a variable is determined at runtime based on the assigned value.


βœ… Basic Variable Assignment

x = 10
y = 20
z = x + y
print(f"x = {x}, y = {y}, z = x + y = {z}")
  • Variables are created when you assign them a value
  • The type is automatically inferred

Multiple Assignment

a, b, c = 1, 2, 3
print(f"Multiple assignment: a={a}, b={b}, c={c}")

You can assign multiple variables in a single line.

Unpacking from List or Tuple

In Python, unpacking allows you to assign multiple values from a list or tuple into variables in a single line.

🟒 What is a List?

A list is an ordered, changeable collection of items.

Lists use square brackets []

You can change (mutate) their contents:



values = [100, 200, 300]
x, y, z = values
print(x, y, z)  # Output: 100 200 300

Lists use square brackets []

You can change (mutate) their contents:

my_list[1] = 99
print(my_list)  # Output: [10, 99, 30]

πŸ”΅ What is a Tuple? A tuple is also an ordered collection, but immutable (cannot be changed after creation).

my_tuple = (1, 2, 3)
print(my_tuple[0])  # Output: 1
Tuples use parentheses ()

You cannot modify their values:

my_tuple[1] = 99 # ❌ This will raise a TypeError

πŸ” Unpacking Example with List

values = [100, 200, 300]
x, y, z = values
print(x, y, z)  # Output: 100 200 300

Unpacking Example with Tuple

data = ("Alice", 30, "Tester")
name, age, role = data
print(f"{name} is a {age}-year-old {role}.")

βœ… Make sure the number of variables on the left matches the number of elements in the list or tuple, or Python will raise a ValueError.

πŸ”„ Type Conversion (Casting) in Python

Type conversion, also known as casting, is the process of changing a value from one data type to another.

Python provides several built-in functions for casting types:

  • int() – convert to integer
  • float() – convert to float
  • str() – convert to string
  • bool() – convert to boolean

πŸ”’ Convert to Integer with int()

x = "100"
num = int(x)
print(num + 1)  # Output: 101
Works with numeric strings ("10"), floats (10.5), and booleans (True β†’ 1, False β†’ 0).

The type is automatically inferred

Integrating with PracticeAutomatedTesting.com

PracticeAutomatedTesting.com offers a unique platform where users can interactively learn and practice test automation. It provides real-world scenarios for UI and API testing, making it an ideal place to apply the concepts learned above.

For UI/API testing, you can automate scenarios like form submissions, data validations, and user navigation flows. For API testing, you can practice by automating tests for CRUD operations, authentication flows, and response validations.

Why Practice on PracticeAutomatedTesting.com?

  1. Real-World Scenarios: The website offers a variety of real-world scenarios that mimic actual development tasks.
  2. Interactive Learning: By applying what you’ve learned in an interactive environment, you reinforce your knowledge and skills.
  3. Immediate Feedback: The platform provides immediate feedback on your tests, helping you learn and adapt quickly.

Final Thoughts

Test automation is a critical skill in software development, and Python offers an accessible entry point into this field. By utilizing resources like PracticeAutomatedTesting.com, learners can gain hands-on experience with both UI and API testing, making the learning process both effective and engaging.

Remember, the key to mastering test automation is practice. So, explore, experiment, and learn as you go. Happy testing!