A Python script is just a .py file with code that runs top to bottom. There's no class to declare, no main method to wrap your logic in, no semicolons to remember. This lesson walks through the few primitives every Python program is built from — printing output, doing arithmetic, leaving comments, formatting strings — and ends with a 12-line script that builds a real test-run summary. By the end you'll be writing useful scripts on your own.
print() — your console output
print() is Python's way of writing to the terminal. It's the equivalent of console.log() in JavaScript or System.out.println() in Java — but cleaner.
print("Test started")Output:
Test started
Pass any value — number, boolean, string — print converts it to text for you:
print(200)
print(True)
print(3.14)Output:
200
True
3.14
Pass several values separated by commas — print puts a space between them automatically:
print("Status:", 200, "OK")Output:
Status: 200 OK
Notice three small but important things:
- No semicolons. Statements end at the newline.
- No curly braces. A script's "block" is just the file itself.
Trueis capitalised. Different from JavaScript'strueand Java'strue. Capital T, capital F. Mixing them up is one of the first errors every beginner hits.
Indentation matters — but not yet
Python uses indentation instead of curly braces to mark blocks. A function body, a loop body, an if branch — all are defined by the indent level. We'll see this in chapter 2 when we meet if and loops. In a one-line script, there's no block to worry about — every line starts at column 1.
Comments — code for humans
Python uses # for single-line comments. Anything after # on the line is ignored:
# Print a friendly greeting
print("Hello, QA!") # this comment is at the end of a linePython has no syntax for multi-line comments. People use one of two patterns:
# A multi-line note
# usually written as
# several single-line comments stacked.
"""
A triple-quoted string is technically a string,
but if it isn't assigned to anything Python ignores it.
This is the conventional way to write doc comments.
"""The triple-quoted form is reserved for docstrings — the official way to document functions, classes, and modules. We'll meet docstrings properly in chapter 5.
Arithmetic — the operators you'll actually use
Python's number operators look familiar, with two extras:
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | True division | 7 / 2 | 3.5 |
// | Integer division | 7 // 2 | 3 |
% | Modulo | 7 % 2 | 1 |
** | Power | 2 ** 10 | 1024 |
The two surprises if you come from Java or JavaScript:
/always produces a float.7 / 2is3.5, not3. Java'sint / inttruncates; Python's/doesn't. Use//if you want truncation.**is the power operator. No need forMath.pow(2, 10)— write2 ** 10.
A small QA example — calculating a pass rate from counts:
total_tests = 32
passed = 28
failed = total_tests - passed
pass_rate = (passed / total_tests) * 100
print("Pass rate:", pass_rate, "%")Output:
Pass rate: 87.5 %
That output works but reads awkwardly — there's a space before % and the number has no formatting. f-strings fix both.
f-strings — Python's template literals
An f-string (format string) lets you embed variables and expressions directly inside a string literal. Prefix the string with f and put expressions inside {}:
name = "Login Test"
status = "PASSED"
duration = 1250
print(f"✅ {name}: {status} ({duration}ms)")Output:
✅ Login Test: PASSED (1250ms)
f-strings (introduced in Python 3.6) are the modern, idiomatic way to format strings. They are the equivalent of JavaScript's backtick templates: `Hello ${name}` becomes f"Hello {name}".
You can put any Python expression inside the braces — variables, arithmetic, function calls:
passed = 28
total = 32
print(f"Pass rate: {passed / total * 100}%")
print(f"Failed: {total - passed}")Output:
Pass rate: 87.5%
Failed: 4
Format specifiers — controlling how values appear
After the expression you can add : followed by a format spec. The two you'll use most:
pass_rate = 0.875432
print(f"Pass rate: {pass_rate:.1%}") # 87.5% — percent with 1 decimal
print(f"Pass rate: {pass_rate * 100:.2f}%") # 87.54% — float with 2 decimals
print(f"{'Login':<10} | {'PASSED':>8}") # left/right pad to widthOutput:
Pass rate: 87.5%
Pass rate: 87.54%
Login | PASSED
:.2f means "format as a float with 2 decimal places." :.1% means "format as a percentage with 1 decimal." :<10 pads on the right to 10 characters; :>10 pads on the left.
String concatenation — possible but not preferred
You can join strings with +, but unlike JavaScript and Java, Python does not convert numbers automatically:
name = "Login"
status = 200
# print(name + " " + status) # ERROR — can't concatenate str + int
print(name + " " + str(status)) # works, ugly
print(f"{name} {status}") # idiomaticThe first commented line raises TypeError: can only concatenate str (not "int") to str. Either wrap the int in str() or use an f-string. f-strings are almost always cleaner — reach for them by default.
Reading input from the user
input() pauses the script, prints a prompt, and returns whatever the user types as a string:
name = input("Enter your name: ")
print(f"Hello, {name}!")Run it, type Alice, press Enter:
Enter your name: Alice
Hello, Alice!
Two things to remember about input():
- It always returns a string, even if the user types digits. To use the value as a number, wrap it:
age = int(input("Age: ")). - It blocks the script until the user presses Enter. Useful for small CLI tools and quick scripts; not what you want inside automated tests (which run unattended).
A real QA example — a test summary
A script that prints a nightly run summary, exactly the kind of utility you'd write in your first month on the job. Save as nightly_summary.py:
suite_name = "checkout-suite"
total = 34
passed = 28
failed = 4
skipped = 2
duration_seconds = 215
pass_rate = passed / total
print("=== Nightly Test Run ===")
print(f"Suite: {suite_name}")
print(f"Total: {total}")
print(f"Passed: {passed}")
print(f"Failed: {failed}")
print(f"Skipped: {skipped}")
print(f"Pass rate: {pass_rate:.1%}")
print(f"Duration: {duration_seconds // 60} min {duration_seconds % 60} sec")
print("========================")Run:
python nightly_summary.pyOutput:
=== Nightly Test Run ===
Suite: checkout-suite
Total: 34
Passed: 28
Failed: 4
Skipped: 2
Pass rate: 82.4%
Duration: 3 min 35 sec
Twelve lines and you have a clean, formatted summary — no class declarations, no scaffolding. That brevity is exactly why teams reach for Python for quick scripts.
Match each piece to its job
Each Python construct does a specific job
Match each piece of Python syntax to what it does.
- print('hello')
- f'Pass: {rate:.1%}'
- # this is a note
- duration // 60
- input('Name: ')
⚠️ Common mistakes
- Lowercase
true/false. Python usesTrueandFalsewith capital first letters.if x == true:is aNameError. JavaScript and Java both lowercase these — don't carry the habit over. - Forgetting the
fon a format string. Writingprint("Pass rate: {pass_rate:.1%}")— without the leadingf— prints the literal text{pass_rate:.1%}instead of the value. f-strings only work when prefixed withf. - Concatenating a number to a string.
"Status: " + 200raisesTypeError. Either wrap the number instr(...)or, better, use an f-string:f"Status: {200}".
🎯 Practice task
Build a real Python summary tool. 20-30 minutes.
-
In your
python-for-qafolder, create a filerun_report.py. -
Declare these variables at the top:
suite = "checkout-suite"passed = 47failed = 3duration_seconds = 215(pick whatever values you like)
-
Calculate
total = passed + failed. -
Use
printand f-strings to produce this output (substituting your numbers):Suite: checkout-suite Total: 50 | Passed: 47 | Failed: 3 Pass rate: 94.0% Duration: 3 min 35 secHints:
:.1%for the pass rate,//and%for the minutes/seconds split. -
Run with
python run_report.py. Confirm the output matches your inputs. -
Add a final line that prints
"⚠️ Some tests failed!"only iffailed > 0— but you'll need aniffor that, which is the next lesson. For now: just hard-code the line and read on. -
Stretch: open a Python REPL (
python3with no filename) and try f-string format specifiers interactively:>>> f"{1/7:.4f}" >>> f"{1234567:,}" >>> f"{'Login':<15}|{'PASSED':>10}"Observe what each format option does. Exit with
exit().
You now have the building blocks of every Python script. The next lesson formalises variables and types so the values inside your scripts stop being magic.