• Automation
  • Home
  • /
  • Learning Hub
  • /
  • Python Basics Tutorial: Beginners Guide With Examples
  • -
  • July 13 2023

Python Basics Tutorial: Beginners Guide With Examples

This comprehensive Python Basics tutorial explores essential Python concepts, syntax, and practical examples in a concise and accessible format.

OVERVIEW

Python has established itself as a beloved language among software engineers, quality engineers, data scientists, and developers worldwide, thanks to its remarkable simplicity, readability, and versatility.

In this Python Basics tutorial, we will take a deep dive into the Python language, creating the Python Cheat Sheet - Python Basics and Quick Reference. This invaluable resource serves as a compact reference guide, providing a wealth of essential concepts, syntax, and practical examples in an easily digestible format for programmers of all proficiency levels.

Whether you're a beginner looking to grasp the fundamentals or an experienced Python developer needing a handy reference, this Python Basics tutorial will undoubtedly enhance your Python programming journey. So, let's embark on this knowledge-packed adventure and unlock the power of Python together!

What is Python?

Python, introduced by Guido van Rossum in 1991, is a high-level programming language that emphasizes the readability of code and utilizes a concise syntax for improved understanding and accessibility. Python's user-friendly nature and cross-platform compatibility make it an ideal choice for teaching programming, fostering simplicity, and encouraging collaboration within the open-source community.

It is a programming language that is constantly being updated and has excellent support from the community. Python, renowned for its simplicity, readability, and flexibility, has garnered immense popularity among software engineers, data scientists, and developers due to its extensive collection of libraries and frameworks.

The popularity of Python has skyrocketed in recent years, as demonstrated by the data from Stack Overflow Trends. Python has emerged as the most widely used programming language, surpassing other languages in adoption and community engagement. This can be observed in the following chart:

cy-pause-execution

Python has emerged as a popular choice among quality engineers for test automation due to its numerous advantages. If you want to understand why Python is widely regarded as the optimal programming language for test automation, please look at this insightful blog titled Why Python is the Go-To Choice for Test Automation. This resource offers an in-depth exploration of Python Basics' specific capabilities and strengths, making it an exceptional tool for automating tests.

By harnessing the potential of Python Basics, you can streamline your test automation endeavors, leverage its extensive range of libraries and frameworks, and tap into the vast resources and community support it offers.

Why Python?

Python's widespread adoption across diverse domains can be attributed to several compelling factors:

  • User-Friendliness

    Python's syntax is straightforward and intuitive, rendering it particularly suitable for beginners. Its emphasis on simplicity diminishes the learning curve and empowers developers to write clean, understandable code.

  • Versatility

    Python finds applications in web development, data analysis, artificial intelligence, machine learning, test automation, scientific computing, and more. Its extensive assortment of libraries and frameworks equips programmers with powerful tools tailored to various domains.

  • Active and Thriving Community

    Python boasts a vibrant and supportive global community of developers. This community actively contributes to the language's evolution, creates new libraries, fosters knowledge sharing, and extends assistance through forums and online communities.

  • Cross-Platform Compatibility

    Python runs seamlessly on multiple platforms, including Windows, macOS, and Linux, making it highly portable. Python programs can be executed on different operating systems without significant modifications.

  • Rich Ecosystem of Libraries and Frameworks

    Python offers an extensive ecosystem of libraries and frameworks that expedite development processes. Popular libraries bolster productivity and provide ready-made solutions for common tasks.

This Python Basics tutorial is a handy resource for learning and quick reference. It offers a comprehensive yet concise overview of Python, making it beneficial for beginners to grasp fundamental concepts and syntax. For experienced Python programmers, it serves as a convenient tool to refresh their memory on specific topics. The Python Basics tutorial includes code snippets, examples, and explanations to demonstrate concepts effectively, making it a valuable resource for all levels of Python proficiency.

Note

Note : Test your Python web applications on the cloud. Try LambdaTest Today

Python Basics

Within this section on Python Basics, we will delve into critical subjects, including Python installation, variable manipulation, data types, control flow statements, functions, and modules. Our approach will feature lucid explanations, code snippets, and practical examples to facilitate a comprehensive comprehension of each concept.

Installing Python

To begin your journey into the world of Python Basics, you'll need to install Python. Follow the step-by-step instructions below to complete the installation process on Windows:

  • Navigate to the official Python website and access the Downloads section.
  • Choose the appropriate installer for your Windows system, selecting either the 32-bit or 64-bit version based on your computer's architecture.
  • Once the installer file is downloaded, install it by double-clicking on it.
  • The installation wizard will appear. Ensure that you select the option to add Python to PATH, as this will allow you to easily access Python from the command line.
  • Proceed with the installation by following the on-screen instructions. Python will be installed in the default directory, typically C:\Python.
  • After the installation, open the command prompt by pressing the Windows key + R, typing cmd into the Run dialog, and hitting Enter.
  • In the command prompt window, type the command python --version and press Enter. This will display the version of Python installed on your system, confirming a successful installation.

python --version 
      
install-python

Congratulations! You have now successfully installed Python on your Windows machine. You're ready to dive into the exciting world of Python Basics, where endless possibilities await.

If you use a different OS, you can follow the official Python documentation to install Python according to your operating system.

Please remember that the installation steps may differ slightly based on the specific version of Python and your Windows operating system. For the most up-to-date and detailed installation instructions tailored to your specific setup, it's advisable to consult the official Python documentation, as provided in the above paragraph.

Python Data Types

When working with Python Basics, understanding the different data types is essential for effective variable manipulation. Data types define how values are stored and operated upon in Python. In this section of the Python Basics tutorial, let's explore the various data types in detail.

Numbers

Numbers are used for representing numerical values in Python. The language supports several numeric data types, including integers, floating-point, and complex numbers.

Integers

Integers are whole numbers without fractional components. They can be positive or negative values. For example:


x = 13
y = -3 

Floating-Point Numbers

Floating-point numbers, or floats, are numeric values with decimal points. They can represent both fractional and real numbers. For instance:


pi = 3.14159
radius = 2.5

Floats provide more precision than integers and are commonly used in scientific computations or when working with decimal values.

Complex Numbers

Complex numbers represent quantities with real and imaginary parts. They are typically written as a + bj, where a represents the real part and b represents the imaginary part. For example:


z = 3 + 4j

Complex numbers are useful in various mathematical calculations and can be manipulated using built-in functions and operators in Python.

Strings

Strings are sequences of characters enclosed within single quotes ('') or double quotes (""). They are employed to represent textual data. Consider the following examples:


name = "Paulo Oliveira"
message = 'Hello, Paulo!'

String concatenation can be performed using the + operator:


greeting = "Hello"
name = "Paulo"
full_greeting = greeting + " " + name
print(full_greeting)  # Output: Hello Paulo

Execution result:

python-string-execution-result

Booleans

Booleans serve as truth values and have two possible states: True and False. They are employed in logical operations and program flow control. Observe the following example:


is_raining = True
is_sunny = False

Boolean values often come into play within conditional statements, as we will see in future sections.

Lists

In Python, a list is a versatile and widely used data type that allows you to store and manipulate collections of items. Lists are especially valuable in test automation as they provide a convenient way to manage and organize test data, test cases, and other related information.

A list in Python is denoted by square brackets [] and can contain elements of any data type, including numbers, strings, booleans, or even other lists. Here's an example of a Python list that stores a collection of test cases:


test_cases = ["login", "register", "search", "checkout"]

In test automation, lists can be utilized in various ways. For instance, you can use lists to define a set of test data inputs, such as usernames or passwords, which must be tested across multiple scenarios. Here's an example:


usernames = ["user1", "user2", "user3"]
passwords = ["pass123", "pass456", "pass789"]

You can iterate over these lists and use the values to execute test cases with different input combinations, ensuring comprehensive test coverage.

Lists also support various operations, such as appending or removing elements, sorting, and accessing specific elements by their index. For example, you can append a new test case to an existing list using the append() method:


test_cases = ["login", "register", "search"]
test_cases.append("checkout")
print(test_cases) # Output: ['login', 'register', 'search', 'checkout']

Execution result:

python-list-execution-result

You can also remove an element from the list using the remove() method:


test_cases.remove("register")
print(test_cases) # Output: ['login', 'search', 'checkout']

Execution result:

python-remove-execution-result

Furthermore, lists can be combined, sliced, or manipulated in other ways to perform complex operations.

Lists in Python offer a flexible and intuitive way to handle data collections in test automation scenarios. Whether it's managing test cases, test data, or result sets, the ability to store and manipulate data using lists provides a powerful tool for effective test automation.

Tuples

When learning Python Basics, a tuple is an immutable data type that allows you to store a collection of items. Tuples are particularly useful in test automation scenarios where you must represent data that should not be modified.

A tuple in Python Basics is defined using parentheses() and can contain elements of different data types. Here's an example of a tuple that stores test case data:


test_case = ("login", "user1", "pass123", True)

In test automation, tuples can be employed in various ways. One common use case is to represent test case parameters or inputs that remain constant throughout the test execution. For instance, you can define a tuple to store the login credentials for different user roles:


credentials = (
    ("admin", "admin123"),
    ("user", "user123"),
    ("guest", "guest123")
)

By using tuples, you ensure that the test case parameters remain unchanged during the test execution, maintaining the integrity and consistency of the test data.

Tuples, being immutable, offer advantages in terms of data integrity and security. Once a tuple is created, its elements cannot be modified. This property makes tuples suitable for storing sensitive or critical data in test automation, where accidental modifications should be avoided.

Tuples also support various operations, such as indexing, slicing, and unpacking. You can access specific elements in a tuple using their index:


test_case = ("login", "user1", "pass123", True)
print(test_case[0])  # Output: login

Execution result:

python-tuples-execution-result

You can slice a tuple to extract a subset of elements:


credentials = ("admin", "user", "guest", "tester")
print(credentials[1:3])  # Output: ("user", "guest")

Execution result:

python-tuples-subset-execution-result

Additionally, you can unpack the elements of a tuple into separate variables:


user, password = ("admin", "admin123")
print(user)      # Output: admin
print(password)  # Output: admin123

Execution result:

python-tuples-separate-variable-execution-result

Tuples provide a reliable and immutable way to represent and protect data in test automation scenarios. Whether it's storing constant test inputs, sensitive information or ensuring data integrity, tuples offer a valuable data type for effective and secure test automation.

Sets

When learning Python Basics, a set is an unordered collection of unique elements. Sets are particularly useful in test automation scenarios where you must handle a collection of distinct items or perform set operations such as unions, intersections, and differences.

A set in Python Basics is defined using curly braces {} or the set() function. Here's an example of a set that stores a collection of test tags:


test_tags = {"smoke", "regression", "functional"}

Sets in test automation can be utilized in various ways. One common use case is representing the tags or categories assigned to test cases. For instance, you can define a set to store the tags associated with a specific test case:


test_case_1_tags = {"smoke", "regression"}
test_case_2_tags = {"functional", "performance"}

You can perform set operations on sets to manipulate and compare them. Some commonly used set operations include:

Union: Combines two sets and returns a new set containing all the unique elements from both sets.


test_tags = {"smoke", "regression"}
additional_tags = {"functional", "performance"}

all_tags = test_tags.union(additional_tags)
print(all_tags)  # Output: {"regression", "functional", "smoke", "performance"}

Execution result:

python-sets-execution-result

Intersection: Returns a new set containing the common elements between two sets.


test_tags = {"smoke", "regression", "functional"}
selected_tags = {"functional", "performance"}

common_tags = test_tags.intersection(selected_tags)
print(common_tags)  # Output: {"functional"}

Execution result:

python-sets-intersection-execution-result

Difference: Returns a new set containing the elements from one set that are not present in the other set.


test_tags = {"smoke", "regression", "functional"}
excluded_tags = {"regression", "performance"}

remaining_tags = test_tags.difference(excluded_tags)
print(remaining_tags)  # Output: {"functional", "smoke"}

Execution result:

python-sets-difference-execution-result

Sets also support membership tests and set operations such as subset, superset, and disjoint checks, which can be handy in test automation scenarios.


test_tags = {"smoke", "regression", "functional"}

print("regression" in test_tags)  # Output: True
print({"functional", "performance"}.issubset(test_tags))  # Output: False
print({"functional", "performance"}.isdisjoint(test_tags))  # Output: True

Execution result:

python-sets-membership-execution-result

Sets provide a convenient and efficient way to handle unique elements and perform set operations in test automation. Whether it's managing test tags, performing set operations, or checking membership, sets offer a valuable data type for handling distinct items and performing set-related tasks effectively in test automation.

Dictionaries

In Python Basics, a dictionary is a versatile data type that allows you to store and retrieve key-value pairs. Dictionaries are handy in test automation scenarios where you must store and access data using unique identifiers or keys. They provide an efficient way to organize and manipulate data, making them valuable for various tasks in test automation.

To understand dictionaries, imagine a real-life dictionary where you can look up a word (key) and find its corresponding definition (value). Similarly, in Python dictionaries, you can use a key to access the associated value. Dictionaries are enclosed in curly braces {} and consist of key-value pairs separated by a colon (:).

Here are some examples of dictionaries in test automation:

Test Case Data: You can use a dictionary to store the data related to a test case, such as test inputs, expected outputs, and other relevant information. Each key represents a specific piece of data, and its corresponding value holds the actual data.


test_case_1 = {
    "name": "Login",
    "input": {"username": "testuser", "password": "password123"},
    "expected_output": "Success",
    "tags": ["smoke", "regression"]
}

Test Environment Configuration: Dictionaries can be used to store configuration settings for different test environments. Each key represents a configuration parameter, and its value stores the corresponding setting.


test_environment = {
    "url": "https://example.com",
    "browser": "Chrome",
    "timeout": 10,
    "headless": True
}
...

Test Data Mapping: Dictionaries can be employed to map test data to specific test cases. Each key represents a test case identifier, and its value holds the corresponding test data.


test_data = {
    "TC001": {"input": 5, "expected_output": 25},
    "TC002": {"input": 10, "expected_output": 100},
    "TC003": {"input": -2, "expected_output": 4}
}

Test Results: Dictionaries can be used to store and organize test results. Each key represents a test case identifier, and its value stores the test execution outcome.


test_results = {
    "TC001": "Pass",
    "TC002": "Fail",
    "TC003": "Pass"
}

Dictionaries provide several methods to manipulate and access data. You can retrieve values using keys, add new key-value pairs, update values, and delete entries. Here are a few examples:


#Dictionaries Access and Manipulation

test_case = {"name": "Login", "status": "Pass", "tags": ["smoke", "regression"]}
print(test_case["name"])  # Output: "Login"

test_case["status"] = "Fail"
print(test_case)  # Output: {"name": "Login", "status": "Fail", "tags": ["smoke", "regression"]}

test_case["timeout"] = 10
print(test_case)  # Output: {"name": "Login", "status": "Fail", "tags": ["smoke", "regression"], "timeout": 10}

del test_case["tags"]
print(test_case)  # Output: {"name": "Login", "status": "Fail", "timeout": 10}

Execution result:

python-dictionaries-execution-result

Dictionaries provide a flexible and efficient way to organize, access, and manipulate data in test automation. Whether it's storing test case data, managing configuration settings, mapping test data, or tracking test results, dictionaries offer a powerful data structure for handling key-value pairs effectively in test automation.

Understanding and working with these data types will enable you to manipulate and process data effectively in Python. Make sure to practice and experiment with different operations to reinforce your understanding. In the next section of this tutorial on Python Basics, we will dive deeper into Python's control flow statements.

Operators

Operators play a vital role in Python programming as they allow us to perform various operations on data. In this section of this tutorial on Python Basics, we will explore three types of operators: arithmetic operators, comparison operators, and logical operators. Understanding how to use these operators will enhance your ability to perform calculations, make comparisons, and implement logical conditions in your Python Basics programs.

Arithmetic Operators

Arithmetic operators perform mathematical calculations such as addition, subtraction, multiplication, division, and more. Here are some commonly used arithmetic operators while working with Python Basics:

Addition (+): The addition operator is used to add two values together. For example:


x = 10
y = 5
result = x + y
print(result)  # Output: 15

Execution result:

python-addition-execution-result

Subtraction (-): The subtraction operator subtracts one value from another. For example:


x = 10
y = 5
result = x - y
print(result)  # Output: 5

Execution result:

python-subtraction-execution-result

Multiplication (*): The multiplication operator multiplies two values. For example:


x = 10
y = 5
result = x * y
print(result)  # Output: 50

Execution result:

python-multiplication-execution-result

Division (/): The division operator divides one value by another. For example:


x = 10
y = 5
result = x / y
print(result)  # Output: 2.0

Execution result:

python-division-execution-result

Note: In Python 3.x, division always returns a float value. If you want to perform integer division, you can use the double-slash operator (//).

Modulus (%): The modulus operator returns the remainder of the division between two values. For example:


x = 10
y = 3
result = x % y
print(result)  # Output: 1

Execution result:

python-modulus-execution-result

Exponentiation (**): The exponentiation operator raises the first value to the power of the second value. For example:


x = 2
y = 3
result = x ** y
print(result)  # Output: 8

Execution result:

python-exponentiation-execution-result

Arithmetic operators allow you to perform mathematical operations on numeric values. They are versatile and can be used in various scenarios, such as calculating totals, averages or performing complex mathematical computations.

Comparison Operators

Comparison operators are used to compare two values and return a boolean result (True or False) based on the comparison. These operators are commonly used in conditional statements and loops. Here are the comparison operators while working with Python Basics:

Equal to (==): The equal to operator checks if two values are equal. For example:


x = 5
y = 5
result = x == y
print(result)  # Output: True

Execution result:

python-equal-to-execution-result

Not equal to (!=): The not equal to operator checks if two values are not equal. For example:


x = 5
y = 10
result = x != y
print(result)  # Output: True

Execution result:

python-not-equal-to-execution-result

Greater than (>): The greater than operator checks if the first value is greater than the second value. For example:


x = 10
y = 5
result = x > y
print(result)  # Output: True

Execution result:

python-greater-than-execution-result

Less than (<): The less than operator checks if the first value is less than the second value. For example:


x = 5
y = 10
result = x < y
print(result)  # Output: True

Execution result:

python-less-than-execution-result

Greater than or equal to (>=): The greater than or equal to operator checks if the first value is greater than or equal to the second value. For example:


x = 5
y = 5
result = x >= y
print(result)  # Output: True

Execution result:

python-greater-than-or-equal-to-execution-result

Less than or equal to (<=): The less than or equal to operator checks if the first value is less than or equal to the second value. For example:


x = 10
y = 10
result = x <= y
print(result)  # Output: True

Execution result:

python-less-than-or-equal-to-execution-result

Comparison operators are useful for making decisions and controlling the flow of your program based on the comparison results. They allow you to check conditions and execute specific code blocks accordingly.

Logical Operators

Logical operators combine multiple conditions and perform logical operations on them. They are typically used in conjunction with comparison operators. The three logical operators in Python are:

And: The operator returns True if both conditions on either side of the operator are True. For example:


selenium_version = 4.9
python_version = 3.11
result = (selenium_version > 4) and (python_version > 3)
print(result)  # Output: True

Execution result:

python-and-execution-result

Or: The or operator returns True if either one or both of the conditions on either side of the operator are True. For example:


selenium_version = 4.9
python_version = 3.11
result = (selenium_version > 5) or (python_version < 3)
print(result)  # Output: False

Execution result:

python-or-execution-result

Not: The not operator is used to negate the result of a condition. It returns True if the condition is False, and vice versa. For example:


selenium_version = 4.9
result = not(selenium_version > 5)
print(result)  # Output: True

Execution result:

python-not-execution-result

Logical operators allow you to combine conditions and create complex logical expressions to control the flow of your program based on multiple conditions.

By understanding and utilizing arithmetic operators, comparison operators, and logical operators, you can perform calculations, make comparisons, and implement logical conditions in your Python programs. These operators provide the flexibility and control necessary for building robust and dynamic applications.

Control Flow Statements

Control flow statements play a crucial role in Python programming as they provide the means to control the flow of execution in your code. They empower you to make decisions, execute specific code based on conditions, and create iterative processes using loops. This section of the Python Basics tutorial will delve into two fundamental types of control flow statements: conditional statements and loops. Gaining a deep understanding of these statements will greatly enhance your ability to develop dynamic and interactive programs.

Conditional Statements

Conditional statements, also known as if-else statements, provide a way to execute different code blocks based on certain conditions. They allow you to control the flow of your program by evaluating whether a specific condition is True or False.

The basic syntax of a conditional statement in Python is as follows:


if condition:
    # code block to execute if the condition is true
else:
    # code block to execute if the condition is false

To understand conditional statements better, let's consider an example. Suppose we want to create a program that checks if a given Selenium version is updated or deprecated. We can use a conditional statement to achieve this:


selenium_version = float(input("Enter your selenium version: "))

if selenium_version >= 4:
    print("Your selenium version is updated.")
else:
    print("Your selenium version is deprecated.")

In the above code, we prompt the user to enter a number and store it in the variable selenium_version. The conditional statement then checks if the number is greater than or equal to 4. If the condition is True, it prints "Your selenium version is updated." Otherwise, it prints "Your selenium version is deprecated." This allows the program to provide the appropriate output based on the input provided.

Executing this simple code twice, first using selenium_version = 4.9, and then selenium_version = 3.9, we will get these results:

python-selenium-version

You can also expand the conditional statement to include more conditions using elif (short for else if) statements. This allows you to test multiple conditions and execute different code blocks accordingly. Here's an example:


selenium_version = float(input("Enter your selenium version: "))

if selenium_version == 4.9:
    print("Your selenium version is the latest.")
elif selenium_version >= 4:
    print("Your selenium version is updated.")
else:
    print("Your selenium version is deprecated.")

In this modified version, the program first checks if the Selenium version is equal to 4.9. If True, it prints "Your selenium version is the latest." If not, it moves to the next condition and checks if the number is greater than or equal to 4. If True, it prints "Your selenium version is updated." If both conditions are False, it executes the code block under the else statement and prints "Your selenium version is deprecated."

Executing this simple code three times, first using selenium_version = 4.9, then using selenium_version = 4, and finally with selenium_version = 3.9, we will get these results:

python-selenium-different-versions

Loops

Loops are control flow statements that allow you to repeat a specific set of instructions multiple times. They are particularly useful when you want to perform an action iteratively or traverse through data collection.

While learning Python Basics, there are two main types of loops: FOR loops and WHILE loops.

The for loop is used when you know the number of iterations in advance or want to iterate over a sequence such as a list, tuple, or string. The basic syntax of a for loop is as follows:


for item in sequence:
    # code block to execute for each item in the sequence

To illustrate the usage of a for loop, let's consider an example where we want to print the numbers from 1 to 5:


for number in range(1, 6):
    print(number)

In this code, the range(1, 6) function generates a sequence of numbers from 1 to 5 (excluding 6). The for loop then iterates over each number in the sequence and prints it.

Executing this simple code, we will get this result:

python-for-loops

The while loop, on the other hand, is used when you want to repeat a set of instructions as long as a certain condition is true. The basic syntax of a while loop is as follows:


while condition:
    # code block to execute while the condition is true

Let's explore an example of a while loop that calculates the factorial of a given number:


number = int(input("Enter a number: "))
factorial = 1
count = 1

while count <= number:
    factorial = factorial * count
    count += 1

print("The factorial of", number, "is", factorial)

In this code, we first prompt the user to enter a number and store it in the variable number. The variables factorial and count are initialized to 1. The while loop then multiplies the value of factorial by the value of count while the condition count <= number is true. It increments the count by 1 in each iteration. Finally, it prints the factorial of the input number.

Executing this simple code, using number = 5, we will get this result:

python-while-loops

In the realm of Python programming, control flow statements serve as indispensable tools that grant you the ability to regulate the flow of execution within your code. Through the mastery of conditional statements and loops, you gain the power to make decisions, execute specific code blocks based on conditions, and carry out iterative actions.

These statements provide the essential elements of flexibility and control that are instrumental in constructing dynamic and interactive programs. By understanding and effectively implementing control flow statements, you unlock the potential to create sophisticated and responsive software solutions.

Functions

Functions are a fundamental concept in Python programming that allows you to organize and modularize your code. They enable you to break down complex tasks into smaller, reusable blocks of code.

In Python, you can define a function using the def keyword followed by the function name and parentheses. Here's a simple example of a function that greets the user:


#Basic function sample
def latest_selenium_version():
    print("Latest Selenium version is 4.9!")

#Calling the latest_selenium_version() function
latest_selenium_version()

When you run the above code, it will output: Latest Selenium version is 4.9! (this is the current Selenium version when writing this Python Basics tutorial). The latest_selenium_version() function is defined without arguments and performs a specific task: printing the Selenium version message. You can define functions with or without parameters based on the requirements of your code.

python-latest-selenium-version

Arguments and Parameters

Parameters are placeholders for values that a function expects to receive, while arguments are the actual values passed to the function when calling it. Functions can have zero or more parameters, allowing you to pass values and data to the function for further processing.

Let's define a function that takes a Selenium version as a parameter and prints the message with the provided version:


def selenium_version_with_parameter(version):
    print(f"Your Selenium version is {version}!")

# Calling the selenium_version_with_parameter() function with an argument
selenium_version_with_parameter("4.9")

When you execute the above code, it will output: Your Selenium version is 4.9!. In this case, "4.9" is the argument passed to the selenium_version_with_parameter() function, and it is used as the value for the version parameter inside the function.

selenium-version-with-parameter-function

Return Statement

The return statement allows a function to return a value or result to the caller. It is used when you want the function to perform some computations and provide an output or result that can be utilized in the calling code.

Consider the following example of a function that calculates the total execution time of a test suite execution:


def calculate_total_execution_time(testcase_quantity, execution_time_sec):
    total_time = testcase_quantity * execution_time_sec
    return total_time

# Calling the calculate_total_execution_time() function and storing the result in a variable
result = calculate_total_execution_time(5, 35)
print("Total Execution Time in seconds:", result)

When you run the above code, it will output: Total Execution Time in seconds: 175. The calculate_total_execution_time() function takes two parameters, testcase_quantity, execution_time_sec, and computes the total execution time by multiplying them. The result is then returned using the return statement and stored in the result variable. Finally, the total execution time is printed to the console.

total-execution-time-is-printed-to-the-console

You can also return multiple values from a function by separating them with commas. Let's see an example of a function that calculates both the total execution time and the average time of a test suite execution:


def calculate_total_execution_time_and_average(testcase_quantity, execution_time_sec):
    total_time = testcase_quantity * execution_time_sec
    average = total_time / testcase_quantity
    return total_time, average

# Calling the calculate_total_execution_time_and_average() function and storing the results in variables
total_time_result, average_result = calculate_total_execution_time_and_average(12, 25)
print("Total Execution Time in seconds:", total_time_result)
print("Average Execution Time in seconds:", average_result)

When you execute the above code, it will output:

When you execute the above code

In this case, the calculate_total_execution_time_and_average() function returns both the total_time and average values, which are then assigned to the total_time_result and average_result variables, respectively.

Functions play a crucial role in test automation by enabling you better organize your test automation. Let's explore some examples of how functions can be used in test automation scenarios:

Logging and Reporting

In test automation, it is important to log test results and generate test reports for analysis. You can create functions to handle logging and reporting tasks, such as capturing test case execution status, logging errors, and generating comprehensive reports. By encapsulating these functionalities in functions, you can easily integrate them into your test scripts and ensure consistent reporting across multiple test cases.

Test Data Management

Test data plays a crucial role in test automation. You can create functions to handle test data management, such as fetching test data from external sources, generating random test data, or cleaning up test data after test execution. These functions can be reused across multiple test scripts, ensuring efficient and consistent data handling.

Test Case Execution Flow

In test automation, you often need to execute test cases in a specific order or handle pre-test and post-test activities. Functions can be used to define the execution flow of test cases, allowing you to set up test environments, perform necessary configurations, and handle cleanup tasks after test execution.

Reusable Test Steps

In test automation, you may encounter common test steps repeated across multiple test cases. Encapsulating these steps in functions can avoid code duplication and improve script maintainability. These functions can be called within different test cases, making it easier to update and modify the test steps when needed.

Test Assertions

Assertions are crucial in test automation to validate expected results and ensure the correctness of test outcomes. You can create functions for common assertions, such as comparing actual and expected values, checking element visibility, or verifying error messages. These assertion functions enhance code readability and simplify test script development.

These are just a few examples of how functions can be utilized in test automation. Organizing your code into functions can improve code reusability, maintainability, and readability in your test scripts.

Functions allow you to efficiently handle logging and reporting, manage test data, define test case execution flow, encapsulate reusable test steps, and perform assertions. Embracing functions in test automation empowers you to create robust and scalable test frameworks while enhancing productivity and test script maintainability.

Modules

Modules in Python are invaluable in test automation as they allow you to organize, reuse, and enhance your test scripts. In this section of this Python Basics tutorial, we will explore the concepts of importing modules, including the popular Selenium module, and creating your custom modules for test automation.

Importing Modules

Python offers a wide range of modules that can be used for test automation. One such module is Selenium, which provides a powerful framework for automating web browsers. Let's delve into the different ways to import modules in Python for test automation.

Importing a Full Module

To import the entire Selenium module, use the import keyword followed by the module name. Here's an example:


import selenium

# Now you can use the Selenium module to automate web browsers
driver = selenium.webdriver.Chrome()
driver.get("https://www.example.com")

By importing the Selenium module, you gain access to its classes and methods, enabling you to automate web browsers for testing purposes.

Importing Specific Items from a Module

If you only need specific items from the Selenium module, you can import them individually using the from keyword. This approach allows you to directly use the imported items without referencing the module name. Here's an example:


from selenium.webdriver import Chrome, Firefox

# Now you can directly use the imported browser drivers
driver = Chrome()
driver.get("https://www.example.com")

driver = Firefox()
driver.get("https://www.example.com")

In this case, we imported the Chrome and Firefox browser drivers directly from the Selenium module, allowing us to automate specific browsers without referencing the module name.

💡To use the Selenium module, you need to install it first. You can do this by using the pip command, as shown below:


pip install selenium

Running this command, Selenium will be installed in your repository, as shown below.

Selenium will be installed in your repository

If you do not have pip installed on your machine, you should follow the below steps for Windows:

  • Download the get-pip.py script by visiting the official pip installation page: https://pip.pypa.io/en/stable/installing/
  • Save the get-pip.py file to your computer.
  • Open a command prompt and navigate to the directory where you saved the get-pip.py file.
  • Run the following command:

python get-pip.py

Then you can check the installation using the below command:


pip --version
Creating Custom Modules

Creating Custom Modules

In addition to using existing modules, you can create your custom modules to encapsulate test automation-related code and functionality. This approach helps organize your test scripts and promotes code reuse. Let's explore how to create a sample custom module for test automation.

The advantages of creating custom modules in Python for test automation include:

Enhanced Code Organization

Custom modules provide a structured approach to organizing your test automation code and functionality. They allow you to group related elements, such as functions, classes, and variables, making it easier to manage and maintain your codebase.

Increased Code Reusability

By encapsulating commonly used code or functionality within custom modules, you can promote code reuse across different test scripts. Instead of duplicating code in multiple places, you can simply import the module and leverage its functions or classes whenever needed, saving time and effort in development.

Improved Modularity and Maintainability

Custom modules promote modularity by allowing you to divide your codebase into smaller, self-contained modules. Each module can focus on a specific task or functionality, making the code more maintainable. Changes or updates can be made within a module without impacting other parts of the codebase.

Abstraction and Encapsulation

Custom modules enable you to abstract complex logic or implementation details. By exposing only the necessary functions or classes to other scripts, you can encapsulate the underlying implementation, making the module easier for other developers or testers to use and understand.

Simplified Testing and Debugging

Custom modules facilitate isolated testing and debugging of specific functionalities. By writing unit tests for each module, you can ensure that individual components of your test automation code function correctly. This targeted approach to testing and debugging increases efficiency and reduces potential issues.

Flexible Extensibility

Custom modules offer extensibility, allowing you to add new features or functionalities to your test framework. As your automation needs evolve, you can update or expand your custom modules to accommodate new requirements without disrupting the existing codebase.

Creating a Test Automation Module

To create a test automation module, you can create a new Python file with a .py extension and define functions, classes, or variables. Let's create a module named test_utils.py with some common test automation utilities:


# File: test_utils.py
def take_screenshot(driver, file_name):
    driver.save_screenshot(file_name)
    print(f"Screenshot saved as {file_name}")
def assert_element_present(driver, locator):
    try:
        driver.find_element(*locator)
        print("Element found")
        return True
    except:
        print("Element not found")
        return False

In the above code, we created two functions. The take_screenshot takes screenshots that can be used during the execution of your automated test. The second one assert_element_present asserts if an element is present on the screen.

Now, in your test script, you can import and use the functions from the test_utils module:


from selenium import webdriver
from test_utils import take_screenshot, assert_element_present

# Create a webdriver instance
driver = webdriver.Chrome()

# Use the utilities from the test_utils module
take_screenshot(driver, "homepage.png")

locator = ("id", "login_button")
assert_element_present(driver, locator)

# Close the webdriver instance
driver.quit()

By creating a custom module, we encapsulate common test automation utilities, making them reusable across different test scripts.

Modules in Python are powerful tools for test automation, allowing you to import existing modules, such as Selenium, and create your custom modules to encapsulate test automation code and utilities. By leveraging modules, you can enhance the organization, reusability, and maintainability of your test scripts, ultimately improving the efficiency and effectiveness of your test automation efforts.

Input and Output

Input and Output (I/O) operations are vital in test automation using Python Basics, particularly when working with files to populate test cases.

In this section of the Python Basics tutorial, you will learn about handling input and output in the context of test automation, focusing on standard input and output as well as file input and output.

Understanding these concepts is crucial for building dynamic and data-driven test scripts. In the further section of this Python Basics tutorial, we will explore each aspect in detail with examples related to test automation.

Standard Input and Output in Test Automation

While interacting with users through standard input may not be common in test automation, displaying output on the screen is essential for monitoring and debugging test scripts. Python's print() function is a valuable tool in this regard. Consider the following example:


# Displaying test information
test_name = "Login Test"
test_status = "Passed"
print("Test Name:", test_name)
print("Test Status:", test_status)

In this example, the test name and status are stored in variables (test_name and test_status), and the print() function is used to display this information on the screen. This allows testers to track the progress and outcome of test cases.

 test name and status are stored in variables

Python Basics - Quick Reference

This section of this Python Basics tutorial provides a comprehensive overview of Python's fundamental concepts and features. Dive into the Python Basics syntax, including variables, comments, and indentation, to ensure your code is clean and organized.

Explore the wide range of built-in functions, from type conversions to mathematical operations, string manipulation, and working with lists and dictionaries. We'll also share valuable Python snippets that cover essential tasks like reading and writing CSV files, generating random numbers, removing duplicates from lists, reversing strings, and finding the largest and smallest elements in a list.

Basic Syntax

In this section of the Python Basics tutorial, let’s explore the basic syntax of Python.

Variables

Variables play a crucial role in test automation as they allow you to store and manipulate data during test execution. While using Python Basics, you can create variables by assigning values to them using the = operator. Let's consider an example:


# Variable assignment for test data
username = "testuser"
password = "secretpassword"

In this example, we created two variables: username and password, which store the test data for authentication. You can utilize variables to store test inputs, expected results, URLs, or any other relevant data for your test cases.

Comments

Comments are valuable in test automation scripts to clarify and make the code more understandable for you and other team members. You can use comments to explain the purpose of your code, document test scenarios, or describe the expected behavior. Here's an example:


# Login test scenario
# This test verifies the login functionality by entering valid credentials

"""
Steps:
1. Enter the username
2. Enter the password
3. Click on the Login button
4. Verify successful login
"""

In this example, we have two single-line comments (using # at the beginning of each line) and a multi-line comment enclosed in triple quotation marks ("""). Comments help you communicate the intent of your code, making it easier to maintain and collaborate on test automation projects.

Indentation

Indentation is essential in test automation scripts as it defines the structure and scope of code blocks, such as conditional statements and loops. Proper indentation ensures the correct execution of test steps and helps avoid logical errors. Consider the following example:


# Test case for adding items to the cart
if item_available():
    navigate_to_product_page()
    select_item()
    add_to_cart()
    if verify_item_added():
        print("Item added to cart successfully")
    else:
        print("Failed to add item to cart")
else:
    print("Item is not available")

In this example, the code uses indentation to define the code blocks for the conditional statements. All statements indented under the if and else blocks belong to their respective code blocks. Proper indentation ensures that the test steps are executed within the appropriate conditions.

In summary, variables enable you to store and manipulate test data, comments provide clarity and documentation, and indentation defines the structure of code blocks. By mastering these aspects of Python Basics syntax within the context of test automation, you can write efficient and reliable automation scripts to streamline your testing processes.

Built-in Functions

In test automation, leveraging built-in functions is crucial for efficient and effective scripting. Python Basics offers a wide range of built-in functions that can be harnessed to manipulate and analyze different data types. In this comprehensive Python Basics tutorial, we will explore various categories of built-in functions specifically applicable to test automation. We will dive into type conversion functions, mathematical functions, string functions, list functions, and dictionary functions. By mastering these functions, you will be well-equipped to streamline your test automation scripts and enhance your testing efforts.

Type Conversion Functions

Type conversion functions play a pivotal role in test automation, particularly when dealing with diverse data types and performing operations requiring data type transformations. Python Basics provides several built-in functions that facilitate seamless type conversions. Let's explore some examples:


# Converting a string to an integer
age_str = "25"
age_int = int(age_str)
print(age_int)  # Output: 25

# Converting a float to an integer
price_float = 9.99
price_int = int(price_float)
print(price_int)  # Output: 9

# Converting a string to a float:
price_str = "9.99"
price_float = float(price_str)
print(price_float)  # Output: 9.99

# Converting an integer to a string:
quantity_int = 10
quantity_str = str(quantity_int)
print(quantity_str)  # Output: "10"

# Converting a string to an integer using a specific base
binary_str = "101010"
decimal_num = int(binary_str, 2)
print(decimal_num)  # Output: 42

Execution result:

 Mathematical calculations are integral

Mathematical Functions

Mathematical calculations are integral to test automation, whether it involves data analysis, validation, or generating test data. Python Basics offers an extensive set of mathematical functions to handle numerical computations. Let's explore some examples:


# Calculating the absolute value
num = -10
abs_num = abs(num)
print(abs_num)  # Output: 10

# Generating a random number within a range
import random

random_num = random.randint(1, 10)
print(random_num)  # Output: Random number between 1 and 10

# Calculating the square root
import math

num = 16
sqrt_num = math.sqrt(num)
print(sqrt_num)  # Output: 4.0

# Rounding a floating-point number to a specified decimal place
value = 3.14159
rounded_value = round(value, 2)
print(rounded_value)  # Output: 3.14

Execution result:

manipulation is a common task in test automation

String Functions

String manipulation is a common task in test automation, encompassing activities such as parsing inputs, validating outputs, or generating test data. Python Basics provides a rich set of string functions to facilitate these tasks. Let's explore some examples:


# Checking if a string starts with a specific substring
url = "https://www.example.com"
starts_with_https = url.startswith("https")
print(starts_with_https)  # Output: True

# Splitting a string into a list
text = "python,javascript,java"
programming_languages = text.split(",")
print(programming_languages)  # Output: ['python', 'javascript', 'java']

# Finding the index of a substring within a string
sentence = "This is a test case."
index = sentence.find("test")
print(index)  # Output: 10

# Replacing a substring with another substring in a string
sentence = "This is a python code."
new_sentence = sentence.replace("python", "javascript")
print(new_sentence)  # Output: "This is a javascript code."

# Converting a string to uppercase:
message = "your selenium version is 4.9!"
uppercase_message = message.upper()
print(uppercase_message)  # Output: "YOUR SELENIUM VERSION IS 4.9!"

# Converting a string to lowercase:
message = "YOUR SELENIUM VERSION IS 4.9!"
uppercase_message = message.lower()
print(uppercase_message)  # Output: "your selenium version is 4.9!"

Execution result:

indispensable-data-structures-in-test-automation

List Functions

Lists are indispensable data structures in test automation, often used for storing and manipulating data sets. Python Basics provides numerous built-in functions to facilitate efficient list manipulation. Let's explore some examples:


# Checking if an element exists in a list
test_cases = ["login", "register", "checkout"]
exists = "login" in test_cases
print(exists)  # Output: True

# Removing duplicates from a list
test_cases = ["login", "login", "register", "checkout", "register", "register"]
unique_data = list(set(test_cases))
print(unique_data)  # Output: ["login", "checkout", "register"]

# Counting the occurrences of an element in a list
test_cases = ["login", "login", "register", "checkout", "register", "register"]
count = test_cases.count("register")
print(count)  # Output: 3

# Sorting a list in ascending order
test_cases = ["login", "login", "register", "checkout", "register", "register"]
test_cases.sort()
print(test_cases)  # Output: ["checkout", "login", "login", "register", "register", "register"]

# Extending a list by appending elements from another list
test_cases_1 = ["login", "register", "checkout"]
test_cases_2 = ["logout", "profile", "cancel"]
test_cases_1.extend(test_cases_2)
print(test_cases_1)  # Output: ["login", "register", "checkout", "logout", "profile", "cancel"]

Execution result:

valuable data structures in test automation

Dictionary Functions

Dictionaries are valuable data structures in test automation, often employed for managing key-value pairs. Python provides various built-in functions to manipulate and extract information from dictionaries effectively. Let's explore some examples:


# Retrieving all keys from a dictionary
test_case = {"name": "Login", "execution_time_sec": 15, "status": "passed"}
keys = test_case.keys()
print(keys)  # Output: dict_keys(['name', 'execution_time_sec', 'status'])

# Checking if a key exists in a dictionary
test_case = {"name": "Login", "execution_time_sec": 15, "status": "passed"}
exists = "name" in test_case
print(exists)  # Output: True

# Accessing the values of a dictionary
test_case = {"name": "Login", "execution_time_sec": 15, "status": "passed"}
values = test_case.values()
print(values)  # Output: dict_values(['Login', 15, 'passed'])

# Removing a key-value pair from a dictionary
test_case = {"name": "Login", "execution_time_sec": 15, "status": "passed"}
removed_value = test_case.pop("execution_time_sec")
print(removed_value)  # Output: 15

# Merging two dictionaries
test_case_info = {"name": "Login", "execution_time_sec": 15, "status": "passed"}
test_case_data = {"type": "positive", "environment": "production"}
merged_dict = {**test_case_info, **test_case_data}
print(merged_dict)  # Output: {'name': 'Login', 'execution_time_sec': 15, 'status': 'passed', 'type': 'positive', 'environment': 'production'}

Execution result:

Built-in functions in Python serve as powerful tools

Built-in functions in Python serve as powerful tools for test automation. Type conversion functions, mathematical functions, string functions, list functions, and dictionary functions enable seamless data manipulation, numerical computations, string analysis, list management, and dictionary operations. Harness the power of Python's built-in functions to enhance the quality and effectiveness of your test automation efforts.

Useful Python Snippets

In this section of this Python Basics tutorial, we will explore useful Python snippets that can enhance your test automation scripts. We will cover various functionalities, including reading and writing CSV files, generating random numbers, removing duplicates from a list, reversing a string, and finding the largest and smallest elements in a list.

These snippets will provide valuable tools to streamline your test automation process. So, let's dive right in and discover these powerful Python Basics techniques!

Reading and Writing CSV Files

CSV (Comma-Separated Values) files are widely used in many contexts.

In the context of automation and data-driven testing, reading and writing CSV files is highly relevant. CSV files are a common format for storing test data, such as input values, expected results, and test configurations.

By leveraging the capabilities of the CSV module, you can easily read data from CSV files and populate your test cases with the necessary input values. This enables you to create data-driven tests, where you can iterate over different data sets without modifying the test logic.

Similarly, writing data to CSV files is beneficial for capturing test results, logging information, and generating reports. You can store the output of your tests, including actual results and relevant metrics, in a structured format that is easily accessible and analyzable. Python Basics offers convenient methods to read and write data from/to CSV files using the CSV module. Here's an example:


import csv

# Reading CSV File
with open('testdata.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# Writing to CSV File
data = [['Name', 'Age'], ['John', 30], ['Jane', 25]]
with open('output.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

Running this code in the console, we have the below result:


Running this code in the console

Also, a file named output.csv is created with the below structure:


file named output.csv is created

Generating Random Numbers

Randomized test data is crucial for effective testing. Python's random module provides functions to generate random numbers. Here's an example:


import random

# Generating a Random Integer
random_integer = random.randint(1, 10)
print(random_integer)

# Generating a Random Float
random_float = random.uniform(0.0, 1.0)
print(random_float)

Execution result:

Removing Duplicates from a List

Removing Duplicates from a List

In test automation, it's common to work with lists containing duplicate elements. Python provides an easy way to remove duplicates using the set data structure. Here's an example:


numbers = [1, 2, 3, 3, 4, 5, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)

Execution result:

Reversing a string can be useful

Reversing a String

Reversing a string can be useful in scenarios where you need to validate input/output data. Python Basics allows you to reverse a string using slicing. Here's an example:


message = "Python and Selenium for test automation is your best choice!"
reversed_message = message[::-1]
print(reversed_message)

Execution result:

Finding the Largest and Smallest Elements in a List

Finding the Largest and Smallest Elements in a List

When dealing with test data, it's often necessary to find the largest and smallest elements in a list. Python provides the max() and min() functions to accomplish this. Here's an example:


numbers = [5, 2, 8, 1, 9, 3]
largest_number = max(numbers)
smallest_number = min(numbers)
print("Largest:", largest_number)
print("Smallest:", smallest_number)

Execution result:

snippets can greatly enhance your test

These snippets can greatly enhance your test automation scripts by providing efficient solutions to common tasks. Incorporate them into your workflows to save

Automation Testing Frameworks in Python

Python offers a wide range of powerful automation testing frameworks that simplify the process of writing and executing test cases. In this section of the Python Basics tutorial, we will explore four popular automation testing frameworks in Python: pytest, Behave, Robot, and unittest. We will delve into the details of each framework, including its features, installation process, and how they can be leveraged for effective test automation.

To demonstrate how to use each of the frameworks presented in this Python Basic tutorial section on a cloud grid platform, we will automate a test scenario of the LambdaTest ToDo Sample App.

The test scenario we will automate is

The test scenario we will automate is:

Test Scenario:

  • Open the ToDo App page.
  • Click to check the first ToDo item.
  • Check that it should be marked as done.
  • Add a new ToDo item.
  • Check that the total number of ToDos should be 6.
  • Close the browser

The demonstration will be done on a cloud-based grid like LambdaTest, a digital experience testing platform that helps developers and testers to perform Python automation testing of their websites or web applications on over 3000+ real browsers and operating system combinations. While performing automation testing on LambdaTest, you can run your automated tests in parallel across multiple browsers and OS combinations, reducing the overall test execution cycles.

You can refer to the documentation to get started with Python testing on LambdaTest.

To perform Selenium Python testing on the LambdaTest cloud grid, you need to use the capabilities to configure the environment where the test will run. In this Python Basics tutorial, we will run the tests with the following characteristics:

  • Selenium 4.0.0
  • OS: Windows 11
  • Browser: Chrome

You can generate the capabilities code from the LambdaTest Capabilities Generator.

Then, you should get the “Username” and “Access Token” from your account in your LambdaTest Profile Section and set it as an environment variable.

...

unittest

Unittest is a built-in testing framework in Python that offers a lightweight and flexible approach to writing test cases. It follows the xUnit style of testing and provides a rich set of assertions and test discovery mechanisms.

Key features of unittest include:

  • Support for test case creation using test classes and methods.
  • Assertions for verifying expected outcomes.
  • Test fixture management for setup and teardown.
  • Test discovery based on naming conventions and test suites.
  • Integration with other testing tools and frameworks.

Unittest comes pre-installed with Python, so there is no need for additional installation steps.

Parallel Selenium automation testing using unittest on Cloud Grid

Implementation


import unittest
import os
from selenium import webdriver
from selenium.webdriver.common.by import By

# Test class to verify the Todo App functionality
class TodoAppTest(unittest.TestCase):
    def test_verify_todo_app_functionality(self):
        username = os.getenv("LT_USERNAME")
        accessToken = os.getenv("LT_ACCESS_KEY")
        gridUrl = "hub.lambdatest.com/wd/hub"

        options = webdriver.ChromeOptions()
        options.browser_version = "113.0"
        options.platform_name = "Windows 11"
        lt_options = {}
        lt_options["username"] = username
        lt_options["accessKey"] = accessToken
        lt_options["build"] = "your build name"
        lt_options["project"] = "your project name"
        lt_options["name"] = "your test name"
        options.set_capability('LT:Options', lt_options)
       
        url = "https://"+username+":"+accessToken+"@"+gridUrl
       
        driver = webdriver.Remote(
            command_executor=url,
            options=options
        )

        driver.get("https://lambdatest.github.io/sample-todo-app/")
        driver.maximize_window()

        checkbox = driver.find_element(By.NAME, "li1")
        checkbox.click()
        assert checkbox.is_selected()

        text_field = driver.find_element(By.ID, "sampletodotext")
        text_field.send_keys("New Item")

        add_button = driver.find_element(By.ID, "addbutton")
        add_button.click()

        todos = driver.find_elements(By.CSS_SELECTOR, "ul.list-unstyled li")
        assert len(todos) == 6

# Run the test class using unittest
if __name__ == '__main__':
    unittest.main()

Code Walkthrough

The test_todo_app.py begins by importing the necessary modules and libraries, including unittest, selenium, and the os module.

ontains-a-test-class-todoapptest

It contains a test class TodoAppTest that verifies the functionality of the ToDo app. The test class extends the unittest. TestCase class allows it to inherit various assertion methods and test runner functionalities from the unittest framework.

Inside the TodoAppTest class, there is a test method called test_verify_todo_app_functionality. This method defines the steps to test the ToDo app functionality. The code starts with the familiar setup to run the tests in LambdaTest. Next, the WebDriver navigates to the ToDo app page and maximizes the window.

element with the name

Then, it performs various actions to test the functionality.

The code locates the checkbox element with the name li1 and clicks on it, ensuring it becomes selected.

into the input field with the id

It then enters the text "New Item" into the input field with the id sampletodotext.

sampletodotext and clicks

After that, it clicks the Add button.

all the list items using

Afterward, it retrieves all the list items using the CSS Selector ul.list-unstyled li and verifies that the count is equal to 6, indicating the successful addition of a new ToDo item.

indicating the successful additionwhich triggers the test

Finally, the test class is executed using the unittest.main() method, which triggers the test discovery and execution process.

provides a structured and

By using the unittest framework, the test_todo_app.py file provides a structured and standardized approach to define and execute test cases for the ToDo app.

To run this test, just run the below command in the project folder.


python -m unittest test_todo_app.py

The result shows that 1 test was executed and passed.

development and testing life cycle

pytest

pytest is a feature-rich and highly extensible testing framework that enables easy test case creation and execution. It provides a simple syntax and a wide range of powerful features that make writing tests in Python more intuitive and efficient.

You can also subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around Selenium testing, Cypress E2E testing, CI/CD, and more.

Key features of pytest include:

  • Support for test discovery and execution based on naming conventions.
  • Powerful test selection and filtering capabilities.
  • pytest fixtures for managing test resources and dependencies.
  • Ability to run parallel tests for faster execution.
  • Seamless integration with other testing tools and frameworks.

To install pytest, you can use pip, the Python package installer, by running the following command in your terminal:


pip install pytest
pytest on Cloud Grid

Parallel Selenium automation testing using pytest on Cloud Grid

Implementation


import pytest
import os
from selenium import webdriver
from selenium.webdriver.common.by import By

@pytest.fixture
def driver():
    username = os.getenv("LT_USERNAME")
    accessToken = os.getenv("LT_ACCESS_KEY")
    gridUrl = "hub.lambdatest.com/wd/hub"

    options = webdriver.ChromeOptions()
    options.browser_version = "latest"
    options.platform_name = "Windows 11"
    lt_options = {}
    lt_options["username"] = username
    lt_options["accessKey"] = accessToken
    lt_options["build"] = "your build name"
    lt_options["project"] = "your project name"
    lt_options["name"] = "your test name"
    options.set_capability('LT:Options', lt_options)
   
    url = "https://"+username+":"+accessToken+"@"+gridUrl
   
    driver = webdriver.Remote(
        command_executor=url,
        options=options
    )

    driver.maximize_window()

    yield driver
   
    driver.quit

# Test function to verify the Todo App functionality
def test_todo_app(driver):
    driver.get("https://lambdatest.github.io/sample-todo-app/")
    driver.maximize_window()

    checkbox = driver.find_element(By.NAME, "li1")
    checkbox.click()
    assert checkbox.is_selected()

    text_field = driver.find_element(By.ID, "sampletodotext")
    text_field.send_keys("New Item")

    add_button = driver.find_element(By.ID, "addbutton")
    add_button.click()

    todos = driver.find_elements(By.CSS_SELECTOR, "ul.list-unstyled li")
    assert len(todos) == 6

Code Walkthrough

The code provided represents a test script named test_todo_app.py that utilizes the pytest framework for testing the functionality of the LambdaTest ToDo sample app. The script begins by importing the necessary modules, including pytest, os, selenium, and By from selenium.webdriver.common.by.

constructs the Selenium WebDriver

The code defines a driver() fixture using the @pytest.fixture decorator. This fixture is responsible for setting up and providing the Selenium WebDriver instance to the test function. It retrieves the LambdaTest credentials (LT_USERNAME and LT_ACCESS_KEY) from the environment variables and constructs the Selenium WebDriver instance with the desired configuration generated from LambdaTest Capabilities Generator.

used to navigate to the ToDo app

Within the test_todo_app() function, the WebDriver is used to navigate to the ToDo app webpage and maximize the browser window.

test proceeds to interact with

The test proceeds to interact with elements on the page. For example, the code locates the checkbox element with the name li1 using the By.NAME locator and clicks on it. Assertions are used to validate the state of the checkbox.

text field and the Add button

Similarly, the code locates the text field and the Add button. The code type in the text field, click on the Add button.

asserts to check that there are now

Finally, it locates the entire list of ToDos and asserts to check that there are now 6 items in the list.

below command in the project folder

To run this test, just run the below command in the project folder.


pytest

The result is presented showing that 1 test was executed and passed.

stakeholder collaboration and

Behave

Behave is a popular behavior-driven development (BDD) framework that allows you to write tests in a natural language format. It promotes stakeholder collaboration and encourages clear communication through feature files and scenario-based testing.

BDD aims to align technical activities with business goals and requirements by promoting shared understanding and communication through a common language.

In BDD, Behave is a popular Python framework that facilitates the implementation of BDD practices. Behave enables teams to write tests using Gherkin, which allows stakeholders to understand and contribute to the test scenarios. The structure of a Behave code follows a specific pattern to ensure clarity and readability.

A typical Behave code structure includes feature files and step definition files. Feature files contain high-level descriptions of the application features and scenarios written in Gherkin syntax. Each scenario comprises the Given, When, and Then steps, which describe the initial context, actions, and expected outcomes.

Step definition files contain the actual Python code that maps the Gherkin steps to their corresponding implementation. These files define step functions decorated with specific annotations that match the Gherkin keywords. The necessary actions and assertions are performed within these functions using the testing framework or other relevant libraries.

By structuring Behave code, teams can easily collaborate and maintain a shared understanding of the tests. The separation of feature files and step definitions promotes modularity and reusability, making it easier to manage and update the tests as the application evolves. With its natural language syntax and well-organized code structure, Behave empowers teams to implement BDD practices effectively and improve the overall quality of their software.

Key features of Behave include:

  • Support for writing tests in a human-readable Gherkin syntax.
  • Ability to define step definitions that map to test actions.
  • Built-in support for data-driven testing.
  • Rich reporting and visualization options.
  • Integration with other testing tools and frameworks.

To install Behave, you can use pip by running the following command:


pip install behave
using Behave on Cloud Grid

Parallel Selenium automation testing using Behave on Cloud Grid

Implementation

Feature File (todo_app.feature)


Feature: Automate Todo App
    Scenario: Verify Todo App functionality
        Given I open the Todo App page
        When I check the first todo
        Then it should be marked as done
        And a new todo can be added
        And the total number of todos should be 6
        And the browser should be closed

Step Definition File (steps.py)


from behave import given, then, when
from selenium import webdriver
from selenium.webdriver.common.by import By
import os

@given('I open the Todo App page')
def open_todo_app_page(context):
    username = os.getenv("LT_USERNAME")
    accessToken = os.getenv("LT_ACCESS_KEY")
    gridUrl = "hub.lambdatest.com/wd/hub"

    options = webdriver.ChromeOptions()
    options.browser_version = "latest"
    options.platform_name = "Windows 11"
    lt_options = {}
    lt_options["username"] = username
    lt_options["accessKey"] = accessToken
    lt_options["build"] = "your build name"
    lt_options["project"] = "your project name"
    lt_options["name"] = "your test name"
    options.set_capability('LT:Options', lt_options)
   
    url = "https://"+username+":"+accessToken+"@"+gridUrl
   
    context.driver = webdriver.Remote(
        command_executor=url,
        options=options
    )

    context.driver.get("https://lambdatest.github.io/sample-todo-app/")
    context.driver.maximize_window()

@when('I check the first todo')
def check_first_todo_checked(context):
    checkbox = context.driver.find_element(By.NAME, "li1")
    checkbox.click()

@then('it should be marked as done')
def check_first_todo_done(context):
    checkbox = context.driver.find_element(By.NAME, "li1")
    assert checkbox.is_selected()

@then('a new todo can be added')
def add_new_todo(context):
    text_field = context.driver.find_element(By.ID, "sampletodotext")
    text_field.send_keys("New Item")
    add_button = context.driver.find_element(By.ID, "addbutton")
    add_button.click()

@then('the total number of todos should be {count:d}')
def check_total_todos_count(context, count):
    todos = context.driver.find_elements(By.CSS_SELECTOR, "ul.list-unstyled li")
    assert len(todos) == count

@then('the browser should be closed')
def close_browser(context):
    context.driver.quit()

Code Walkthrough

The steps.py file in the Behave framework's steps directory contains step definitions that define the behavior of the tests in a natural language format. Each step definition corresponds to a specific step in the feature files and maps it to the actual implementation using Python code.

The code begins by importing the necessary modules and libraries, including behave, selenium, and the os module. At the moment we are writing this article, Behave current version is 1.2.6.

to connect to the LambdaTest cloud grid

The @given decorator defines a step definition for the given step, responsible for opening the ToDo app page. Within this step definition, the code retrieves the required environment variables and sets up the WebDriver to connect to the LambdaTest cloud grid. The ToDo app page is opened, maximizing the browser window.

locates the checkbox element using

The @when decorator defines a step definition for the when step, which checks the first ToDo item. In this step, the code locates the checkbox element using Selenium's find_element method and performs a click action on it.

performs a click action on it.

The @then decorator defines multiple step definitions for the corresponding then steps. The first @then step definition verifies if the first ToDo item is marked as done. It retrieves the checkbox element again and asserts that it is selected.

the checkbox element again

The next@then step definition adds a new ToDo item by locating the text field element, typing on it, and clicking the add button.

asserts the length of the list

The following @then step definition checks if the total number of ToDos matches the expected count. It retrieves all the ToDo elements and asserts the length of the list.

definition checks if the total number

Finally, the last @then step definition ensures the browser is closed by calling the quit method on the WebDriver instance.

step definition ensures the browser is closed

To run this test, just run the below command in the project folder.


behave
versatile and easy-to-use automation

Robot

Robot framework is a versatile and easy-to-use automation testing framework that supports keyword-driven and data-driven testing approaches. It provides a comprehensive set of libraries and tools for creating, executing, and managing test cases.

Key features of the Robot framework include:

  • Simple and readable test syntax using keywords.
  • Built-in libraries for web testing, database testing, API testing, and more.
  • Support for creating custom libraries and extending functionality.
  • Easy integration with external tools and frameworks.
  • Extensive reporting and logging capabilities.

Also, explore the top robot framework interview questions. The robot framework simplifies software testing with Python, making it valuable for online, mobile, desktop, and API testing. Ace your interview with our expertly curated questions.

To install Robot framework, you can use pip by running the following command:


pip install robotframework
by running the following command

Parallel Selenium automation testing using Robot Framework on Cloud Grid

Implementation

Robot Common File (common.robot)


*** Settings ***
Library  SeleniumLibrary
 
*** Variables ***
 
&{options}          browserName=Chrome     platform=Windows 11       version=latest      name=your test name    buildName=your build name        projectName=your project name
&{CAPABILITIES}     LT:Options=&{options}
${REMOTE_URL}       http://%{LT_USERNAME}:%{LT_ACCESS_KEY}@hub.lambdatest.com/wd/hub
*** Keywords ***
 
Open test browser
    Open browser  https://lambdatest.github.io/sample-todo-app/
    ...  remote_url=${REMOTE_URL}
    ...  desired_capabilities=${CAPABILITIES}
 
Close test browser
    Close all browsers

Robot Test File (todo_app.robot)


*** Settings ***
Resource    common.robot
Test Setup  common.Open test browser
Test Teardown  common.Close test browser

*** Test Cases ***
Verify Todo App Functionality
    ${checkbox}    Get WebElement    name=li1
    Select Checkbox    ${checkbox}
    Checkbox Should Be Selected    ${checkbox}
    Input Text  id=sampletodotext   New Item
    Click Button    id=addbutton
    ${todos}    Get WebElements    css=ul.list-unstyled li
    Length Should Be    ${todos}    6
    Close Browser

Code Walkthrough

The common.robot file contains the common settings, variables, and keywords used in the Robot framework test automation framework. The file starts with the Settings section, where the SeleniumLibrary is imported to provide the necessary keywords for Python web automation.

To use the SeleniumLibrary you need

To use the SeleniumLibrary you need to install it using the pip command below:


pip install robotframework-seleniumlibrary
defined to construct the remote URL

In the Variables section, two variables are defined using the &{variable} syntax. The &{options} variable holds the desired capabilities for the Chrome browser, including the browser name, platform, version, test name, build name, and project name. The &{CAPABILITIES} variable stores the capabilities using the LT:Options key.

The ${REMOTE_URL} variable is defined to construct the remote URL for connecting to the LambdaTest cloud grid. It uses string interpolation to include the LambdaTest username and access key in the URL.

The Open test browser keyword is responsible

The Keywords section defines two keywords. The Open test browser keyword is responsible for opening the browser and navigating to the Todo App page. It uses the Open browser keyword from the SeleniumLibrary, passing the remote URL and desired capabilities as arguments.

The Close test browser is a high-level keyword used to close all open browsers. It calls the Close all browsers low-level keyword from the SeleniumLibrary.

By encapsulating these common actions into keywords

By encapsulating these common actions into keywords, the common.robot file promotes reusability and modularity in test cases. Test cases can import and use these keywords to perform browser setup and teardown, eliminating duplication and ensuring consistent behavior across different test cases.

The todo_app.robot file contains the test case Verify Todo App Functionality , which verifies the functionality of the ToDo app. The file starts with the Settings section, where the common.robot resource file is imported. This allows the test case to use the common keywords defined in the common.robot file. The Test Setup and Test Teardown settings specify that the Open test browser keyword should be executed before the test case and the Close test browser keyword should be executed after the test case.

then used to select the checkbox

The test case Verify Todo App Functionality starts by using the Get WebElement keyword to locate the checkbox element with the name li1 and assigns it to the variable ${checkbox}. The Select Checkbox keyword is then used to select the checkbox. The Checkbox Should Be Selected keyword verifies that the checkbox is indeed selected.

Next, the Input Text keyword is used to enter the text New Item into the input field with the id sampletodotext. The Click Button keyword is used to click the button with the id addbutton.

The Get WebElements keyword is used to locate all the list items in the unordered list with the CSS selector ul.list-unstyled li and assigns them to the variable ${todos}. The Length Should Be keyword verifies that the length of ${todos} is equal to 6, indicating that a new ToDo item has been added successfully.

Finally, the Close Browser keyword is used to close the browser after the test case finishes.

The result is presented

To run this test, just run the below command in the project folder.


robot .

The result is presented, showing that 1 test was executed and passed.

Python provides a rich ecosystem of automation testing frameworks

Python provides a rich ecosystem of automation testing frameworks, each catering to different testing approaches and requirements. Whether you prefer a simple and lightweight framework like pytest or unittest or a more feature-rich and expressive framework like Behave or Robot, Python has a solution for you.

Looking to become a Python automation testing expert? Kickstart your journey by enrolling in a Selenium Python 101 certification program. This excellent choice will enhance your Python Basics skills and lay a solid foundation for effectively utilizing Selenium Python in your testing projects, empowering you to excel in automation testing.

Conclusion

In conclusion, Python is a dynamic and versatile programming language that has gained immense popularity due to its simplicity and extensive range of libraries and frameworks. It offers many advantages for quality assurance engineers, making it a preferred choice for test automation.

Throughout this Python Basics tutorial, we have delved into the fundamental aspects of Python, including data types, operators, control flow statements, functions, modules, and input/output operations. Additionally, we have explored some handy Python snippets and highlighted the main features of well-known automation testing frameworks like pytest, Behave, Robot, unittest, and Lettuce.

By mastering Python Basics and harnessing its built-in functions and libraries, you can streamline your test automation process and develop robust and efficient tests. Whether you opt for the simplicity and flexibility of pytest, unittest, and Robot framework or embrace the behavior-driven approach of Behave, there is a testing framework tailored to suit your specific needs.

It is crucial to remember that this Python Basics tutorial serves as a concise reference guide to Python Basics to assist you in navigating Python's syntax, functions, and testing frameworks.

Embrace Python as your language of choice for test automation, capitalize on its strengths, and witness the enhanced efficiency and reliability it brings to your testing endeavors.

Frequently asked questions

  • General ...
What are the basics about Python?
Python is a popular high-level programming language known for its simplicity and readability. It is widely used in various domains, including web development, data analysis, artificial intelligence, scientific computing, and more. Some key basics about Python are: easy readable syntax, interpreted language, dynamically typed, supports object-oriented programming principles, and more.

Author's Profile

...

Paulo Oliveira

Paulo is a Quality Assurance Engineer with more than 15 years of experience in Software Testing. He loves to automate tests for all kind of applications (both backend and frontend) in order to improve the team’s workflow, product quality, and customer satisfaction. Even though his main roles were hands-on testing applications, he also worked as QA Lead, planning and coordinating activities, as well as coaching and contributing to team member’s development. Sharing knowledge and mentoring people to achieve their goals make his eyes shine.

Hubs: 05

  • Linkedin

Reviewer's Profile

...

Himanshu Sheth

Himanshu Sheth is a seasoned technologist and blogger with more than 15+ years of diverse working experience. He currently works as the 'Lead Developer Evangelist' and 'Senior Manager [Technical Content Marketing]' at LambdaTest. He is very active with the startup community in Bengaluru (and down South) and loves interacting with passionate founders on his personal blog (which he has been maintaining since last 15+ years).

  • Twitter
  • Linkedin

Did you find this page helpful?

Helpful

NotHelpful

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud