Kahibaro
Discord Login Register

Python syntax cheat sheet

Basic Script Structure

# This is a comment
def main():
    print("Hello")
if __name__ == "__main__":
    main()

Comments

Variables and Basic Types

Common literals:

Multiple assignment:

x, y = 1, 2
a = b = 0

Check type:

type(42)           # <class 'int'>
type("hi")         # <class 'str'>

Arithmetic Operators

Augmented assignment:

x += 1   # x = x + 1
x -= 2   # x = x - 2
x *= 3
x /= 4

Comparison and Logical Operators

Comparison (result is True or False):

Logical:

age = 20
is_adult = age >= 18 and age < 65

Identity / membership (common usage):

x is None
"py" in "python"

Strings

Create:

text = "Hello"
other = 'World'

Concatenation and repetition:

"Hello" + " " + "World"
"ha" * 3   # "hahaha"

Indexing and slicing:

s = "python"
s[0]       # 'p'
s[-1]      # 'n'
s[1:4]     # 'yth'
s[:3]      # 'pyt'
s[3:]      # 'hon'

Basic string methods (pattern):

s.lower()
s.upper()
s.strip()
s.split(",")
",".join(["a", "b"])

Input and Output

Input from user (always str):

name = input("Enter your name: ")

Convert input:

age = int(input("Enter age: "))
price = float(input("Enter price: "))

Printing:

print("Hello")
print("Name:", name, "Age:", age)
print(f"Name: {name}, Age: {age}")
print("a", "b", sep="-", end="!\n")

if / elif / else

Basic structure:

if condition:
    # block
    ...
elif other_condition:
    ...
else:
    ...

Example:

age = 18
if age < 18:
    print("Minor")
elif age == 18:
    print("Just adult")
else:
    print("Adult")

One‑line conditional expression:

status = "adult" if age >= 18 else "minor"

while Loops

Structure:

while condition:
    # repeated block
    ...

Example with counter:

count = 0
while count < 5:
    print(count)
    count += 1

for Loops

Loop over a sequence:

for char in "abc":
    print(char)
for item in [1, 2, 3]:
    print(item)

Ranges:

range(stop)          # 0 .. stop-1
range(start, stop)
range(start, stop, step)
for i in range(5):           # 0..4
    print(i)
for i in range(1, 6, 2):     # 1,3,5
    print(i)

break and continue

for i in range(10):
    if i == 5:
        break       # exit loop
    if i % 2 == 0:
        continue    # skip to next iteration
    print(i)

Lists

Create:

numbers = [1, 2, 3]
mixed = [1, "a", True]
empty = []

Index and slice:

numbers[0]       # first
numbers[-1]      # last
numbers[1:3]     # slice

Modify:

numbers.append(4)
numbers.insert(1, 10)
numbers.remove(2)
popped = numbers.pop()      # last element

Iterate:

for n in numbers:
    print(n)

Check membership:

if 3 in numbers:
    print("found")

Tuples

Create (immutable sequences):

coords = (10, 20)
single = (5,)        # note comma

Index:

coords[0]

Tuple unpacking:

x, y = coords

Dictionaries

Create:

person = {
    "name": "Alice",
    "age": 30
}

Access and modify:

person["name"]
person["age"] = 31
person["city"] = "Paris"

Safe get:

person.get("country", "Unknown")

Iterate:

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

Sets

Create:

items = {1, 2, 3}
empty_set = set()

Basic operations:

items.add(4)
items.remove(2)
3 in items        # membership
a = {1, 2, 3}
b = {3, 4}
a | b             # union
a & b             # intersection
a - b             # difference

Functions

Define and call:

def greet(name):
    print("Hello", name)
greet("Alice")

Return values:

def add(a, b):
    return a + b
result = add(2, 3)

Default parameters:

def power(base, exp=2):
    return base ** exp
power(3)        # 9
power(3, 3)     # 27

Imports and Modules

Basic import:

import math
x = math.sqrt(16)

Import specific names:

from math import sqrt, pi
r = sqrt(9)

Alias:

import numpy as np

Working with Files (Text)

Basic pattern:

with open("data.txt", "r", encoding="utf-8") as f:
    text = f.read()
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")

Common modes: "r" (read), "w" (write, overwrite), "a" (append).

Exceptions (try / except)

Basic structure:

try:
    x = int(input("Enter number: "))
except ValueError:
    print("Not a valid integer")

Multiple excepts and finally:

try:
    with open("file.txt") as f:
        data = f.read()
except FileNotFoundError:
    print("File not found")
except PermissionError:
    print("No permission")
finally:
    print("Done")

Raise an exception:

raise ValueError("Invalid value")

Simple Classes (OOP Syntax)

Define a class:

class Person:
    def __init__(self, name, age):
        self.name = name    # attribute
        self.age = age
    def greet(self):
        print(f"Hi, I'm {self.name}")
p = Person("Alice", 30)
p.greet()

Inheritance:

class Employee(Person):
    def __init__(self, name, age, role):
        super().__init__(name, age)
        self.role = role

Common Built‑in Functions (Syntax Shape)

Some useful built‑ins (names only, detailed meaning in other chapters):

Example patterns:

for index, value in enumerate(["a", "b"]):
    print(index, value)
for a, b in zip([1, 2], [3, 4]):
    print(a, b)

Basic Boolean and None Checks

if value is None:
    ...
if value:          # truthy check
    ...
else:
    ...

List Comprehensions (Syntax Form)

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

Quick Style Reminders (Syntax‑Related)

Views: 13

Comments

Please login to add a comment.

Don't have an account? Register now!