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 page 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 missingString Indexing and Slicing
Section titled “String Indexing and Slicing”A string is a sequence of characters, so it uses the same indexing and slicing rules as a list: [start:stop] takes characters from start up to but not including stop. Omitting start means “from the beginning”; omitting stop means “through the end.” Slicing always returns a new string (strings are immutable).
s = "hello"first = s[0] # 'h'mid = s[1:4] # 'ell' — indexes 1, 2, 3prefix = s[:3] # 'hel' — same as s[0:3]suffix = s[2:] # 'llo' — from index 2 to the endsnippet = s[:80] # first 80 characters (shorter strings stay as-is)None 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)