Scripting Intro S1 — Cheatsheet
Python, algorithmic thinking and PowerShell — 2024–2025
Table of Contents
- Algorithms and Basics
- Variables, Types and Operators
- Selection
- Loops
- Strings and Collections
- Functions
- Files
- Debugging and Error Handling
- PowerShell Basics
Algorithms and Basics
An algorithm is a finite, unambiguous sequence of steps that turns input into output. Build the logic first with pseudocode or a flowchart, then translate it into code.
| Flowchart shape | Meaning |
|---|---|
| Oval | start/end |
| Rectangle | processing/assignment |
| Diamond | decision |
| Parallelogram | input/output |
Small steps
Get one case working correctly first. Then add validation, repetition and exception handling.
Variables, Types and Operators
Python
name = input("Name: ")
age = int(input("Age: "))
height = float(input("Height in meters: "))
active = True
print(f"{name} is {age} years old")
| Type | Example |
|---|---|
int |
42 |
float |
3.14 |
str |
"text" |
bool |
True, False |
list |
[1, 2, 3] |
dict |
{"name": "Ada"} |
input() always returns a string. Convert explicitly when you want to calculate.
Operators
| Kind | Python | PowerShell |
|---|---|---|
| add/subtract | +, - |
+, - |
| multiply/divide | *, / |
*, / |
| integer division/remainder | //, % |
[math]::Floor($a/$b), % |
| equal/not equal | ==, != |
-eq, -ne |
| comparison | <, <=, >, >= |
-lt, -le, -gt, -ge |
| logical | and, or, not |
-and, -or, -not |
Order: parentheses → exponents → multiply/divide → add/subtract → comparisons → logical operators.
Selection
Python
score = float(input("Score: "))
if score < 0 or score > 10:
print("Invalid score")
elif score >= 8.5:
print("A")
elif score >= 7.5:
print("B")
else:
print("C or lower")
Python uses indentation to define blocks. The order of conditions matters: test specific/high boundaries before broader/low ones.
PowerShell
$weight = [double](Read-Host 'Weight')
if ($weight -gt 20) {
'Surcharge of 25 euros'
} elseif ($weight -eq 20) {
'Exactly right'
} else {
'Have a good trip!'
}
switch -Wildcard ($department) {
'R&D' { 'Research and development' }
'Sales*' { 'Sales' }
default { $department }
}
Loops
| Construct | Use |
|---|---|
while |
repeat while the condition is true; possibly zero times |
do...while |
at least once, repeat while true |
do...until |
at least once, stop once true |
for |
known number of iterations/counter |
foreach |
each element of a collection |
Python
PowerShell
for ($i = 1; $i -le 10; $i++) {
$i
}
foreach ($item in $items) {
$item
}
do {
$number = [int](Read-Host 'Positive number')
} until ($number -gt 0)
break: exits the nearest loop.continue: skips the rest of the current iteration.exit: ends the entire script/PowerShell session.
foreach versus ForEach-Object
foreach has the collection available upfront and supports break. ForEach-Object processes pipeline objects as they arrive and is suited for streaming.
Strings and Collections
text = "The Holy Hand Grenade"
print(len(text))
print(text.lower())
print(text[0])
print(text[3:10])
vowels = set()
for char in text.lower():
if char in "aeiou":
vowels.add(char)
print(len(vowels))
A list is ordered and mutable; a tuple is ordered and immutable; a set holds unique values; a dictionary maps keys to values.
$names = @('Ada', 'Linus', 'Grace')
$names.Count
$names[0]
$names += 'Guido'
$person = @{ Name = 'Ada'; Age = 36 }
$person.Name
Functions
Functions split a problem into testable, reusable parts.
def calculate_bmi(weight, height):
"""Return BMI rounded to two decimals."""
if height <= 0:
raise ValueError("height must be positive")
return round(weight / height ** 2, 2)
bmi = calculate_bmi(75, 1.80)
| Concept | Meaning |
|---|---|
| Parameter | name in the function definition |
| Argument | concrete value at call time |
| Return value | result for the caller |
| Local variable | exists within the function |
function Get-Bmi {
param(
[Parameter(Mandatory)] [double]$Weight,
[Parameter(Mandatory)] [double]$Height
)
[math]::Round($Weight / ($Height * $Height), 2)
}
Design example: sliding puzzle
Split a larger program into responsibilities:
make_grid() → build the grid and empty position
print_grid() → show the current state
check_move() → validate input
apply_move() → change the state
check_grid() → test the win condition
This avoids one long loop where input, validation, data changes and output are all tangled together.
Files
with open("data.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.rstrip())
with open("result.txt", "w", encoding="utf-8") as file:
file.write("result\n")
| Mode | Effect |
|---|---|
r |
read |
w |
write and overwrite |
a |
append at the end |
x |
create a new file; fails if it already exists |
with also closes the file when an error occurs.
For /etc/passwd-style data:
with open("passwd.txt", encoding="utf-8") as file:
for line in file:
fields = line.rstrip().split(":")
username, uid, home, shell = fields[0], fields[2], fields[5], fields[6]
Debugging and Error Handling
Common errors:
| Error | Cause |
|---|---|
SyntaxError |
code is grammatically invalid |
IndentationError |
incorrect indentation |
NameError |
unknown variable name |
TypeError |
operation doesn't fit the type |
ValueError |
invalid conversion/value |
ZeroDivisionError |
division by zero |
IndexError |
index out of range for the collection |
while True:
try:
divisor = float(input("Divisor: "))
result = 10 / divisor
except ValueError:
print("Enter a number")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(result)
break
Debug systematically: reproduce the error, read the traceback bottom to top, check types and intermediate values, shrink the problem, and test edge cases (0, empty, negative, first/last index).
PowerShell Basics
PowerShell works with objects, not just text. Cmdlets mostly follow Verb-Noun.
Get-Command *Process*
Get-Help Get-Process -Examples
Get-Process | Get-Member
Get-Process |
Where-Object CPU -gt 10 |
Sort-Object CPU -Descending |
Select-Object -First 5 Name, CPU
Variables and interpolation
$name = 'Ada'
$count = 3
"Hello $name, count: $count" # interpolation
'Hello $name' # literal
"Result: $($count * 2)" # expression in a string
Safely converting input
Core rule for solutions
Test deliberately
A program that handles one normal example is not done. Also test wrong types, empty input, boundary values and repeated execution.