Python Basics Cheat Sheet β€” Syntax, Variables, Operators, Print | Dataplexa

Python Basics

Syntax rules  Β·  Variables & types  Β·  Operators  Β·  print() & input()  Β·  Comments

Sheet 1 of 10 Python 3.x Beginner Printable

Python Syntax Rules

must know first
Structure & Blocks
# Colon ( : ) opens every block
if age > 18:
    print("adult")   # 4 spaces

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

# No curly braces  { }
# No semicolons required
# Indentation IS the structure
Line Continuation
# Backslash continues a line
total = 100 + 200 \
        + 300

# Parentheses β€” preferred style
result = (
    1 + 2
    + 3 + 4
)

# Multiple statements (avoid)
x = 1; y = 2  # semicolon ok
Case-Sensitivity & Identifiers
# Python is CASE-SENSITIVE
name  = "Alice"
Name  = "Bob"    # different var!
NAME  = "Carol"  # different again

# Valid identifiers
user_name  # snake_case  βœ“
_private   # leading _   βœ“
value2     # letter+digits βœ“
# 2value   β†’ SyntaxError  βœ—
# for      β†’ keyword      βœ—
Golden rule: Python uses indentation (4 spaces) to define code blocks β€” not braces. Mixing spaces and tabs raises an IndentationError. Always use spaces only.

Variables

assignment
Creating & Assigning
name    = "Alice"         # str
age     = 25              # int
height  = 5.9             # float
active  = True            # bool
score   = None            # NoneType

# Multiple assignment (tuple unpack)
a, b, c = 1, 2, 3

# Same value to many variables
x = y = z = 0

# Swap without a temp variable
a, b = b, a
Checking & Deleting
type(age)              # <class 'int'>
isinstance(age, int)    # True
id(age)                # memory address

del score              # removes the variable
No declaration needed. Variables are created on assignment. Python is dynamically typed β€” the same variable can hold different types over its life.

Core Data Types

types overview
TypeExampleMutable?
int 42 -7 0 1_000 No
float 3.14 -0.5 1e3 No
bool True False No
str "hi" 'hello' No
NoneTypeNone No
list [1, 2, 3] Yes βœ“
dict {"k": "v"} Yes βœ“
tuple (1, 2, 3) No
set {1, 2, 3} Yes βœ“
Sheet scope: int Β· float Β· bool Β· str Β· None are covered here. list Β· dict Β· tuple Β· set are in Sheet 2 β€” Data Types.

Numbers β€” int & float

numeric
Integer Literals
x = 42           # decimal
x = 1_000_000   # underscores for readability
x = 0b1010      # binary  β†’ 10
x = 0xFF        # hex     β†’ 255
x = 0o17        # octal   β†’ 15
Float & Useful Functions
f = 3.14
f = 1.5e3        # 1500.0  (scientific notation)
f = 1.5e-3       # 0.0015

round(3.14159, 2)    # 3.14
abs(-9)              # 9
int(3.9)             # 3  β€” truncates, not rounds
max(1, 5, 3)         # 5
min(1, 5, 3)         # 1
Float β‰  exact: 0.1 + 0.2 == 0.30000000000000004. Use the decimal module for financial calculations.

Booleans & None

bool / NoneType
Truthy & Falsy Values
# All of these evaluate to False
bool(0)       # False  β€” zero int
bool(0.0)     # False  β€” zero float
bool("")      # False  β€” empty string
bool([])      # False  β€” empty list
bool(None)    # False  β€” None

# All of these evaluate to True
bool(1)       # True   β€” non-zero
bool("hi")   # True   β€” non-empty string
bool([1])    # True   β€” non-empty list
None β€” absence of a value
result = None

# Always check None with "is", not "=="
if result is None:
    print("no value yet")

if result is not None:
    print("has a value")
bool is a subclass of int: True == 1 and False == 0. You can do True + True β†’ 2.

Type Conversion

casting
Explicit Casting
int("42")           # 42
int(3.9)            # 3  β€” truncates, not rounds
float("3.14")       # 3.14
float(5)            # 5.0
str(100)            # "100"
str(True)           # "True"
bool(1)             # True
bool("")            # False
Safe Conversion Patterns
# "3.14" β†’ int: go via float first
int(float("3.14"))      # 3

# Validate before converting
s = "42"
if s.isdigit():
    n = int(s)

# Number to formatted string
str(round(3.14159, 2))  # "3.14"
Watch out: int("3.14") raises ValueError. Always pass through float() first when the string contains a decimal point.

Operators

arithmetic Β· comparison Β· logical Β· identity Β· membership
Arithmetic
10 +  3   # 13   β€” addition
10 -  3   # 7    β€” subtraction
10 *  3   # 30   β€” multiplication
10 /  3   # 3.33 β€” true division
10 // 3   # 3    β€” floor division
10 %  3   # 1    β€” modulo (remainder)
2  ** 8   # 256  β€” exponentiation
Comparison (always return bool)
x == y    # equal to
x != y    # not equal to
x >  y    # greater than
x <  y    # less than
x >= y    # greater than or equal
x <= y    # less than or equal
# Chaining:  0 < x < 10  ← valid!
Logical Β· Identity Β· Membership
# Logical operators
True and False     # False
True or  False     # True
not True           # False

# Identity β€” same object in memory?
x is None
x is not None

# Membership β€” is x inside y?
"a" in     "cat"   # True
3   not in [1,2]   # True
Augmented Assignment
x +=  1    # x = x + 1
x -=  1    # x = x - 1
x *=  2    # x = x * 2
x /=  2    # x = x / 2
x //= 2    # x = x // 2
x %=  3    # x = x % 3
x **= 2    # x = x ** 2
Operator Precedence β€” high β†’ low
  • **Exponentiation (right-to-left)
  • +x -x ~xUnary plus / minus / bitwise NOT
  • * / // %Multiply, divide, modulo
  • + -Addition and subtraction
  • < <= > >= == !=Comparisons
  • notLogical NOT
  • andLogical AND
  • orLogical OR (lowest)

print() & input()

I / O
print() β€” all parameters
print("Hello, World!")

# sep β€” separator between values
print("a", "b", "c", sep="-")
# β†’ a-b-c

# end β€” replaces default newline
print("Hi", end=" ")
print("there")     # β†’ Hi there

# Print multiple values at once
print("x =", x, "y =", y)
f-strings β€” recommended formatting
name = "Alice"
age  = 25
pi   = 3.14159

print(f"Hi {name}!")
print(f"Pi = {pi:.2f}")    # 3.14
print(f"{name:>10}")    # right-align 10ch
print(f"{1000:,}")       # 1,000
print(f"{age=}")         # age=25  (debug)
input() β€” reading user input
# input() ALWAYS returns a string
name = input("Your name: ")

# Cast immediately after input
age  = int(input("Age:  "))
gpa  = float(input("GPA:  "))

# Safe input β€” catch bad input
try:
    n = int(input("Number: "))
except ValueError:
    print("Enter a valid number")

Comments & Docstrings

documentation
# Single-line comment
x = 10  # inline comment

"""
Module docstring β€” goes at
the top of a file or class.
"""

def add(a, b):
    """Return the sum of a and b.

    Args:
        a: First number.
        b: Second number.
    Returns:
        int or float sum.
    """
    return a + b

print(add.__doc__)   # access docstring
help(add)             # nicely formatted
Best practice: Comment why, not what. Write docstrings for every public function, class, and module.

Naming Conventions

PEP 8
WhatStyleExample
Variable snake_case user_name
Function snake_case get_data()
Class PascalCase UserProfile
Constant UPPER_CASE MAX_SIZE = 100
Private _leading _helper()
Dunder __double__ __init__
Module/filelowercase my_module.py
Package lowercase mypackage/
Run black . to auto-format your code, or flake8 . to check for style violations.

Common Beginner Errors

debug guide
IndentationError
# Wrong β€” missing indent
if True:
print("oops")  # ← Error!

# Correct
if True:
    print("ok")  # ← 4 spaces

# Mixed tabs + spaces
# β†’ TabError: use spaces only
TypeError & NameError
# TypeError: mismatched types
"Age: " + 25          # Error!
"Age: " + str(25)    # Fixed
print(f"Age: {25}")    # Better

# NameError: undefined variable
print(Score)   # Error! (capital S)
print(score)   # Fixed (check case)
ValueError & SyntaxError
# ValueError: bad value for type
int("hello")          # Error!
int("3.14")           # Error!
int(float("3.14"))   # 3  βœ“

# SyntaxError: typos / missing :
if x == 1             # Missing colon!
prnit("hi")          # Typo in print

Basics Mastery Checklist

sheet 1 complete
SyntaxKey point
Write a block with correct indentation4 spaces
Span a statement across multiple lines( ) or \
Understand case-sensitivityname β‰  Name
Name variables correctlysnake_case
Variables & TypesKey point
Assign single & multiple varsa, b = 1, 2
Know the 5 primitive typesint float bool str None
Cast between types safelyint(float("3.14"))
Identify truthy / falsy values0, "", None β†’ False
Operators & I/OKey point
All 7 arithmetic operators+ - * / // % **
Comparison & logical operators== != and or not
Format output with f-stringsf"Hello {name}"
Read and cast user inputint(input(…))
Next up β†’ Sheet 2: Python Data Types  Β·  int Β· str Β· list Β· dict Β· set Β· tuple β€” deeper coverage of every built-in type with methods, slicing, and real-world use cases.