Python Basic Syntax Cheat Sheet

A concise reference for Python beginners and developers coming from languages like JavaScript, Java, or C++.

1. Variables & Data Types

1
2
3
4
5
6
7
8
x = 10              # int
y = 3.14 # float
name = "Alice" # string
is_valid = True # boolean
items = [1, 2, 3] # list
data = {"a": 1} # dict
nums = (1, 2, 3) # tuple
unique = {1, 2, 3} # set

Type Checking

1
2
type(x)        # <class 'int'>
isinstance(x, int) # True

2. Control Flow

If / Elif / Else

1
2
3
4
5
6
if x > 10:
print("Large")
elif x == 10:
print("Equal")
else:
print("Small")

Ternary Expression

1
msg = "even" if x % 2 == 0 else "odd"

3. Loops

For Loop

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

for item in items: # iterate over list
print(item)

While Loop

1
2
3
while x > 0:
print(x)
x -= 1

Break / Continue

1
2
3
4
5
6
for i in range(5):
if i == 2:
continue
if i == 4:
break
print(i)

4. Functions

1
2
3
4
def greet(name):
return f"Hello, {name}!"

print(greet("Wen"))

Default & Keyword Arguments

1
2
3
4
5
def power(base, exp=2):
return base ** exp

print(power(3)) # 9
print(power(exp=3, base=2)) # 8

Lambda (Anonymous Function)

1
2
square = lambda x: x ** 2
print(square(4)) # 16

5. Collections (List / Dict / Set / Tuple)

List

1
2
3
4
5
6
7
nums = [1, 2, 3]
nums.append(4)
nums.extend([5, 6])
nums.insert(1, 100)
nums.pop()
nums.remove(100)
print(nums[::-1]) # reverse

Dictionary

1
2
3
4
5
6
person = {"name": "Alice", "age": 25}
print(person["name"])
person["city"] = "Sydney"

for key, value in person.items():
print(key, value)

Set

1
2
3
4
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # union
print(a & b) # intersection

Tuple

1
2
point = (10, 20)
x, y = point # unpacking

6. List Comprehensions

1
2
squares = [x**2 for x in range(5)]
even = [x for x in range(10) if x % 2 == 0]

7. String Operations

1
2
3
4
5
6
7
s = "Python"
print(s.lower())
print(s.upper())
print(s.replace("Py", "My"))
print(s[0:3]) # slicing
print("Hello " + s)
print(f"Welcome to {s}!")

8. Classes & Objects

1
2
3
4
5
6
7
8
9
10
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
return f"Hi, I'm {self.name}!"

p = Person("Alice", 25)
print(p.greet())

9. File I/O

1
2
3
4
5
6
with open("data.txt", "w") as f:
f.write("Hello, file!")

with open("data.txt", "r") as f:
content = f.read()
print(content)

10. Common Built-in Functions

Function Description Example
len() length len([1,2,3]) → 3
sum() sum of elements sum([1,2,3]) → 6
max(), min() largest/smallest max([1,5,3]) → 5
sorted() return sorted list sorted([3,1,2]) → [1,2,3]
enumerate() get index + value for i,v in enumerate(arr)
zip() combine iterables zip([1,2], ['a','b']) → [(1,'a'), (2,'b')]
map() apply function map(str, [1,2,3]) → ['1','2','3']
filter() filter items filter(lambda x: x>0, nums)

11. Error Handling

1
2
3
4
5
6
try:
x = 10 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero!")
finally:
print("Done.")

12. Imports & Modules

1
2
3
4
5
import math
from datetime import datetime

print(math.sqrt(16))
print(datetime.now())

13. Useful One-liners

1
2
3
4
5
6
7
8
9
10
11
12
# Swap values
a, b = b, a

# Read input
name = input("Enter name: ")

# Check membership
if "x" in [1, "x", 3]:
print("Found!")

# Conditional expression
status = "OK" if success else "FAILED"

14. Comments & Docstrings

Single-line comment

1
2
3
4
"""
Multi-line comment or docstring
Use triple quotes for documentation.
"""