Your First Python Script

7 min read

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() 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:

  1. No semicolons. Statements end at the newline.
  2. No curly braces. A script's "block" is just the file itself.
  3. True is capitalised. Different from JavaScript's true and Java's true. 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 line

Python 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:

OperatorNameExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/True division7 / 23.5
//Integer division7 // 23
%Modulo7 % 21
**Power2 ** 101024

The two surprises if you come from Java or JavaScript:

  • / always produces a float. 7 / 2 is 3.5, not 3. Java's int / int truncates; Python's / doesn't. Use // if you want truncation.
  • ** is the power operator. No need for Math.pow(2, 10) — write 2 ** 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 width

Output:

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}")         # idiomatic

The 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():

  1. It always returns a string, even if the user types digits. To use the value as a number, wrap it: age = int(input("Age: ")).
  2. 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.py

Output:

=== 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 uses True and False with capital first letters. if x == true: is a NameError. JavaScript and Java both lowercase these — don't carry the habit over.
  • Forgetting the f on a format string. Writing print("Pass rate: {pass_rate:.1%}") — without the leading f — prints the literal text {pass_rate:.1%} instead of the value. f-strings only work when prefixed with f.
  • Concatenating a number to a string. "Status: " + 200 raises TypeError. Either wrap the number in str(...) or, better, use an f-string: f"Status: {200}".

🎯 Practice task

Build a real Python summary tool. 20-30 minutes.

  1. In your python-for-qa folder, create a file run_report.py.

  2. Declare these variables at the top:

    • suite = "checkout-suite"
    • passed = 47
    • failed = 3
    • duration_seconds = 215 (pick whatever values you like)
  3. Calculate total = passed + failed.

  4. Use print and 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 sec
    

    Hints: :.1% for the pass rate, // and % for the minutes/seconds split.

  5. Run with python run_report.py. Confirm the output matches your inputs.

  6. Add a final line that prints "⚠️ Some tests failed!" only if failed > 0 — but you'll need an if for that, which is the next lesson. For now: just hard-code the line and read on.

  7. Stretch: open a Python REPL (python3 with 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.

// tip to track lessons you complete and pick up where you left off across devices.