Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to Cheat Sheets
Python Basics Cheat Sheet for Beginners

Python Basics Cheat Sheet for Beginners

Cheat SheetsBy Muhammad Fareed
pythonbeginnerssyntaxcheat sheet

Short answer: Python is a readable language where indentation defines blocks. This cheat sheet summarizes variables, data types, collections, control flow, functions and file handling so you can look up syntax quickly.

Variables and types

name = "Asha"      # str
age = 30           # int
price = 9.99       # float
active = True      # bool
nothing = None

Python is dynamically typed, so you do not declare types. Use type(x) to check one and int(), str() or float() to convert.

Strings

  • f-strings: f"Hello {name}".
  • Methods: .upper(), .lower(), .strip(), .split(","), .replace("a", "b").
  • Slicing: text[0:3] returns the first three characters.

Collections

TypeExampleNotes
list[1, 2, 3]Ordered, changeable
tuple(1, 2, 3)Ordered, not changeable
set{1, 2, 3}Unique values, unordered
dict{"a": 1}Key and value pairs
items = [1, 2, 3]
items.append(4)
user = {"name": "Asha"}
user["age"] = 30

Control flow

if age >= 18:
    print("adult")
elif age >= 13:
    print("teen")
else:
    print("child")

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

while count < 5:
    count += 1

Use break to leave a loop and continue to skip to the next pass.

Functions

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

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

The second line is a list comprehension, a short way to build a list from a loop.

Files and errors

with open("data.txt") as f:
    text = f.read()

try:
    value = int(text)
except ValueError:
    value = 0

The with statement closes the file automatically, even if an error occurs.

Modules and virtual environments

Import code with import math or from pathlib import Path. Keep each project's libraries separate with a virtual environment: python -m venv .venv, then activate it and run pip install package. Save the list of dependencies with pip freeze > requirements.txt so others can reproduce your setup.

Classes in brief

class Dog:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} says woof"

A class bundles data and behavior. __init__ runs when you create an object, and self refers to that object.

Common beginner errors

  • IndentationError: mixed tabs and spaces or wrong block depth. Use four spaces everywhere.
  • NameError: using a variable before it exists or misspelling its name.
  • TypeError: combining incompatible types, such as adding a number to a string. Convert first with str() or int().
  • KeyError: reading a dictionary key that is missing. Use user.get("age") to get None instead of an error.

Useful built-ins

  • len(), sum(), min(), max(), sorted().
  • enumerate() gives an index with each item, and zip() pairs two lists.
  • input() reads text from the user and print() shows output.

Comprehensions and unpacking

squares = [n * n for n in range(10)]
evens = [n for n in range(20) if n % 2 == 0]
lengths = {word: len(word) for word in ["api", "python", "loop"]}

first, *rest = [1, 2, 3, 4]      # first = 1, rest = [2, 3, 4]
a, b = b, a                       # swap two variables

for index, name in enumerate(["Ana", "Ben"], start=1):
    print(index, name)

for name, score in zip(["Ana", "Ben"], [90, 85]):
    print(f"{name}: {score}")

Comprehensions build lists and dictionaries in one readable line. Keep them simple; if one needs several conditions, a normal loop is clearer. More examples in Python list comprehensions.

Working with JSON and dates

import json
from datetime import datetime, timedelta

data = {"name": "Ana", "skills": ["python", "sql"]}
text = json.dumps(data, indent=2)     # dict to JSON string
back = json.loads(text)               # JSON string to dict

now = datetime.now()
next_week = now + timedelta(days=7)
print(now.strftime("%Y-%m-%d %H:%M"))

Mutable vs immutable types

Immutable (cannot change in place)Mutable (can change in place)
int, float, str, tuple, bool, frozensetlist, dict, set, most custom objects

This matters when you pass values to functions. A function that appends to a list you pass in changes the caller's list too.

Common mistakes

  • Mutable default arguments. def add(item, items=[]) shares one list across calls. Use items=None and create the list inside.
  • Comparing with is instead of ==. Use is only for None.
  • Mixing tabs and spaces. Use four spaces, which most editors do automatically.
  • Naming files after modules, such as random.py, which hides the real module of the same name.
  • Catching every exception with a bare except:, which hides real bugs. Catch specific errors; see exception handling in Python.

Frequently asked questions

What is the difference between a list and a tuple?

Lists can be changed after creation, while tuples cannot, which makes tuples suitable for fixed data.

Why does Python care about indentation?

Indentation marks which lines belong to a block such as an if statement or a function, so inconsistent spacing causes errors.

How do I install extra libraries?

Use pip, for example pip install requests, ideally inside a virtual environment.

What should I learn after the basics?

Practise with small projects, then learn virtual environments, testing and a library for your goal, such as Flask or Django for web or pandas for data. The Python overview lists common paths.

Should I learn Python 2 or Python 3?

Python 3. Python 2 reached end of life in 2020 and no longer receives updates. All modern tutorials, libraries and jobs use Python 3.

How do I read a Python error message?

Read the traceback from the bottom up. The last line names the error type and message, and the lines above show the file and line number where it happened, plus the chain of calls that led there.