“Introduction to Python for testers” is a comprehensive course designed to equip learners with essential skills in automating testing processes for UI applications using Python.

Data Types

Python has several built-in data types, each serving different purposes:

Numbers

  • Integers (int): Whole numbers, positive or negative, without decimals.
  • Floating Point Numbers (float): Numbers that have a decimal point or an exponent.
  • Complex Numbers (complex): Numbers with a real and imaginary part, written as a + bj.
int_number = 5
float_number = 5.0
complex_number = 3+4j

Boolean (bool):

Represents truth values: True and False.

Useful in control flows and conditional testing.

is_valid = True

Strings (str):

Ordered sequences of characters used to store and represent text data.

Immutable, meaning that once a string is created, the elements within it cannot be changed.

name = "John Doe"

Lists (list):

  • Ordered and mutable collections of items (which can be of different types).
  • Lists are created by placing items inside square brackets [], separated by commas.
fruits = ["apple", "banana", "cherry"]

Example of list manipulation, in this case an append

# Start with this list
numbers = [1, 2, 3, 4, 5]

# Print the initial list
print("Initial list:", numbers)

# Append an element to the list
numbers.append(6)

# Print the updated list
print("Updated list with appended element:", numbers)

# Print the second element (index 1) and the fourth element (index 3)
print("Second element:", numbers[1])
print("Fourth element:", numbers[3])

As you noticed an index is starting with 0 so if you want to print the second element it should start with [1] instead of 2

Tuples (tuple):

Ordered collections like lists, but immutable.

Tuples are created by placing items inside parentheses (), separated by commas.

point = (1, 2, 3)

Lets dive into a tuple example

# Define a tuple
my_tuple = (1, 2, 3)

# Attempt to modify the second element of the tuple
try:
    my_tuple[1] = 4
except TypeError as e:
    print("Error:", e)

Explanation:

  • Defining the tuple: my_tuple = (1, 2, 3) creates a tuple with three integers.
  • Modifying the tuple: The line my_tuple[1] = 4 attempts to change the second element of the tuple from 2 to 4. Since tuples are immutable, Python does not allow this operation.
  • Handling the error: The try-except block catches the TypeError that is raised when trying to modify a tuple. The error message “Error: ’tuple’ object does not support item assignment” is printed.

In this example you will see it is impossible to modify an element of a tuple as this is immutable

Dictionaries (dict):

  • Unordered collections of key-value pairs.
  • Keys must be unique and immutable. Values can be of any type.
  • Dictionaries are created by placing comma-separated keypairs inside curly braces {}.
person = {"name": "Alice", "age": 25}

 # Define a dictionary representing a person
person = {"name": "John", "age": 30, "city": "New York"}
# Print the entire dictionary
print("Complete dictionary:", person)
# Access and print only the age
print("Age:", person["age"])
# Add a new key-value pair for occupation
person["occupation"] = "Software Developer"

# Print the updated dictionary
print("Updated dictionary with occupation:", person)

Explanation:

  • Defining the dictionary: The dictionary person is created with keys name, age, and city, and corresponding values “John”, 30, and “New York”.
  • Printing the entire dictionary: The print() function is used to display all key-value pairs in the person dictionary.
  • Accessing and printing the age: The age is accessed using the key age (person[“age”]). This demonstrates how to retrieve specific data from a dictionary.
  • Adding a new key-value pair: A new key-value pair (“occupation”: “Software Developer”) is added to the dictionary. This shows how to update a dictionary by adding new entries.
  • Printing the updated dictionary: The dictionary is printed again to show the updated content, including the newly added occupation.

Sets (set):

  • Unordered collections of unique elements.
  • Useful for membership testing, removing duplicates, and mathematical operations like unions, intersections.
  • Sets are created by placing items inside curly braces {}, separated by commas, or by using the set() constructor.
colors = {"red", "blue", "green"}

An example of a conversion of a my_tubple to a set

# Create a tuple with specified elements
my_tuple = (10, 20, 30, 40, 50)

# Convert the tuple to a set
my_set = set(my_tuple)
print("Set created from tuple:", my_set)

# Add an element to the set
my_set.add(60)
print("Set after adding an element:", my_set)

# Check if an element is in the set
if 20 in my_set:
    print("20 is in the set.")
else:
    print("20 is not in the set.")

Explanation:

  • my_tuple = (10, 20, 30, 40, 50): This line initializes a tuple named my_tuple with the elements 10, 20, 30, 40, and 50.
  • my_set = set(my_tuple): This line converts the tuple into a set. Sets are collections of unique elements and are useful for operations like checking membership and removing duplicates.
  • print(“Set created from tuple:”, my_set): This prints the set created from the tuple, which should show {10, 20, 30, 40, 50} since sets are unordered.
  • my_set.add(60): The add() method adds an element to the set. After this operation, the set will contain the element 60 in addition to the elements from the tuple.
  • print(“Set after adding an element:”, my_set): This prints the set after the new element (60) has been added.
  • if 20 in my_set:: This line checks if the element 20 is present in the set. The in keyword is used for membership testing in Python.
  • print(“20 is in the set.”): If 20 is found in the set, this message is printed.

Type Conversion

You can convert between different data types explicitly using Python’s built-in functions:

int(), float(), str(), list(), tuple(), set(), dict()
str_number = "123"
int_number = int(str_number)  # Converts string to integer

Variables

Variables in Python are names that refer to data stored in memory. The variable name is a label that can be attached to different types of data.

  • Dynamic Typing: Python is dynamically typed, which means you don’t need to declare the type of the variable when you create one. The type can change as the variable is reassigned.

  • Assignment: Variables are created when they are first assigned a value. Python uses the equals sign = for variable assignments.

x = 10        # integer
greeting = "Hello, world!"  # string
  • Variable Names: Variable names in Python can contain letters, digits, and underscores but cannot start with a digit. Python is case-sensitive, so variable and Variable would be considered different variables.

An example of how variable can be used for manipulation purposes

# Initial string
greeting = "Hello, world!"

# Print the string in uppercase
uppercase_greeting = greeting.upper()
print("Uppercase:", uppercase_greeting)

# Replace "world" with your name
personalized_greeting = greeting.replace("world", "Alice")
print("Personalized:", personalized_greeting)

# Print the result in reverse
reversed_greeting = personalized_greeting[::-1]
print("Reversed:", reversed_greeting)
  • Print in Uppercase: The upper() method is used to convert all characters in the string to uppercase. This is helpful when you want to standardize text input or emphasize something.
  • Replace “world” with your name: The replace() method replaces occurrences of a substring within the string with another substring. In this case, “world” is replaced with “Alice”. This method is useful for modifying strings based on dynamic input or correcting data.
  • Print the string in reverse: To reverse a string in Python, you can use the slicing method. string[::-1] returns a new string that is a reverse of the original. Slicing is a powerful feature that allows you to extract parts of strings and arrays efficiently.

Exercise 1: Basic Variables and Types

Task: Create variables of each type (int, float, str, bool) and print their types using the type() function.

Your task: Create the variables here and print their types

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

Exercise 2: List Operations

Task: Create a list of five integer elements. Perform the following operations:

  • Print the list.
  • Append an element to the list.
  • Print the third and fourth elements.

# Start with this list
numbers = [1, 2, 3, 4, 5]

Your task: Append, access, and print operations

Exercise 3: String Manipulation

Task: Given the string “Hello, world!”, perform the following:

  • Print the string in lowercase.
  • Replace “hello, " with “Perfect”
  • Print the result in reverse.
greeting = "Hello, world!"

Your task: Manipulate and print the string as described

Exercise 4: Dictionary Lookup

Task: Create a dictionary representing a person. It should include keys such as name, age, and city.

Perform the following:

  • Print the entire dictionary.
  • Access and print only the age.
  • Add a new key-value pair for occupation.
person = {"name": "John", "age": 30, "city": "New York"}

Your task: Dictionary operations

Exercise 5: Tuple and Set Operations

Task: Create a tuple with elements (10, 20, 30, 40, 50). Convert this tuple to a set and add an element 60 to this set. Print the whole set

my_tuple = (10, 20, 30, 40, 50)

Your task: Convert to set, add element, check membership

Exercise 6: Type Conversion and calculation

Task: Given a list of strings [“1”, “2”, “3”, “4”], convert each string in the list to an integer. Sum all the integers and print the result.

string_numbers = ["1", "2", "3", "4"]

Your task: Convert and calculate the sum