Python Programming Cheat Sheet: Essential Syntax and Libraries

Numbers and Math

  • Arithmetic: +, -, /, // (floor), % (remainder), ** (exponent).
  • Shorthand: a += 2 (also -=, *=, //=).
  • Functions: abs(-3.5), round(3.56, 1), max(3.56, 4.57).

Strings and Formatting

  • Quotes: 'spam eggs', "doesn't".
  • Newline: print('\n').
  • F-Strings: f'Price {cost:.2f}', f'{ratio:.2%}'.

Data Types

  • int (whole), float (decimal), str (text), bool (True/False).
  • Input: input() (returns string), int(input()) (converts to integer).

Decision Making

age = int(input('Enter your age: ')) if age >= 18: print('You can vote') else: print('You cannot vote yet')

Operators

  • == (equal), != (not equal), >= (greater/equal), < (less than).

Lists and Slicing

  • Indexing: data = [1, 'hello', 5.5]. data[0] is 1. Negative indexing starts from -1.
  • Slicing: data[1:3] (index 1 to 2), data[:2] (start to 1), data[2:] (2 to end).
  • Operations: append(x), extend(list2), insert(i, x), pop(), remove(x), index(5).

Dictionaries

  • phone_nums = {'Debby': 999, 'Abe': 555}.
  • Access: phone_nums['Wei'].
  • Delete: del phone_nums['Abe'].

Loops and Flow Control

  • While: while count <= 5:. Use break to exit.
  • For: Iterates through lists, strings, or dictionary keys.
  • Range: range(start, stop, step).
  • List Comprehensions: [d**2 for d in data if d > 0].

Functions and Scope

  • Define: def add(a, b): return a + b.
  • Scope: Global vs Local variables.

NumPy Basics

  • np.array([[1,2],[3,4]]).
  • Attributes: B.shape, B.dtype.
  • Functions: np.zeros(), np.arange(), np.linspace(), np.mean(), np.std().

Matplotlib and Seaborn

  • Matplotlib: plt.plot(), plt.scatter(), plt.hist(), plt.subplots().
  • Seaborn: sns.histplot(), sns.boxplot(), sns.heatmap().

Pandas Data Structures

  • Series: 1D labeled array. s.loc['Label'], s.iloc[0].
  • DataFrame: 2D table. df['Column'], df.iloc[row, col].
  • Operations: drop(), sort_values(), apply(), concat(), describe().
  • Date Parsing: pd.to_datetime() using format codes like %Y-%m-%d.