TL;DR:
This beginner‑friendly Python cheat sheet covers installation, syntax essentials, variables and types, strings, lists/tuples/dicts/sets, conditionals, loops, functions, modules, file I/O, errors, virtual environments, common libraries, and quick recipes—plus copy‑paste code blocks you can run immediately.

low cost unlimited emails

🧭 At a Glance (SEO Quick Facts)

  • Primary keyword: Python programming cheat sheet
  • Secondary keywords: Python basics, Python for beginners, Python syntax, Python tips
  • Ideal readers: New programmers, students, non‑technical professionals automating tasks

✅ Getting Started

Install Python

 

python –version
# or on macOS/Linux:
python3 –version

 

Run Python

 

# Start REPL
python

 

# Run a script
python hello.py

 

🧱 Python Syntax Essentials

 

# Comments
# This is a comment

 

# Printing
print(“Hello, Python”)

 

# Variables (dynamic typing)
name = “Anshul”
count = 3
price = 9.99
is_ready = True

 

Data Types

 

x_int = 10                 # int
x_float = 3.14             # float
x_bool = True              # bool
x_str = “Python”           # str
x_none = None              # NoneType

 

Type Conversion

 

int(“7”)        # 7
float(“3.5”)    # 3.5
str(42)         # “42”
bool(0)         # False

 

🔤 Strings (immutable)

 

s = “cheat sheet”
s.upper()           # ‘CHEAT SHEET’
s.title()           # ‘Cheat Sheet’
s.replace(” “, “_”) # ‘cheat_sheet’
len(s)              # 11
“cheat” in s        # True
s[0:5]              # ‘cheat’  (slice)

 

f-strings:

 

name, score = “Alex”, 95
print(f”{name} scored {score}/100″)  # Alex scored 95/100

 

📦 Lists, Tuples, Dicts, Sets

List (ordered, mutable)

 

nums = [3, 1, 2]
nums.append(4)
nums.sort()          # [1, 2, 3, 4]
nums[0]              # 1

 

Tuple (ordered, immutable)

 

point = (10, 20)
x, y = point

 

Dict (key → value)

 

user = {“name”: “Alex”, “age”: 21}
user[“country”] = “IN”
user.get(“role”, “guest”)  # ‘guest’
for k, v in user.items():
    print(k, v)

 

Set (unique, unordered)

 

a = {1, 2, 3}
b = {3, 4}
a | b     # {1,2,3,4} union
a & b     # {3} intersection

 

🔀 Conditionals

 

age = 18
if age >= 18:
    print(“Adult”)
elif 13 <= age < 18:
    print(“Teen”)
else:
    print(“Child”)

 

# Ternary
status = “even” if age % 2 == 0 else “odd”

 

🔁 Loops

 

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

 

# Looping collections
for item in [“a”, “b”, “c”]:
    print(item)

 

# While
n = 3
while n > 0:
    n -= 1

 

# Comprehensions
squares = [x*x for x in range(5)]  # [0,1,4,9,16]
evens = {x for x in range(10) if x % 2 == 0}

 

🧩 Functions & Scope

 

def greet(name: str, excited: bool = False) -> str:
    msg = f”Hello, {name}”
    return msg + “!” if excited else msg

 

print(greet(“Anshul”, True))

 

Args & Kwargs

 

def demo(*args, **kwargs):
    print(args)    # tuple of positional args
    print(kwargs)  # dict of keyword args

 

demo(1, 2, a=3, b=4)

 

Lambdas

add = lambda x, y: x + y

📚 Modules & Packages

 

# math module
import math
math.sqrt(16)          # 4.0

 

# from-import
from statistics import mean
mean([1, 2, 3])        # 2

 

Your own module (file utils.py)

 

def shout(s): return s.upper()

 

Use it:

 

import utils
print(utils.shout(“python”))

 

🗂️ File I/O

 

# Write
with open(“notes.txt”, “w”, encoding=”utf-8″) as f:
    f.write(“Hello\n”)

 

# Read
with open(“notes.txt”, “r”, encoding=”utf-8″) as f:
    content = f.read()

 

# Read lines
with open(“notes.txt”) as f:
    for line in f:
        print(line.strip())

 

🧯 Errors & Exceptions

 

try:
    10 / 0
except ZeroDivisionError as e:
    print(“Cannot divide by zero:”, e)
finally:
    print(“Always runs”)

 

Raise an error

 

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError(“Insufficient funds”)
    return balance – amount

 

🧪 Virtual Environments & Packages

 

# Create & activate (Windows)
python -m venv .venv
.venv</span>Scripts</span>activate

 

# macOS/Linux
python3 -m venv .venv
source .venv/bin/activate

 

# Install packages
pip install requests pandas

 

# Freeze
pip freeze > requirements.txt

 

🧠 Must‑Know Built‑ins

 

len(seq)          # length
type(x)           # type of x
range(start, stop, step)
enumerate(list)   # index + value
sum([1,2,3])      # 6
min/max([..])
sorted([3,1,2])   # [1,2,3]
zip(a, b)         # pair items

 

🧭 Common Library Mini‑Recipes

HTTP Request (with requests)

 

import requests
r = requests.get(“https://api.github.com”)
print(r.status_code, r.json().get(“current_user_url”))

 

CSV with pandas

 

import pandas as pd
df = pd.read_csv(“data.csv”)
print(df.head())
df.to_csv(“out.csv”, index=False)

 

Dates & Times

 

from datetime import datetime, timedelta
now = datetime.now()
next_week = now + timedelta(days=7)
print(now.strftime(“%Y-%m-%d %H:%M”))

 

Random & Seeding

 

import random
random.seed(42)
random.choice([“red”, “green”, “blue”])

 

Simple CLI Args

 

import sys
print(“Args:”, sys.argv[1:])  # python app.py foo bar

 

🧹 Style & Good Practices (PEP 8 quick hits)

  • Use 4 spaces for indentation.
  • Snake_case for variables and functions: total_count.
  • UpperCase for classes: MyClass.
  • Keep lines ≤ 79–99 chars where possible.
  • Add docstrings:

 

def add(a: int, b: int) -> int:
    “””Return the sum of a and b.”””
    return a + b

 

🧪 Quick Project: “Number Guessing Game”

 

# save as guess.py
import random

 

secret = random.randint(1, 50)
attempts = 0
print(“Guess a number between 1 and 50”)

 

while True:
    attempts += 1
    try:
        guess = int(input(“Your guess: “))
    except ValueError:
        print(“Please enter a valid integer.”)
        continue

 

    if guess < secret:
        print(“Too low!”)
    elif guess > secret:
        print(“Too high!”)
    else:
        print(f”Congrats! You guessed it in {attempts} tries.”)
        break

 

Run: python guess.py

❓FAQs (Beginner‑Friendly)

Is Python fast enough?
For most tasks (automation, data analysis, web backends) yes. For heavy compute, use optimized libraries (NumPy, pandas) or C/C++ extensions.

Which editor should I use?
VS Code (with Python extension), PyCharm Community, or even IDLE for the absolute start.

What’s the best way to learn?
Build tiny projects daily: a unit converter, a to‑do CLI, a CSV cleaner.

📌 Summary

This cheat sheet gives you the practical Python building blocks you’ll use every day—clean syntax, data structures, control flow, functions, files, errors, and must‑have tooling—plus mini‑recipes to get real work done quickly.