Code Cheat Sheet: Python and Git Essentials
In this article
- Which basic elements belong on a programming cheat sheet?
- How do I write a loop in Python?
- Count down with while
- How do I define and call a function?
- Call the function
- What is the simplest pattern for reading and writing files?
- Read the file back line by line
- Which Git commands are essential for everyday work?
- Make changes, then stage and commit
- Keep the branch up‑to‑date
- Push the feature for a pull request
- What common mistakes cause bugs when using cheat‑sheet code?
A code cheat sheet is a compact reference that lists the most frequently used syntax and commands for a language or tool. For example, a Python cheat sheet might show a one‑line loop, a function definition, and a file‑read pattern all in a few lines of code.
Which basic elements belong on a programming cheat sheet?
A useful cheat sheet includes the building blocks you reach for most often. Keep the list short enough to scan quickly, but comprehensive enough to cover everyday tasks.
- Variable assignment and data‑type literals (strings, numbers, lists, dictionaries).
- Control flow:
if/elif/elsestatements and loop structures. - Function definition and calling syntax.
- Common standard‑library calls for file I/O, JSON handling, and date/time.
- Regular‑expression patterns for search and replace.
- Command‑line shortcuts and Git commands for version control.
- Typical error‑handling patterns (
try/except).
Rule of thumb: limit each section to a single concept and a minimal, runnable example. If you find yourself adding more than three lines for one item, consider splitting it into its own cheat sheet.
How do I write a loop in Python?
Loops let you repeat actions without writing the same line many times. The two most common loops are for and while.
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
Count down with while
counter = 5
while counter > 0:
print(counter)
counter -= 1
In the for example, the loop automatically pulls each element from the list. In the while example, the condition counter > 0 is checked before each iteration, and the loop stops when the condition becomes false.
Sign you need a loop: you have a collection of items or a repetitive task that depends on a changing variable.
How do I define and call a function?
Functions encapsulate reusable logic. Define a function with def, list parameters in parentheses, and indent the body.
def greet(name, times=1):
"""Print a greeting the requested number of times."""
for _ in range(times):
print(f"Hello, {name}!")
Call the function
greet("Sam") # prints once
greet("Alex", 3) # prints three times
The optional times=1 gives a default value, so callers can omit that argument. Returning a value works the same way, just add return inside the body.
Common mistake: forgetting the colon after the function header or mixing up indentation levels, which leads to IndentationError. Keep the header on its own line and indent the body consistently with four spaces.
What is the simplest pattern for reading and writing files?
File handling appears in almost every script. Use the with statement to open a file; it automatically closes the file when the block ends, preventing resource leaks.
# Write a short text file
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("Remember to water the plants.\n")
f.write("Buy tea tomorrow.\n")
Read the file back line by line
with open("notes.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
Opening in "w" mode creates a new file or overwrites an existing one. Use "a" to append instead. When reading, strip() removes the trailing newline character.
Safety tip: never trust external file content without validation. If the file may contain user input, consider sanitising or using json.load for structured data.
Which Git commands are essential for everyday work?
Git tracks changes and collaborates with others. The following one‑liner commands cover the most common workflow.
git status– shows modified, staged, and untracked files.git add <path>– stages a file or directory for commit.git commit -m "Message"– records staged changes with a brief description.git pull– fetches and merges remote updates into the current branch.git push– sends local commits to the remote repository.git branch– lists existing branches;git checkout -b new‑branchcreates and switches to a new branch.git log --oneline– shows a compact history of commits.
Example sequence to start a feature:
# Create and switch to a new branch
git checkout -b feature/login
Make changes, then stage and commit
git add login.py
git commit -m "Add login form"
Keep the branch up‑to‑date
git pull origin main
Push the feature for a pull request
git push -u origin feature/login
Rule of thumb: commit early and often with clear messages. Small commits are easier to review and revert if needed.
What common mistakes cause bugs when using cheat‑sheet code?
Even a concise reference can mislead if you overlook context. Here are frequent pitfalls and how to fix them.
- Indentation errors – Python relies on whitespace. Copying code into an editor that mixes tabs and spaces can break execution. Set your editor to insert four spaces for each tab.
- Hard‑coded paths – Using absolute file paths makes scripts fail on other machines. Prefer relative paths or
os.path.jointo build platform‑independent paths. - Missing imports – A snippet may assume
import jsonorimport reis already present. Check the top of the snippet for required imports. - Version assumptions – Some syntax (e.g., f‑strings) requires Python 3.6+. Verify your interpreter version before using newer features.
- Git force pushes – Using
git push --forcecan overwrite teammates' work. Reserve force pushes for private branches and always communicate before using them. - Unclosed files – Forgetting the
withstatement can leave file handles open, leading to “Too many open files” errors. Always usewithfor file I/O.
When a snippet fails, re‑read the error message, verify the surrounding context, and adjust the code to match your project's settings.