PyDA Course
📋 Python cheatsheets

Python cheatsheets

The snippets you will reach for every single lesson. Code runs in the cells above; these are the patterns to copy.

  • Variables

    • Assign & read

      x = 5
      x = x + 1   # 6
      print(x)    # 6

      = stores a value under a name. Reassigning just points the name at the new value.

    • Naming rules

      score = 10      # snake_case ✅
      age_2 = 3       # digits ok after first char
      age 2 = 3       # ❌ space & leading digit
      Score = 10      # works, but remember: case-sensitive

      Names are case-sensitive. Use snake_case, descriptive names, and avoid built-in words like print.

    • Swap & unpack

      a, b = 1, 2
      a, b = b, a   # swap in one line
      first, *rest = [1, 2, 3]  # first=1, rest=[2, 3]

      Python assigns several names at once — the cleanest swap there is.

  • Output

    • print

      print('Hello, world!')
      print(2 + 3)      # 5, values print automatically

      The one function you will use in every single lesson.

    • No trailing comma

      print('a', 'b', sep='-')   # a-b

      sep controls the separator; the default is a space.

  • Input

    • Read the prompt

      name = input('Your name: ')
      print('Hi', name)

      input() pauses and waits; it ALWAYS returns a string.

    • Convert it

      age = int(input('Age: '))
      price = float(input('Price: '))

      Convert at the read with int()/float(), or every math step after will fail.

  • Numbers

    • Basic arithmetic

      x = 7
      x // 2   # 3  integer division
      x % 2    # 1  remainder
      x ** 2   # 49 exponent

      // and % are division partners — they answer "how many times" and "how much is left".

    • type()

      type(3)     # <class 'int'>
      type(3.0)   # <class 'float'>
      type("3")   # <class 'str'>

      Check any value's type when an error mentions a type mismatch.

    • Converting

      int('42')   # 42
      float('4.2')
      str(42)     # '42'

      input() always returns a string — convert before doing math.

  • Strings

    • f-strings

      name = 'PyDA'
      print(f'{name} → {len(name)} letters')

      The f before the quote makes {…} insert values. Use this, not concatenation.

    • Methods

      '  hi  '.strip()   # 'hi'
      'hello'.upper()   # 'HELLO'
      'a,b'.split(',')   # ['a', 'b']

      Methods return a NEW string — strings are immutable.

    • Slicing

      word = 'python'
      word[0]    # 'p'
      word[-1]   # 'n'
      word[1:4]  # 'yth'

      start inclusive, end exclusive. Negative indexes count from the end.

    • Combine, repeat, search

      'py' + 'thon'    # 'python'
      'ha' * 3        # 'hahaha'
      'py' in 'python'  # True
      len('abc')        # 3

      + glues strings, * repeats them, in tests for a substring, len() counts characters.

    • Backslash escapes

      print('she\'s fine')   # she's fine
      print('line1\nline2')  # two lines
      print('tab\there')      # tab       here

      \' is a quote, \n a new line, \t a tab. Use raw strings r"…" when a path has too many backslashes.

  • Lists

    • Building & adding

      nums = [1, 2, 3]
      nums.append(4)      # [1, 2, 3, 4]
      nums + [5]        # [1, 2, 3, 4, 5]

      append mutates the list in place; + makes a new one.

    • Reading

      nums[0]      # 1
      len(nums)    # 4
      nums[-1]     # 4
      3 in nums    # True

      in / not in are the membership checks.

    • Looping

      for n in nums:
          print(n * 2)

      The for loop reaches for each element one at a time.

    • Sort & copy

      nums.sort()          # in place
      sorted(nums)         # NEW sorted list
      copy = nums[:]       # real copy, not the same list

      sort() changes the list and returns None; sorted() returns a new one. Use nums[:] to work on a copy.

    • Slice tricks

      nums = [0, 1, 2, 3, 4]
      nums[1:]    # [1, 2, 3, 4]  drop the head
      nums[:-1]   # [0, 1, 2, 3]  drop the tail
      nums[::-1]  # [4, 3, 2, 1, 0]  reversed

      The [start:end:step] form is list surgery — dropping, copying, and reversing in one line.

  • Tuples & Sets

    • Tuples

      t = (1, 2, 3)
      t[0]        # 1
      x, y = t        # unpack
      # t[0] = 9      # ❌ tuples can't change

      A fixed list — use it when the shape should not change: coordinates, config pairs, read-only data.

    • Sets

      s = {1, 2, 2, 3}   # {1, 2, 3} — duplicates dropped
      s.add(4)
      4 in s        # True
      s.remove(4)

      An unordered bag of unique items — perfect for de-duplication and fast membership checks.

    • Set operations

      a = {1, 2, 3}
      b = {3, 4}
      a | b       # {1, 2, 3, 4}  union
      a & b       # {3}           intersection
      a - b       # {1, 2}        difference
      a ^ b       # {1, 2, 4}     symmetric

      | , & , - , ^ turn sets into one-line math — compare groups without nested loops.

    • Which container?

      list    # ordered, editable, keeps order
      tuple   # ordered, read-only
      set     # unordered, unique, fast in
      dict    # key → value lookup

      Pick by what the code needs: order, uniqueness, or finding things by name.

  • Dictionaries

    • Build & read

      ages = {'ada': 36, 'bob': 41}
      ages['ada']        # 36
      ages.get('zoe')    # None (safe "missing")
      ages.get('zoe', 0) # 0 (with default)

      Using [key] on a missing key raises KeyError — prefer .get() when unsure.

    • Write

      ages['ada'] = 37
      ages['zoe'] = 22
      del ages['bob']

      Assignment adds or updates; del removes a key.

    • Iterate

      for k, v in ages.items():
          print(k, v)

      .items() gives (key, value) pairs; .keys() and .values() give just one side.

  • Conditionals

    • if / elif / else

      if score >= 90:
          print("A")
      elif score >= 80:
          print("B")
      else:
          print("C")

      elif stops once a condition is True — order matters.

    • Comparisons

      ==  !=  <  <=  >  >=

      == tests equality; = assigns. Remembering this fixes most beginner "why is it True" bugs.

    • Boolean operators

      a and b    # both truthy
      a or b     # at least one
      a and not b

      and / or / not — the plain words, not && and ! like other languages.

    • Truthiness

      if x:             # 'is x non-empty?'
          print(x)
      # Falsy: 0, 0.0, '', [], {}, None
      # Everything else is truthy

      "if x:" is the idiomatic "is x there?" check — empty containers and 0 fail, everything else passes.

    • Ternary one-liner

      'pass' if score >= 50 else 'fail'

      A compact if/else that returns a value — great inside f-strings and print().

  • Loops

    • range

      for i in range(3):   # 0, 1, 2
          print(i)
      for i in range(1, 4): # 1, 2, 3
          print(i)

      range stops before the second number — same end-exclusive rule as slicing.

    • enumerate / zip

      for i, item in enumerate(['a','b']):
          print(i, item)
      for x, y in zip([1,2],[3,4]):
          print(x, y)

      enumerate adds a counter; zip pairs two sequences element-wise.

    • break / continue

      for n in range(10):
          if n == 3:
              break      # stop the loop
      for n in range(10):
          if n % 2:
              continue   # skip this one
          print(n)

      break leaves the loop entirely; continue jumps to the next iteration.

    • while

      n = 3
      while n > 0:
          print(n)
          n -= 1   # don't forget: while needs progress

      while repeats until its condition becomes False — a loop that never updates its condition never ends.

    • Loop else (optional)

      for n in nums:
          if n == target:
              break
      else:
          print("not found")

      The else block runs only if the loop finished without a break — a built-in "was it found?" flag.

  • Functions

    • Define & call

      def double(x):
          return x * 2
      
      y = double(21)   # 42

      def … body must be indented. return hands a value back; without it you get None.

    • Defaults & keywords

      def greet(name, exclaim=True):
          s = f"Hello {name}"
          return s + ("!" if exclaim else "")
      
      greet("ada")        # Hello ada!
      greet("ada", False) # Hello ada

      Parameters with = get defaults; callers can pass by keyword.

    • Return multiple values

      def minmax(nums):
          return min(nums), max(nums)
      
      lo, hi = minmax([3, 1, 4])  # lo=1, hi=4

      A function can return a tuple and callers unpack it into several names at once.

    • Scope & print vs return

      x = 10            # global
      
      def show(y):
          x = 5         # local — different x!
          print(x, y)   # side effect, returns None
      
      result = show(1)  # result is None

      print shows a value in the console; return actually hands it back. Assigning inside a function shadows the global.

    • Lambda (short forms)

      double = lambda x: x * 2
      sorted(nums, key=lambda n: -n)

      Use lambdas for one-line throwaway functions passed to sort/max/map.

  • Comprehensions

    • List

      [n * 2 for n in nums]              # [2, 4, 6]
      [n for n in nums if n > 1]      # [2, 3]
      {n * 2 for n in nums}           # set

      A for loop inside brackets — the idiomatic way to transform a list.

    • Dict

      {n: n ** 2 for n in range(4)}   # {0: 0, 1: 1, 2: 4, 3: 9}

      Same shape, with a colon between the key and the value.

  • Files & CSV

    • Read a file

      text = open("file.txt").read()
      lines = text.splitlines()

      The easiest read; use with open(...) as f when you need streaming.

    • CSV rows

      import csv
      with open('data.csv') as f:
          rows = list(csv.reader(f))

      rows[0] is the header; each later row is a list of strings — convert to numbers before math.

  • pandas (Data Analysis)

    • Load & glance

      import pandas as pd
      df = pd.read_csv('data.csv')
      df.head()      # first 5 rows
      df.describe()  # numeric summary

      The standard incantation — pd.read_csv is how every data lesson starts.

    • Columns & rows

      df['name']          # one column
      df[['a', 'b']]      # several
      df.loc[0]           # first row
      df[df['age'] > 30]  # filter rows

      Square brackets on a column name; boolean masks for filtering.

    • Group & aggregate

      df.groupby('city')['sales'].sum()
      df.groupby('city').mean()

      groupby + one summary method is the pivot of the Data Analysis section.

  • Error recovery

    • Read the last line

      TypeError: unsupported operand type(s) for +: 'int' and 'str'

      The final line names the error and the offending values — it is the message that says what to fix.

    • try / except

      try:
          total = int(user_input) * 2
      except ValueError:
          print('That was not a number')

      Catch only the specific error you expect; catching everything hides real bugs.