Python Basics & Setup
Welcome to the very first step of your journey into test automation with Python. This module assumes you have never written a line of code in your life, and that is exactly how we will treat it. By the end you will have Python installed, a proper editor open, and your own scripts running—printing messages, storing values, asking the user for input, and converting between data types. More importantly, you will understand why each piece exists and how it connects to the automated tests you will eventually write. We build slowly, we explain everything, and nothing is left as magic.
Learning objectives
By the end of this lesson you will be able to:
- Explain what Python is and why it is the dominant language for test automation.
- Install Python on your machine and confirm it works from the command line.
- Understand what
pipis and the role it plays in a test project. - Set up a professional editor (VS Code or PyCharm) and run your first script.
- Use the interactive REPL to experiment and use
print()to produce output. - Write comments, create variables, and work with the core data types:
int,float,str, andbool. - Convert between types, read input with
input(), and respect Python’s strict indentation rules.
What Python is, and why testers love it
Python is a general-purpose programming language created by Guido van Rossum and first released in 1991. A programming language is simply a way of writing precise instructions that a computer can carry out. What sets Python apart is that its instructions read almost like plain English: where other languages drown you in punctuation and boilerplate, Python aims for code that a human can read aloud and roughly understand. That readability is not a cosmetic nicety—it is the single biggest reason Python has become the default choice for people whose main job is not writing software, which includes most testers.
For a tester, Python hits a sweet spot. It is quick to learn, it has a vast ecosystem of ready-made libraries—pytest for structuring tests, requests for calling APIs, selenium and playwright for driving browsers—and it is everywhere in the QA world, so answers, examples, and jobs are plentiful. You will use the fundamentals from this very module—variables, types, input—every time you write a test that stores an expected value and compares it to an actual one.
Where this shows up in real testing
Imagine a test that logs into a website and checks the welcome banner. Behind the scenes it stores an expected string ("Welcome, Tom"), reads the actual text from the page, and compares them. That is nothing more than two string variables and a comparison—exactly what you learn today. Every automated test, no matter how sophisticated, is built from these same atoms: values held in variables, of specific types, combined and compared. Master the basics here and the advanced modules become assembly rather than mystery.
Installing Python
Head to the official site, python.org, go to the Downloads section, and grab the latest stable version for your operating system (Python 3.12 or newer is ideal; anything 3.10+ is fine for this course). Python 2 is long dead—always use Python 3.
On Windows, run the installer and—the one step beginners miss—tick the checkbox labelled “Add Python to PATH” before clicking Install. PATH is the list of places your system looks for programs; adding Python to it lets you type python from any terminal. On macOS and Linux a version is often preinstalled, but it is safest to install the current release from python.org (macOS) or your package manager (Linux).
To confirm it worked, open a terminal—Command Prompt or PowerShell on Windows, Terminal on macOS/Linux—and type:
python --version
You should see something like Python 3.12.4. If Windows reports that python is not recognised, the PATH checkbox was likely missed—re-run the installer and tick it. On macOS/Linux you may need to type python3 instead of python.
pip: Python’s package installer
When you install Python you also get pip, the tool that downloads and installs packages—bundles of code other people have written and shared. This is central to testing, because your test frameworks arrive as packages. You will not install anything serious until Module 3, but it is worth confirming pip is present now:
pip --version
Later, installing a testing library will be as simple as pip install pytest. Think of pip as an app store for Python code: one command and a professional-grade library is in your project.
Tutor tip: type the commands, do not copy them
Through this whole course, resist the urge to copy-paste every command and snippet. Type them by hand. It feels slower, but your fingers and eyes learn the syntax—where the colons and parentheses go, how indentation lines up—far faster than your brain does by reading. Typos you make and fix are lessons; code you paste and run is forgotten by lunchtime.
Choosing an editor (IDE)
You can write Python in Notepad, but you should not. An IDE (Integrated Development Environment) or smart code editor gives you syntax highlighting, autocomplete, error underlines, and a built-in way to run your code. Two dominate the Python world:
- Visual Studio Code (VS Code) — free, lightweight, hugely popular. Install it, then add the official Python extension from Microsoft. The recommended starting point for most people.
- PyCharm — a dedicated Python IDE from JetBrains. The Community Edition is free, capable, and has excellent built-in support for test frameworks; favoured by many professional SDETs.
Either is fine. We keep instructions editor-neutral: whatever you pick, you need to create a .py file, type code into it, and run it.
Your first script
Create a new file called hello.py. The .py extension is what marks a file as Python source code. Inside it, type exactly one line:
print("Hello, QA world!")
Save it, then run it from a terminal opened in the same folder:
python hello.py
The terminal prints Hello, QA world!—you have written and executed a program. Dissecting that line: print is a built-in function (a named action you can call); the parentheses () are how you call it; and whatever you put inside is passed to it—here the text "Hello, QA world!", where the double quotes mark it as a string.
The REPL: Python’s interactive playground
You do not always need a file. Type python on its own (no filename) and press Enter. The prompt changes to >>>. You are now in the REPL—Read, Evaluate, Print, Loop—an interactive mode where you type one line and immediately see its result. It is perfect for trying things out.
>>> 2 + 2
4
>>> print("testing the repl")
testing the repl
>>> name = "Priya"
>>> name
'Priya'
Notice that in the REPL you often do not even need print()—just typing an expression shows its value. To leave the REPL, type exit() and press Enter (or press Ctrl+Z then Enter on Windows, Ctrl+D on macOS/Linux). Use the REPL constantly to check “what does this do?” without creating a file.
Comments
A comment is a note for humans that Python ignores completely. Anything after a # on a line is a comment. Comments explain why code does something, which is far more valuable than restating what it does.
# This is a comment; Python skips it entirely.
print("Running smoke test") # comments can also sit after code
# Good comments explain intent:
# We wait 2 seconds because the banner animates in slowly.
Python has no dedicated multi-line comment syntax—you simply start each line with #. (You will later see triple-quoted strings used as documentation, but that is a different feature.)
Variables
A variable is a name that refers to a value. You create one with the = sign, which means “assign the value on the right to the name on the left.” It is not the equals of mathematics; it is an arrow pointing a label at a value.
browser = "Chrome"
test_count = 25
pass_rate = 0.96
is_release_build = True
print(browser) # Chrome
print(test_count) # 25
Python is dynamically typed: you never declare what kind of value a variable holds—Python works it out from what you assign. You can even point the same name at a different kind of value later, though doing so carelessly leads to confusing code. Good variable names are lowercase, descriptive, and use underscores between words (test_count, not tc or testCount). This convention is called snake_case and it is the Python standard.
Core data types
Every value in Python has a type—a category that determines what you can do with it. The four you will use most from day one are:
| Type | Name | Example | Used for |
|---|---|---|---|
int |
Integer | 25, -3, 0 |
Whole numbers: counts, indexes, retries. |
float |
Floating-point | 0.96, 3.14, -0.5 |
Decimal numbers: timings, percentages. |
str |
String | "Chrome", 'ok' |
Text: names, messages, URLs, HTML. |
bool |
Boolean | True, False |
Yes/no facts: did the test pass? |
You can ask any value its type with the built-in type() function—a habit worth forming:
print(type("Chrome")) # <class 'str'>
print(type(25)) # <class 'int'>
print(type(0.96)) # <class 'float'>
print(type(True)) # <class 'bool'>
Strings can use single or double quotes—'ok' and "ok" are identical—just be consistent. Booleans must be capitalised: True/False, never true/false. A tester’s mind should light up here: the result of a test—passed or failed—is a Boolean, and “does actual equal expected?” produces one.
Going deeper: why strings and numbers are not interchangeable
The text "25" and the number 25 look the same to a human but behave completely differently to Python. Try this in the REPL:
>>> "25" + "3"
'253'
>>> 25 + 3
28
With strings, + means join (concatenate), giving '253'; with numbers it means add, giving 28. This matters enormously in testing because data read from a web page, a file, or a user is almost always a string: read the item count from a cart and you get the text "3", not the number 3—so "3" + "1" gives "31", not 4. The fix is type conversion, which is next.
Type conversion
Type conversion (or casting) turns a value of one type into another using the type’s name as a function: int(), float(), str(), bool().
items_text = "3" # a string, e.g. read from a web page
items = int(items_text) # convert to an integer -> 3
print(items + 1) # 4 (now arithmetic works)
price = float("19.99") # string -> float -> 19.99
count = str(42) # int -> string -> "42"
print("Cart has " + str(items) + " items") # join text and number safely
The last line shows a crucial habit: to glue a number into a message with +, convert it to a string first, or Python raises a TypeError. Not every conversion is possible—int("hello") fails with a ValueError because "hello" is not a number. We will handle such errors gracefully in a later module.
input() always gives you a string
This trips up nearly every beginner. The input() function, which reads what the user types, always returns a string—even when the user types a number. So this looks right but is wrong:
age = input("Enter your age: ") # user types 30
print(age + 1) # TypeError! age is the string "30", not the number 30
The value of age is the string "30", and you cannot add the number 1 to a string. The fix is to convert immediately:
age = int(input("Enter your age: ")) # read, then convert to int
print(age + 1) # 31 -- correct
Remember this rule: anything from input() is text until you convert it. The same is true of text read from web pages and files, which is why conversion is a daily tool in test automation.
Reading input with input()
The input() function pauses the program, shows an optional prompt, waits for the user to type and press Enter, and returns what they typed as a string.
name = input("What is your name? ")
print("Hello, " + name + "! Let us write some tests.")
environment = input("Which environment? (dev/staging/prod) ")
print("Running the suite against:", environment)
Notice the last print() uses a comma instead of +. When you separate values with commas, print accepts multiple arguments, inserts a space between them, and converts each to text for you—so you can freely mix strings and numbers without casting. It is often the easiest way to print a mixed message.
Indentation: critical in Python
In most languages, indentation is decoration; in Python it is syntax. Python uses indentation—the whitespace at the start of a line—to decide which lines belong together as a block. Where other languages use curly braces, Python uses the shape of your code.
if pass_rate > 0.9:
print("Release looks healthy") # indented -> inside the if
print("Notifying the team") # also inside the if
print("Done") # not indented -> always runs
The two indented lines run only when the condition is true; the last line always runs because it is back at the left margin. We cover if properly in Module 2—for now, just absorb the rule.
The standard is four spaces per level. Do not mix tabs and spaces—Python rejects the file with a TabError or IndentationError. Any good editor can insert four spaces when you press Tab; turn that on and indentation becomes effortless. Inconsistent indentation is the number-one syntax error for newcomers, so let your editor do the work.
Hands-on exercise
Create a file called profile.py and build a tiny interactive script that uses everything from this module:
- Print a welcome line with
print(). - Use
input()to ask for the user’s name (a string) and store it in a variable. - Use
input()to ask how many tests they ran today, and convert it to anintimmediately. - Use
input()to ask the pass rate as a decimal, and convert it to afloat. - Print a summary line that mixes the name, the test count, and the pass rate—using commas in
print()so you do not have to cast. - Add a line that prints
test_count + 5to prove the conversion worked (it should do arithmetic, not join text). - Add at least one comment explaining why you convert the input.
- Bonus: in the REPL, call
type()on each of your variables and confirm you gotstr,int, andfloat.
Knowledge check
- Give two reasons Python is a popular choice for test automation.
- What is
pip, and what will you use it for in a test project? - What does the REPL let you do that running a
.pyfile does not? - Name the four core data types covered and give an example value of each.
- What does
"25" + "3"produce, and why is it different from25 + 3? - What type does
input()always return, and what must you often do to the result? - Why is indentation more important in Python than in many other languages, and what is the standard indent width?
Show answers
- Any two of: it is easy to read and learn; it has a huge ecosystem of testing libraries (pytest, requests, selenium); it is ubiquitous in QA so help and jobs are plentiful.
pipis Python’s package installer; you use it to install testing libraries and other packages, e.g.pip install pytest.- The REPL evaluates one line at a time and immediately shows the result, making it ideal for quick experiments without creating a file.
int(e.g.25),float(e.g.0.96),str(e.g."Chrome"),bool(True/False)."25" + "3"gives the string'253'because+joins strings, whereas25 + 3gives the number28because+adds numbers.input()always returns a string; you must often convert it withint()orfloat()before doing arithmetic.- Python uses indentation as syntax to define code blocks (instead of braces), so getting it wrong changes the program’s meaning or breaks it; the standard is four spaces per level.
Key takeaways
- Python is readable, beginner-friendly, and the default language of test automation—install Python 3 from python.org and confirm with
python --version. pipinstalls packages; an IDE like VS Code or PyCharm gives you a comfortable place to write and run.pyfiles.- Use
print()for output and the REPL for quick experiments; comment with#to record intent. - Variables name values; every value has a type—
int,float,str,boolare the core four—andtype()reveals it. - Convert with
int()/float()/str(); rememberinput()always returns a string, and indentation (four spaces) is real syntax in Python.
Go deeper
Three small facts about Python’s type system pay off the moment you start writing real assertions:
- Booleans are secretly integers.
boolis a subclass ofint, soTrueequals1andFalseequals0. That meanssum([True, False, True])returns2—a neat trick for counting how many checks passed in a list of comparison results. - Floats are approximate. Because decimals are stored in binary,
0.1 + 0.2is0.30000000000000004, not0.3. Never assert exact equality on a computed float; compare with a tolerance (abs(a - b) < 0.001) or round first withround(). - Prefer
isinstance()overtype()for checks.type(x) == intworks, butisinstance(x, int)is the idiomatic way to ask “is this an integer?” and it also respects subclasses.
Python also lets you assign several names at once, which keeps setup code tidy and leans on the fact that a Boolean counts as a number:
passed = failed = skipped = 0 # chained assignment: all three start at 0
expected, actual = "Dashboard", "Dashboard" # multiple assignment in one line
passed += (expected == actual) # True counts as 1, so passed becomes 1
Finally, you can wrap input() directly in a converter, but guard it: int(input(...)) crashes if the user types letters. You will learn to catch that cleanly with try/except in a later module—for now, just know the crash is a ValueError, not a flaw in your logic.