Cheatsheets

linux, html or python: This section is my personal library of cheatsheets.


Linux

kurzer Text ΓΌber den Fotos – aber nur als β€žHookβ€œ

Priority Command / Flag What it does Typical example Useful flags / notes
Very often ssh Connects to another computer over the network and gives you its terminal. ssh name@host.local -p = use another port,
-i = use a key file
Very often ls Shows the files and folders in the current folder. ls -l = detailed list,
-a = show hidden files,
-h = human-readable sizes
Very often cd Changes to another folder. cd ~/bme280_logger cd .. = go one folder up,
cd ~ = go home,
cd - = go back to last folder
Very often pwd Shows where you are right now in the file system. pwd No common flags needed for beginners
Very often sudo Runs a command with administrator rights. You need it for important system changes. sudo apt update Use with care: it gives a command more power
Very often nano Opens a simple text editor in the terminal. nano test_bme280.py Ctrl+O = save,
Ctrl+X = exit
Very often clear Clears the terminal screen. clear Ctrl+L does nearly the same thing
Very often mkdir Creates a new folder. mkdir logs -p = also create parent folders if needed
Very often touch Creates an empty file. touch notes.txt Also updates the file time if the file already exists
Very often cp Copies a file or folder. cp test.py backup.py -r = copy folders too,
-v = show what is being copied
Very often mv Moves a file/folder or renames it. mv old.txt new.txt Same command for moving and renaming
Very often rm Deletes a file or folder. rm old.txt -r = delete folders too,
-f = force delete,
-i = ask before deleting
Very often cat Prints the content of a file to the terminal. cat config.txt Good for short files; bad for very long files
Very often tail Shows the last lines of a file. Very useful for logs. tail log.txt -f = keep watching for new lines live
Very often head Shows the first lines of a file. head log.txt Useful for quick checks
Very often python / python3 Runs a Python script. python3 test_bme280.py On Raspberry Pi,
python3 is usually the safe choice
Often apt update Downloads the newest package lists. It does not install updates yet. sudo apt update Usually run before upgrade or install
Often apt upgrade Installs available updates for installed software. sudo apt upgrade -y = answer β€œyes” automatically
Often apt full-upgrade Does a bigger system update and may replace or remove packages if needed. sudo apt full-upgrade -y Useful for full system maintenance
Often apt install Installs new software packages. sudo apt install -y i2c-tools -y = skip the confirmation question
Often apt remove Removes installed software packages. sudo apt remove package-name Removes software, but sometimes leaves config files behind
Often find Searches for files and folders. find . -name "*.py" . means β€œstart here”
Often grep Searches for text inside files or command output. grep error log.txt -i = ignore upper/lower case,
-r = search inside folders too
Often less Opens a file for easy reading, one screen at a time. less long_log.txt Press q to quit
Often history Shows your previous commands. history Very useful when you forgot what you typed earlier
Often !! Runs the last command again. sudo !! Classic trick: rerun the last command with sudo
Often python3 -m venv .venv Creates a Python virtual environment for a project. python3 -m venv .venv Keeps project Python packages separate and tidy
Often source .venv/bin/activate Activates the virtual environment. source .venv/bin/activate After that, Python and pip use the virtual environment
Often jobs Shows programs running in the background in your current terminal. jobs Useful after starting a script with &
Often fg Brings a background job back to the front. fg Good if you want to stop it with Ctrl+C
Often & Starts a command in the background. python3 logger.py & The terminal stays usable after starting the program
Regularly reboot Restarts the Raspberry Pi. sudo reboot Useful after updates or config changes
Regularly shutdown Turns the Raspberry Pi off safely. sudo shutdown -h now -h = halt/power off,
-r = reboot
Regularly raspi-config Opens Raspberry Pi settings like SSH, I2C, SPI, hostname and more. sudo raspi-config Very important on Raspberry Pi systems
Regularly ip a Shows network information like IP addresses. ip a Good when you want to know how the Pi is connected
Regularly hostname Shows the computer name. hostname Useful for SSH and network setup
Regularly ping Tests whether another device or website can be reached over the network. ping raspberrypi.com Press Ctrl+C to stop it
Regularly i2cdetect -y 1 Scans the I2C bus and shows connected I2C devices like the BME280. i2cdetect -y 1 Needs i2c-tools installed; on Raspberry Pi, bus 1 is the normal one
Regularly ps aux Shows running processes. ps aux Useful when you want to find a running script
Regularly top Shows live system activity like CPU, memory and running processes. top Press q to quit
Regularly htop A friendlier and clearer version of top. htop May need installation first: sudo apt install htop
Sometimes kill Stops a running process by its process ID. kill 1234 -9 = force stop; use only if normal stop fails
Sometimes man Shows the manual page for a command. man ls Good when you want the official explanation
Sometimes --help Shows a short help text for many commands. ls --help Faster than reading the full manual page
Sometimes Ctrl+C Stops the currently running command. python3 logger.py then press Ctrl+C Extremely important in daily terminal use
Sometimes TAB Auto-completes file names and commands. Type cd Doc and press TAB Saves time and avoids typing mistakes
Sometimes Arrow Up Shows your previous command in the terminal. Press ↑ Perfect for repeating or editing old commands
Important flags -r Recursive. Usually means β€œalso go through folders and everything inside them”. cp -r myfolder backup/ Common with cp,
rm,
grep
Important flags -f Force. Do it without asking, even if it may be risky. rm -f file.txt Dangerous with delete commands
Important flags -y Automatically answer β€œyes” to questions. sudo apt install -y i2c-tools Useful in package management
Important flags -i Interactive. Usually asks before doing something risky. rm -i file.txt Good for safer deleting
Important flags -v Verbose. Shows more details about what the command is doing. cp -v a.txt b.txt Useful when learning
Important flags -h Human-readable. Shows file sizes in an easy form like KB, MB, GB. ls -lh Very handy when checking file sizes
Important flags -a Shows all files, including hidden ones. ls -a Hidden files often start with a dot, like .bashrc
Important flags -l Long format. Shows more details like permissions, owner and size. ls -l Often combined as ls -lah

Important beginner notes:

↑ top


HTML

HTML is the structural backbone of a webpage. It does not make things β€œpretty” by itself β€” it tells the browser what something is: a heading, a paragraph, a link, an image, a section, a form field.

This cheatsheet focuses on the HTML things you actually use all the time: document structure, text elements, links, images, lists, semantic layout, forms, metadata and a few common traps.


Document basics

Basic document structure

Use: The minimum clean HTML skeleton for a normal page.

<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>My page</title>
    </head>
    <body>
      ...
    </body>
    </html>

Use this as the default starting point for every new HTML file.

<head> vs <body>

Head: invisible page metadata, title, CSS, SEO.

Body: everything visible on the page.

<head>
      <title>Cheatsheets</title>
    </head>

    <body>
      <h1>Hello</h1>
    </body>

Attributes

Attributes add extra information to an element, for example href, src, alt, class or id.

<a href="about.html" class="button">About</a>

Text & structure

Headings: h1 to h6

Use: Page and section structure.

<h1>Main page title</h1>
    <h2>Section title</h2>
    <h3>Subsection title</h3>

Use headings for structure, not just because they look big.

Paragraph: p

Use: Normal blocks of text.

<p>This is a paragraph of text.</p>

Emphasis: strong and em

Use: Meaningful emphasis, not just decoration.

<p>This is <strong>important</strong> and this is <em>emphasized</em>.</p>

Line break and rule: br, hr

Use: Small structural helpers.

<p>Line one<br>Line two</p>

    <hr>

Do not use <br> as a lazy substitute for CSS spacing.


Link: a

Use: Navigation to pages, sections or external websites.

<a href="about.html">About me</a>

External link in new tab

<a 
      href="https://example.com" 
      target="_blank" 
      rel="noopener noreferrer">
      External page
    </a>

Jump link with id

<a href="#contact">Go to contact</a>

    <section id="contact">
      <h2>Contact</h2>
    </section>

Image: img

Use: Photos, graphics, illustrations.

<img 
      src="images/boat.jpg" 
      alt="Small sailing boat in calm evening light">

The alt text matters. β€œimage” is useless. Describe what is actually there.

figure and figcaption

<figure>
      <img src="drone.jpg" alt="Drone on a field">
      <figcaption>First outdoor drone test.</figcaption>
    </figure>

Lists & grouping

Unordered list: ul

<ul>
      <li>HTML</li>
      <li>CSS</li>
      <li>JavaScript</li>
    </ul>

Ordered list: ol

<ol>
      <li>Create file</li>
      <li>Add structure</li>
      <li>Open in browser</li>
    </ol>

div

Use: Neutral block container for grouping content.

<div class="card">
      <h2>News</h2>
      <p>Today I learned HTML.</p>
    </div>

span

Use: Neutral inline wrapper inside text.

<p>This is <span class="highlight">highlighted</span> text.</p>

class vs id

class: reusable group name.

id: unique identifier on the page.

<h2 class="section-title">Projects</h2>
    <section id="about">...</section>

Semantic layout

Semantic page structure

These elements describe the role of a block. Much better than endless anonymous div soup.

<header>...</header>
    <nav>...</nav>
    <main>...</main>
    <section>...</section>
    <article>...</article>
    <footer>...</footer>

Example semantic layout

<header>
      <h1>My website</h1>
      <nav>
        <a href="#about">About</a>
        <a href="#projects">Projects</a>
      </nav>
    </header>

    <main>
      <section id="about">
        <h2>About</h2>
        <p>Some text.</p>
      </section>

      <article>
        <h2>Latest post</h2>
        <p>New entry here.</p>
      </article>
    </main>

    <footer>
      <p>Β© 2026 Julian</p>
    </footer>

Forms

Basic form

<form action="/send" method="post">
      <label for="name">Name</label>
      <input type="text" id="name" name="name">

      <label for="message">Message</label>
      <textarea id="message" name="message"></textarea>

      <button type="submit">Send</button>
    </form>

Always connect label for="..." with the matching input id.

Common input types

<input type="text">
    <input type="email">
    <input type="password">
    <input type="checkbox">
    <input type="radio">
    <input type="file">

Buttons

<button type="button">Click</button>
    <button type="submit">Submit</button>
    <button type="reset">Reset</button>

Head & metadata

Character encoding

<meta charset="UTF-8" />

Without this, umlauts and special characters may break.

Responsive viewport

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

Without this, mobile layout may look completely wrong.

CSS, JS and favicon

<link rel="stylesheet" href="style.css">
    <link rel="icon" href="favicon.ico">
    <script src="script.js" defer></script>

Meta description

<meta 
      name="description" 
      content="Personal website about electronics, sailing and projects." 
    />

Escaping HTML & displaying code

Why HTML must be escaped

The browser normally interprets angle brackets as HTML elements. To display HTML code as text, replace reserved characters with their corresponding HTML entities.

HTML written normally:

<p>Hello World</p>

The browser interprets this as a paragraph. To display the tag itself, write:

&lt;p&gt;Hello World&lt;/p&gt;

The browser then displays <p>Hello World</p> instead of creating a paragraph.

Common HTML entities

Character HTML entity Meaning
< &lt; Less-than sign
> &gt; Greater-than sign
& &amp; Ampersand
" &quot; Double quotation mark
' &#39; Single quotation mark
Non-breaking space &nbsp; Space without a possible line break

Escape the ampersand first when converting text automatically. Otherwise newly created entities may be escaped a second time.

Display a code block: pre and code

<code> marks content as source code. <pre> preserves spaces, indentation and line breaks.

<pre><code>
      &lt;section class=&quot;card&quot;&gt;
        &lt;h2&gt;Heading&lt;/h2&gt;
        &lt;p&gt;Some text.&lt;/p&gt;
      &lt;/section&gt;
      </code></pre>

Use <pre><code> for complete code blocks and <code> alone for short fragments inside normal text.

Inline code

Use a standalone <code> element when mentioning a tag, attribute, filename or command inside a sentence.

<p>
        Add the <code>&lt;main&gt;</code> element once per page.
      </p>

Result: Add the <main> element once per page.

HTML escaping vs JSON escaping

HTML and JSON use different escaping rules. When HTML code is stored inside a JSON string, both layers may matter.

  • HTML: escape angle brackets with &lt; and &gt;.
  • JSON: escape quotation marks with \".
  • JSON: represent line breaks with \n.
{
        "content_de": "The attribute is class=\"card\".\nThis is a new line."
      }

HTML entities begin with &. JSON escape sequences begin with a backslash. They solve different problems despite looking equally cryptic.

Escape dynamic text with JavaScript

When text comes from JSON, form input or another external source, escape it before inserting it into HTML.

function escapeHtml(value) {
        return String(value).replace(/[&<>"']/g, character => ({
          "&": "&amp;",
          "<": "&lt;",
          ">": "&gt;",
          '"': "&quot;",
          "'": "&#39;"
        })[character]);
      }

Escaping prevents text such as <script> from becoming executable HTML. Never insert untrusted text directly with innerHTML.

↑ top


File paths & URLs

Paths tell the browser where to find another resource, such as an image, stylesheet, JavaScript file, download or another HTML page. A path may be relative to the current file, relative to the domain root, or a complete external URL.

Most path problems are not HTML problems. They are descriptions of the wrong location.

Example project structure

The examples below assume this folder structure:

web/
      
      
      β”œβ”€β”€ index.html
      β”œβ”€β”€ cheatsheets.html
      β”œβ”€β”€ astronomy/
      β”‚   └── clouds.html
      └── assets/
      β”œβ”€β”€ css/
      β”‚   └── main.css
      β”œβ”€β”€ js/
      β”‚   └── main.js
      └── img/
      └── wolkenbetrachtung/
      └── stratocumulus01.jpg

The correct path depends on the location of the file containing the src or href attribute.

Relative path

A relative path is resolved from the location of the current HTML file. It does not begin with a slash.

From cheatsheets.html in the project root:

<img
      
      
      src="assets/img/wolkenbetrachtung/stratocumulus01.jpg" alt="Stratocumulus clouds" >

The browser starts in the folder containing cheatsheets.html and then enters assets, img and wolkenbetrachtung.

Relative paths are usually the most portable choice for a static GitHub Pages project.

Current folder: ./

A leading ./ explicitly means β€œstart in the current folder”. It is usually optional.

<img
      
      
      src="./assets/img/photo.jpg" alt="Example photograph" >

These two paths normally mean the same thing:

assets/img/photo.jpg
      
      
      ./assets/img/photo.jpg

Parent folder: ../

Two dots mean β€œgo one folder upward”.

From astronomy/clouds.html:

<img
      
      
      src="../assets/img/wolkenbetrachtung/stratocumulus01.jpg" alt="Stratocumulus clouds" >

The path means:

  1. Leave the astronomy folder with ../.
  2. Enter assets/img/wolkenbetrachtung/.
  3. Open stratocumulus01.jpg.
../        one folder up
      
      
      ../../      two folders up
      ../../../   three folders up

Root-relative path: leading /

A path beginning with / starts at the root of the current domain, not at the folder containing the HTML file.

<img
      
      
      src="/web/assets/img/wolkenbetrachtung/stratocumulus01.jpg" alt="Stratocumulus clouds" >

On this deployed address:

https://username.github.io/web/astronomy/clouds.html

the browser requests:

https://username.github.io/web/assets/img/wolkenbetrachtung/stratocumulus01.jpg

A leading slash means domain root. It does not automatically mean the root of a GitHub repository.

GitHub Pages project paths

A GitHub Pages project site commonly includes the repository name in its URL:

https://username.github.io/web/

In that case:

/assets/img/photo.jpg
      
      
      β†’ https://username.github.io/assets/img/photo.jpg
      
      /web/assets/img/photo.jpg
      β†’ https://username.github.io/web/assets/img/photo.jpg

The first path skips the repository folder and is therefore usually wrong for a project site. The second path explicitly includes the repository name.

Root-relative paths such as /web/... couple the site to the repository name. Renaming the repository or using another deployment path then breaks them.

Complete absolute URL

An absolute URL contains the protocol, domain and complete resource path.

<img
      
      
      src="https://username.github.io/web/assets/img/photo.jpg" alt="Example photograph" >

Useful for:

  • external websites
  • canonical URLs
  • resources that must always point to one particular domain

For internal links, complete URLs are often unnecessarily rigid.

Relative, root-relative or absolute?

Path Starts from Typical use
assets/img/photo.jpg Current HTML folder Files near the current page
../assets/img/photo.jpg Parent of current HTML folder Pages inside subfolders
/web/assets/img/photo.jpg Domain root Fixed GitHub Pages project path
https://example.com/photo.jpg Specified external domain External or permanently fixed resources

Why web/assets/... may be wrong

Consider this path:

web/assets/img/photo.jpg

Because it has no leading slash, it is a relative path. From cheatsheets.html, the browser looks for:

web/
      
      
      └── web/
      └── assets/
      └── img/
      └── photo.jpg

It is correct only when there really is another web folder inside the current folder.

The repository name visible in a GitHub Pages URL is not necessarily a folder that should appear in a relative path.

Paths in HTML, CSS and JavaScript

Relative paths are not always resolved from the same file.

  • In HTML, src and href are normally relative to the HTML document.
  • In CSS, url(...) is relative to the CSS file containing the rule.
  • In JavaScript, a relative fetch() URL is normally resolved against the page URL.
  • In a JavaScript module, new URL("...", import.meta.url) resolves from the module file.

Example CSS file at assets/css/main.css:

.hero {
      
      
      background-image: url("../img/photo.jpg");
      }

The CSS file goes one folder upward from assets/css/ to assets/, then enters img/.

Folder links and index.html

If a folder contains an index.html, these URLs often lead to the same page:

sailing/
      
      
      sailing/index.html

However, a folder containing home.html does not automatically open that file. You must link to it explicitly:

<a
      
      
      href="sailing/home.html" >Sailing

Fragments and query strings

A URL may contain more than a file path.

article.html#sources
      
      
      archive.html?topic=astro
      archive.html?topic=astro#moon
  • #sources jumps to an element with id="sources".
  • ?topic=astro adds a query string.
  • Neither changes the physical location of the HTML file.

Case sensitivity and filenames

GitHub Pages runs on a case-sensitive system. These names are different:

Stratocumulus01.jpg
      
      
      stratocumulus01.jpg
      stratocumulus01.JPG

Recommended filename style:

  • use lowercase letters
  • avoid spaces
  • use hyphens or underscores consistently
  • check the exact file extension
stratocumulus-01.jpg
      
      
      stratocumulus01.jpg

A path may work on Windows and still fail after deployment because Windows is often more forgiving about uppercase and lowercase filenames.

Avoid spaces and special characters

This filename is technically possible but needlessly awkward:

My cloud photo (final).jpg

The URL may have to encode spaces and characters:

My%20cloud%20photo%20%28final%29.jpg

Prefer:

my-cloud-photo-final.jpg

Do not confuse file-system paths with URLs

A browser cannot use a Windows file-system path on the deployed website:

C:\Users\Julian\Documents\web\assets\img\photo.jpg

Use a web path with forward slashes:

assets/img/photo.jpg

URLs use forward slashes. Backslashes belong to Windows file paths, where they may remain and contemplate their sins.

The <base> element

A <base> element can redefine the starting point for every relative URL in a document.

<base
      
      
      href="/web/" >

After this, relative links such as assets/img/photo.jpg are resolved from /web/ instead of the current document folder.

Use <base> only deliberately. It changes all relative links on the page and can cause impressively confusing breakage.

Debugging a broken path

  1. Open the browser developer tools.
  2. Open the Network tab.
  3. Reload the page.
  4. Look for a red 404 request.
  5. Inspect the exact URL requested by the browser.
  6. Compare uppercase, lowercase, folders and file extension.

You can also copy the image URL and open it directly in a new browser tab.

Do not stare at the HTML and hope the path confesses. Check the URL the browser actually requested.

Recommended rule for this project

Prefer relative paths so the website works both locally and on GitHub Pages without depending unnecessarily on the repository name.

From a root-level HTML file:

assets/img/wolkenbetrachtung/stratocumulus01.jpg

From an HTML file one folder deeper:

../assets/img/wolkenbetrachtung/stratocumulus01.jpg

Root-relative GitHub Pages alternative:

/web/assets/img/wolkenbetrachtung/stratocumulus01.jpg

Use /web/... only when the deployed site definitely lives below https://domain.example/web/ and you accept that dependency.

↑ top


Practical rules

↑ top


CSS

CSS gives structure its visual form. HTML says what something is; CSS decides how it looks, how much space it gets, how it behaves on small screens and how elements interact visually.

This cheatsheet focuses on the CSS things you actually use all the time on real websites: selectors, box model, spacing, colors, typography, layout, responsive design, hover states and a few traps that waste absurd amounts of time.


Basic rule structure

Basic CSS syntax

Use: Every CSS rule has a selector and one or more declarations.

.card {
      background: white;
      border: 1px solid #ddd;
      padding: 1rem;
    }

Selector = what to target. Property = what to change. Value = how to change it.

How CSS connects to HTML

<div class="card">Hello</div>
.card {
      padding: 1rem;
      background: #fff;
    }

HTML provides the hook. CSS styles the hook.

Comments

/* This is a CSS comment */
    .card-title {
      font-size: 1.2rem;
    }

Use comments for structure, not for writing a tragic novel into your stylesheet.


Selectors

Element selector

p {
      line-height: 1.6;
    }

Targets all <p> elements.

Class selector

.card {
      border-radius: 16px;
    }

Targets all elements with class="card".

ID selector

#top {
      scroll-margin-top: 1rem;
    }

Targets one unique element with that ID.

Descendant selector

.card p {
      margin-bottom: 1rem;
    }

Targets paragraphs inside .card.

Multiple selectors

h1, h2, h3 {
      line-height: 1.25;
    }

Same rule for several elements.

Pseudo-classes

a:hover {
      text-decoration: underline;
    }

    a:focus-visible {
      outline: 2px solid rgba(11, 95, 255, 0.45);
    }

Useful for hover, keyboard focus, active states and more.


Box model

The box model

Every element is basically a box made of:

  • content
  • padding = inner space
  • border = visible edge
  • margin = outer space
.box {
      margin: 1rem;
      padding: 1rem;
      border: 1px solid #ccc;
    }

box-sizing: border-box

*,
    *::before,
    *::after {
      box-sizing: border-box;
    }

This is one of the least glamorous and most useful lines in modern CSS.

Margin vs padding

.card {
      padding: 1.25rem;   /* inside */
      margin: 1rem 0;     /* outside */
    }

Padding creates breathing room inside. Margin separates elements from each other.


Spacing & sizing

Common spacing values

.section {
      margin: 2rem 0;
      padding: 1rem 1.25rem;
    }

Very often you only need margin, padding and a bit of restraint.

Width and height

.content {
      max-width: 980px;
      width: 100%;
    }

    .hero {
      min-height: 160px;
    }

max-width is usually better than fixed width for content areas.

Useful units

  • px = fixed pixels
  • rem = relative to root font size
  • % = relative to parent
  • vw / vh = viewport width / height
  • fr = fractional grid space
  • ch = character width approximation
.hero-quote {
      max-width: 42ch;
      font-size: 1.35rem;
    }

Shorthand spacing

margin: 1rem;          /* all sides */
    margin: 1rem 2rem;     /* top/bottom | left/right */
    margin: 1rem 2rem 3rem;/* top | left/right | bottom */
    margin: 1rem 2rem 3rem 4rem; /* top | right | bottom | left */

Text & fonts

Font basics

body {
      font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif;
      font-size: 1rem;
      line-height: 1.6;
    }

Good typography is half the website. The other half is not ruining it.

Common text properties

.site-title {
      font-size: 1.4rem;
      font-weight: 700;
      letter-spacing: 0.2px;
      text-align: left;
    }

Muted text

.hint,
    .card-meta {
      color: var(--muted);
      font-size: 0.95rem;
    }

Muted text is for secondary information, not for making everything look tired.

Text decoration

a {
      text-decoration: underline;
      text-underline-offset: 3px;
      text-decoration-thickness: 1px;
    }

Colors & backgrounds

Text and background colors

body {
      color: #1f2328;
      background: #f7f7f7;
    }

Border and radius

.card {
      border: 1px solid #e5e7eb;
      border-radius: 16px;
    }

RGBA transparency

.overlay {
      background: rgba(0, 0, 0, 0.35);
    }

Useful for overlays, subtle borders and layered backgrounds.

Background images

.hero {
      background: url("../img/photo.jpg") center / cover no-repeat;
    }

center / cover no-repeat is a classic trio for full-area background images.


Display & positioning

display

.thing {
      display: block;
    }
  • block = takes full width
  • inline = stays inside text flow
  • inline-block = inline but sizeable
  • flex = flexible row/column layout
  • grid = grid layout
  • none = hidden

Positioning

.parent {
      position: relative;
    }

    .child {
      position: absolute;
      top: 0;
      right: 0;
    }

relative creates a positioning context. absolute places something precisely inside it.

inset: 0

.overlay {
      position: absolute;
      inset: 0;
    }

Elegant shorthand for top/right/bottom/left = 0.

z-index

.background {
      z-index: -1;
    }

    .overlay {
      z-index: 2;
    }

Controls stacking order. Only useful on positioned elements.


Flexbox & grid

Flexbox row layout

.header-inner {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      gap: 1rem;
    }

Use flex for one-dimensional layouts: row or column.

Flex wrap

.top-nav {
      display: flex;
      gap: 0.9rem;
      flex-wrap: wrap;
    }

Very handy when items should wrap instead of colliding like drunken shopping carts.

Grid layout

.tile-grid {
      display: grid;
      gap: 1rem;
      grid-template-columns: repeat(3, minmax(0, 1fr));
    }

Use grid for two-dimensional layouts with rows and columns.

Centering with grid

.hero {
      display: grid;
      place-items: center;
    }

Ridiculously convenient for centering content both horizontally and vertically.


Basic link styling

a {
      color: var(--text);
      text-decoration: underline;
    }

Hover state

a:hover {
      text-decoration-color: currentColor;
    }

Hover gives feedback. Overdo it and the page starts performing circus tricks.

Focus-visible

a:focus-visible {
      outline: 2px solid rgba(11, 95, 255, 0.45);
      outline-offset: 2px;
    }

Keyboard users exist. Design accordingly.

Transitions

.tile-image {
      transition: transform 180ms ease;
    }

    .tile:hover .tile-image {
      transform: scale(1.06);
    }

Use transitions sparingly. A website is not a casino machine.


Responsive design

Media query

@media (max-width: 900px) {
      .tile-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
      }
    }

Use media queries when layout must adapt to smaller screens.

Mobile stacking

@media (max-width: 560px) {
      .header-inner {
        flex-direction: column;
        align-items: flex-start;
      }

      .tile-grid {
        grid-template-columns: 1fr;
      }
    }

Responsive images

img {
      max-width: 100%;
      height: auto;
      display: block;
    }

This prevents images from exploding out of their containers like idiots.

Viewport meta tag reminder

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Responsive CSS without this meta tag is often dead on arrival.


Variables

Define variables in :root

:root {
      --bg: #f7f7f7;
      --surface: #ffffff;
      --text: #1f2328;
      --muted: #6b7280;
      --border: #e5e7eb;
      --radius: 16px;
    }

Very useful for consistent colors, spacing and theme changes.

Use variables with var()

body {
      color: var(--text);
      background: var(--bg);
    }

    .card {
      background: var(--surface);
      border-radius: var(--radius);
    }

Calculated values

.media-placeholder {
      border-radius: calc(var(--radius) - 4px);
    }

calc() lets values relate to each other instead of drifting into random numerology.


Practical rules

↑ top


Python

Python is a general-purpose language with a clean syntax and a low barrier to entry. It is excellent for automation, scripting, data handling, small tools, quick experiments and hardware-related projects.

This cheatsheet focuses on the Python things you actually use all the time: variables, data types, conditions, loops, functions, files, modules, virtual environments and a few common traps.


Basics

Hello world

print("Hello, world!")

Use: Prints text to the console.

Variables

name = "Julian"
    age = 28
    temperature = 21.5
    is_online = True

Python variables do not need explicit type declarations.

Comments

# This is a comment

    """
    This is a multi-line docstring
    or documentation string.
    """

Use comments for explanations, not for narrating every line like a bad sports commentator.

Indentation matters

if True:
        print("Indented correctly")

    print("Outside the block")

In Python, indentation is not decoration. It defines the structure.


Data types

Common data types

text = "hello"      # str
    number = 42         # int
    pi = 3.1415         # float
    active = True       # bool
    nothing = None      # NoneType

Check a type

value = 42
    print(type(value))

Useful when you are not sure what you are actually handling.

Convert between types

age_text = "28"
    age_number = int(age_text)

    temperature = "21.5"
    temperature_number = float(temperature)

    number = 42
    text = str(number)

Strings

Basic string operations

name = "Julian"

    print(name.lower())
    print(name.upper())
    print(len(name))
    print(name[0])

f-strings

name = "Julian"
    age = 28

    print(f"My name is {name} and I am {age} years old.")

This is usually the cleanest way to build readable output strings.

Useful string methods

text = "  Hello World  "

    print(text.strip())         # remove outer spaces
    print(text.replace("World", "Python"))
    print(text.startswith("  He"))
    print(text.endswith("  "))
    print(text.split())

Multi-line strings

message = """Line one
    Line two
    Line three"""

    print(message)

Conditions

if, elif, else

temperature = 18

    if temperature > 25:
        print("Warm")
    elif temperature > 15:
        print("Mild")
    else:
        print("Cold")

Comparison operators

x == 10   # equal
    x != 10   # not equal
    x > 10
    x < 10
    x >= 10
    x <= 10

Logical operators

if age >= 18 and country == "AT":
        print("Allowed")

    if is_admin or is_editor:
        print("Can edit")

    if not active:
        print("Inactive")

Truthy and falsy values

if []:
        print("List has content")

    if not []:
        print("List is empty")

Empty strings, empty lists, zero and None are treated as false.


Loops

for loop

for i in range(5):
        print(i)

Prints 0 to 4.

Loop through a list

colors = ["red", "green", "blue"]

    for color in colors:
        print(color)

while loop

count = 0

    while count < 3:
        print(count)
        count += 1

Useful, but easy to abuse into infinite nonsense if you forget to update the condition.

break and continue

for i in range(10):
        if i == 3:
            continue
        if i == 7:
            break
        print(i)

continue skips one iteration, break stops the loop completely.

enumerate()

items = ["a", "b", "c"]

    for index, item in enumerate(items):
        print(index, item)

Very useful when you need both index and value.


Functions

Basic function

def greet(name):
        print(f"Hello, {name}!")

    greet("Julian")

Return values

def add(a, b):
        return a + b

    result = add(3, 4)
    print(result)

return gives a value back to the caller.

Default arguments

def greet(name="world"):
        print(f"Hello, {name}!")

    greet()
    greet("Julian")

Keyword arguments

def describe(name, age):
        print(f"{name} is {age} years old.")

    describe(age=28, name="Julian")

Lists, tuples, dicts, sets

Lists

colors = ["red", "green", "blue"]

    colors.append("yellow")
    colors.remove("green")
    print(colors[0])
    print(len(colors))

Lists are ordered and mutable.

Tuples

point = (10, 20)
    print(point[0])

Tuples are ordered but immutable.

Dictionaries

person = {
        "name": "Julian",
        "age": 28,
        "city": "Graz"
    }

    print(person["name"])
    print(person.get("age"))

Dictionaries store key-value pairs.

Sets

numbers = {1, 2, 3, 3}
    print(numbers)

Sets contain unique values only.

List comprehensions

squares = [x * x for x in range(5)]
    print(squares)

Compact and powerful, though beginners should not turn every line into cryptic wizardry.


Files

Read a file

with open("notes.txt", "r", encoding="utf-8") as file:
        content = file.read()

    print(content)

with open(...) is the standard clean pattern.

Write a file

with open("output.txt", "w", encoding="utf-8") as file:
        file.write("Hello, file!")

"w" overwrites the file if it already exists.

Append to a file

with open("log.txt", "a", encoding="utf-8") as file:
        file.write("New line\n")

"a" adds content at the end instead of replacing the file.

Read line by line

with open("data.txt", "r", encoding="utf-8") as file:
        for line in file:
            print(line.strip())

Errors & exceptions

Basic try / except

try:
        number = int("abc")
    except ValueError:
        print("That was not a valid integer.")

else and finally

try:
        value = int("42")
    except ValueError:
        print("Invalid")
    else:
        print("Success:", value)
    finally:
        print("This always runs")

Raise your own error

age = -1

    if age < 0:
        raise ValueError("Age cannot be negative")

Modules & imports

Import a module

import math

    print(math.sqrt(16))

Import specific things

from math import sqrt

    print(sqrt(25))

Common useful modules

import os
    import sys
    import json
    import csv
    import pathlib
    import datetime

These are everyday tools for files, paths, data, dates and system interaction.

Main guard

def main():
        print("Program starts here")

    if __name__ == "__main__":
        main()

Useful so code only runs when the file is executed directly.


Virtual environments

Create a virtual environment

python3 -m venv .venv

Creates an isolated Python environment for a project.

Activate it on Linux / Raspberry Pi

source .venv/bin/activate

Install packages

pip install requests

Usually do this after activating the virtual environment.

Freeze dependencies

pip freeze > requirements.txt

Install from requirements

pip install -r requirements.txt

Deactivate

deactivate

Practical rules

↑ top


Arduino

Arduino is a beginner-friendly microcontroller platform for reading sensors, controlling outputs and building small interactive hardware projects. It combines simple hardware access with a lightweight C/C++-style programming model.

This cheatsheet focuses on the Arduino things you actually use all the time: sketch structure, variables, pins, digital and analog I/O, timing, serial monitor, functions, libraries and a few common traps.


Basics

Basic sketch structure

void setup() {
      // runs once at startup
    }

    void loop() {
      // runs again and again
    }

setup() runs once. loop() runs forever until power is removed or the board is reset.

Hello world on Serial

void setup() {
      Serial.begin(9600);
      Serial.println("Hello, Arduino!");
    }

    void loop() {
    }

A classic first test. If this does not work, something basic is wrong: board, port, cable or baud rate.

Comments

// Single-line comment

    /*
      Multi-line comment
    */

Use comments to explain intent, not to narrate every obvious line like a village herald.

Semicolon matters

int ledPin = 13;   // correct
    int ledPin = 13    // wrong

Unlike Python, Arduino/C++ wants semicolons. Forget them and the compiler sulks immediately.


Variables & data types

Common data types

int sensorValue = 0;
    float temperature = 21.5;
    bool ledState = true;
    char letter = 'A';

These are the types you will meet constantly in small Arduino projects.

Useful integer types

byte smallValue = 255;
    unsigned long currentTime = 0;

unsigned long is especially important for timing with millis().

const for fixed values

const int ledPin = 13;
    const int buttonPin = 2;

Use const for pin numbers and fixed settings. It keeps the code clearer and safer.

Global vs local variables

int counter = 0;   // global

    void loop() {
      int localValue = 5;  // local
      counter++;
    }

Global variables are visible everywhere. Local variables only exist inside their function or block.


Pins & pin modes

pinMode()

void setup() {
      pinMode(13, OUTPUT);
      pinMode(2, INPUT);
    }

Before using a pin, tell the microcontroller what role it should play.

Common pin modes

pinMode(13, OUTPUT);
    pinMode(2, INPUT);
    pinMode(3, INPUT_PULLUP);
  • OUTPUT = drives LED, relay, etc.
  • INPUT = reads an external signal
  • INPUT_PULLUP = input with internal pull-up resistor

Why INPUT_PULLUP matters

pinMode(3, INPUT_PULLUP);

Very useful for buttons. It avoids floating input chaos and saves an external resistor in many cases.


Digital input & output

Turn an LED on and off

const int ledPin = 13;

    void setup() {
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      digitalWrite(ledPin, HIGH);
      delay(1000);
      digitalWrite(ledPin, LOW);
      delay(1000);
    }

HIGH usually means on, LOW means off.

Read a button

const int buttonPin = 2;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop() {
      int state = digitalRead(buttonPin);
      Serial.println(state);
    }

With INPUT_PULLUP, a pressed button often reads LOW, not HIGH. Slightly perverse, but normal.

React to a button press

const int buttonPin = 2;
    const int ledPin = 13;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      if (digitalRead(buttonPin) == LOW) {
        digitalWrite(ledPin, HIGH);
      } else {
        digitalWrite(ledPin, LOW);
      }
    }

Analog input & PWM output

Read an analog value

int sensorValue = 0;

    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      delay(500);
    }

On many Arduino boards, analogRead() returns values from 0 to 1023.

PWM output with analogWrite()

const int ledPin = 9;

    void setup() {
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      analogWrite(ledPin, 128);
    }

On classic Arduino boards, PWM values usually go from 0 to 255.

Map one range to another

int sensorValue = analogRead(A0);
    int brightness = map(sensorValue, 0, 1023, 0, 255);

    analogWrite(9, brightness);

map() is useful when sensor ranges and output ranges do not match.

constrain()

int value = 300;
    value = constrain(value, 0, 255);

Keeps a value inside a defined range.


Serial monitor

Start Serial communication

void setup() {
      Serial.begin(9600);
    }

The baud rate in the Serial Monitor must match this value.

Serial.print() vs Serial.println()

Serial.print("Value: ");
    Serial.println(42);

print() stays on the same line. println() adds a line break.

Print several values clearly

int temp = 23;
    int humidity = 55;

    Serial.print("Temp: ");
    Serial.print(temp);
    Serial.print(" C, Humidity: ");
    Serial.print(humidity);
    Serial.println(" %");

Serial for debugging

Serial.println("Reached setup()");
    Serial.println(sensorValue);

Serial output is one of the most useful debugging tools in Arduino land. Primitive, but gold.


Timing

delay()

delay(1000);

Pauses the program for 1000 milliseconds = 1 second.

Blink without delay using millis()

const int ledPin = 13;
    unsigned long previousMillis = 0;
    const unsigned long interval = 1000;
    bool ledState = false;

    void setup() {
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        ledState = !ledState;
        digitalWrite(ledPin, ledState);
      }
    }

This is the classic non-blocking timing pattern. Very important once projects get even mildly serious.

millis() basics

unsigned long now = millis();

Returns the number of milliseconds since the board started running.

micros()

unsigned long t = micros();

Like millis(), but in microseconds. Useful for faster timing needs.


Conditions & logic

if, else

int value = analogRead(A0);

    if (value > 500) {
      Serial.println("High");
    } else {
      Serial.println("Low");
    }

Comparison operators

x == 10
    x != 10
    x > 10
    x < 10
    x >= 10
    x <= 10

Logical operators

if (temp > 20 && humidity < 70) {
  Serial.println("Comfortable");
}

if (buttonPressed || sensorTriggered) {
  Serial.println("Action");
}

if (!enabled) {
  Serial.println("Disabled");
}

Loops & iteration

for loop

for (int i = 0; i < 5; i++) {
  Serial.println(i);
}

Useful for repeated actions, arrays and test output.

while loop

int x = 0;

while (x < 3) {
  Serial.println(x);
  x++;
}

Works fine, but be careful: a bad while loop can lock your program into stupidity.

Loop over an array

int values[] = {10, 20, 30, 40};

for (int i = 0; i < 4; i++) {
  Serial.println(values[i]);
}

Functions

Basic function

void blinkOnce() {
  digitalWrite(13, HIGH);
  delay(200);
  digitalWrite(13, LOW);
}

Functions help split code into reusable, readable chunks.

Function with parameters

void blinkLed(int pin, int duration) {
  digitalWrite(pin, HIGH);
  delay(duration);
  digitalWrite(pin, LOW);
}

Function with return value

int readSensor() {
  return analogRead(A0);
}

Using a function

void loop() {
  int value = readSensor();
  Serial.println(value);
  delay(500);
}

Libraries

Include a library

#include <Wire.h>

Libraries add functionality for sensors, displays, communication and more.

Typical pattern with an object

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.print("Hello");
}

void loop() {
}

Many Arduino libraries create an object first, then you call methods on it.

Common built-in or standard libraries

#include <Wire.h>     // I2C
#include <SPI.h>      // SPI
#include <EEPROM.h>   // EEPROM
#include <Servo.h>    // Servo motors

I2C basics with Wire

#include <Wire.h>

void setup() {
  Wire.begin();
}

void loop() {
}

Very common for sensors like BME280, displays and RTC modules.


Practical rules

↑ top


↑ topβŒ‚ home