Skip to content

Python Language Basics

First PublishedByAtif Alam

You don’t declare types or use keywords like var — assign a value and the variable exists.

x = 42 # int
name = "Alice" # str
pi = 3.14 # float
flag = True # bool
items = [1, 2, 3] # list
person = {"name": "Bob", "age": 25} # dict
pair = (1, 2) # tuple
tags = {1, 2} # set

Common types: int, float, str, bool, list, dict, tuple, set. See Data structures for details and when to use each.

# Single-line comment
x = 1 # inline comment

Python uses indentation (usually 4 spaces) to define blocks. No braces.

if x > 0:
print("positive")
else:
print("non-positive")
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 -= 1
# List: zero-based index, slice
nums = [10, 20, 30]
first = nums[0] # 10
subset = nums[1:3] # [20, 30]
nums.append(40)
# Dict: key-value
d = {"a": 1, "b": 2}
d["c"] = 3
value = d.get("x", 0) # default if missing

None is the “no value” object. In conditions, False, 0, "", [], {} are falsy; most else is truthy.

result = None
if items: # falsy if empty
process(items)