Python Language Basics
Variables and Types
Section titled “Variables and Types”You don’t declare types or use keywords like var — assign a value and the variable exists.
x = 42 # intname = "Alice" # strpi = 3.14 # floatflag = True # boolitems = [1, 2, 3] # listperson = {"name": "Bob", "age": 25} # dictpair = (1, 2) # tupletags = {1, 2} # setCommon types: int, float, str, bool, list, dict, tuple, set. See Data structures for details and when to use each.
Comments
Section titled “Comments”# Single-line commentx = 1 # inline commentIndentation and Blocks
Section titled “Indentation and Blocks”Python uses indentation (usually 4 spaces) to define blocks. No braces.
if x > 0: print("positive")else: print("non-positive")Conditionals
Section titled “Conditionals”if n < 0: result = "negative"elif n == 0: result = "zero"else: result = "positive"for and while. See the Loops cheatsheet for more.
for x in [1, 2, 3]: print(x)
while n > 0: n -= 1List and Dict Basics
Section titled “List and Dict Basics”# List: zero-based index, slicenums = [10, 20, 30]first = nums[0] # 10subset = nums[1:3] # [20, 30]nums.append(40)
# Dict: key-valued = {"a": 1, "b": 2}d["c"] = 3value = d.get("x", 0) # default if missingNone and Truthiness
Section titled “None and Truthiness”None is the “no value” object. In conditions, False, 0, "", [], {} are falsy; most else is truthy.
result = Noneif items: # falsy if empty process(items)