Python

Python


How to Python

This is the fastest way to shift into python gear, more blinker fluids are listed after.

Indentation Matters

Python uses indentation instead of curly braces to define blocks of code. Incorrect indentation will throw an error.

if x > 5:
    print("x is greater than 5")  # Correct
print("This is outside the if block")

No Semicolons

Python does not require semicolons at the end of statements.

x = 10  # No semicolon needed

Variables and Types

Python is dynamically typed, so you don’t need to declare variable types. Use type() to check the type of a variable.

x = 10          # Integer
x = "Hello"     # Now it's a string
print(type(x))  # Output: <class 'str'>

Strings

Strings can be enclosed in single quotes, double quotes, or triple quotes for multi-line strings.

s = "Hello"
s = 'Hello'
s = """This is a
multi-line string"""

Lists vs Arrays

Python uses lists instead of arrays. Lists are dynamic and can hold mixed types.

my_list = [1, 2, 3, "Hello"]

For Loops

Python’s for loop is more like a foreach loop. Use range() for traditional indexing.

for i in range(5):  # 0 to 4
    print(i)

No Switch-Case

Python does not have a switch-case statement. Use if-elif-else or dictionaries instead.

choice = 2
if choice == 1:
    print("Case 1")
elif choice == 2:
    print("Case 2")
else:
    print("Default case")

Functions

Use def to define functions. No need to specify return types.

def add(a, b):
    return a + b

No Increment/Decrement Operators

Python does not have ++ or --. Use += or -= instead.

x = 5
x += 1  # Equivalent to x++

Input and Output

Use input() to take user input (returns a string) and print() for output.

name = input("Enter your name: ")
print("Hello,", name)

File Handling

Use open() to open files. Always close files with close() or use with for automatic closing.

with open("file.txt", "r") as file:
    content = file.read()

No Pointers

Python does not have pointers. Variables are references to objects.

a = [1, 2, 3]
b = a  # b references the same list as a
b[0] = 10
print(a)  # Output: [10, 2, 3]

Global Variables

Use the global keyword to modify global variables inside a function.

x = 10
def change_x():
    global x
    x = 20

List Comprehensions

Python has a concise way to create lists using list comprehensions.

squares = [x**2 for x in range(10)]

No Main Function

Python scripts don’t require a main() function, but you can use if __name__ == "__main__": to define executable code.

def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()

Exception Handling

Use try-except for exception handling.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Modules and Imports

Use import to include modules.

import math
print(math.sqrt(16))  # Output: 4.0

No null

Python uses None instead of null.

x = None

Dictionaries

Python’s equivalent of a map or hash table is a dictionary.

my_dict = {"key1": "value1", "key2": "value2"}
print(my_dict["key1"])  # Output: value1

Tuples

Tuples are immutable sequences.

my_tuple = (1, 2, 3)

Sets

Sets are unordered collections of unique elements.

my_set = {1, 2, 3}

Lambda Functions

Python supports anonymous functions using lambda.

square = lambda x: x**2
print(square(5))  # Output: 25

No do-while Loop

Python does not have a do-while loop. Use while with a condition.

while True:
    # Do something
    if condition:
        break

String Formatting

Use f-strings (Python 3.6+) for clean string formatting.

name = "Alice"
print(f"Hello, {name}!")

Syntax

Variables & Data Types

# πŸ’  Integer
x = 10

# πŸ’  Float
y = 3.14  

# πŸ’  String
name = "Alice"  

# πŸ’  Boolean
is_active = True

# πŸ’  NoneType
data = None  

Conditionals

x = 10
if x > 5:
    print("Greater than 5")
elif x == 5:
    print("Equal to 5")
else:
    print("Less than 5")

Loops

# πŸ’  For loop
for i in range(5):  # 0 to 4
    print(i)

# πŸ’  While loop
x = 5
while x > 0:
    print(x)
    x -= 1

Operators

# ♦️Arithmetic operators
# πŸ’  Addition
print(10 + 3)

# πŸ’  Exponentiation
print(10 ** 2)

# πŸ’  Floor division
print(10 // 3)  

# πŸ’  Comparison operators
x = 5
print(x == 5)
print(x != 3)

# πŸ’  Logical operators
if x > 0 and x < 10:
    print("Valid range")

Conditional Flow

# If-elif-else
age = 18
if age < 13:
    print("Child")
elif age < 20:
    # This will execute
    print("Teen")  
else:
    print("Adult")

# Ternary operator
status = "Allowed" if age >= 18 else "Denied"

Comments

# Single-line comment

"""
Multi-line comment
(using triple-quotes)
"""

def calculate():
    '''Docstring comment 
    explaining function purpose'''

Input/Output

# πŸ’  Basic output
print("Hello", "World!", sep="-")

# πŸ’  Formatted string (f-string)
name = "Alice"
print(f"Hello {name}!")

# πŸ’  User input
age = input("Enter your age: ")
print(f"You're {age} years old")

Common Data Structures

Strings

Strings are immutable sequences used for text manipulation.

String Manipulation and Methods

# πŸ’  String manipulation
greeting = "Hello, world!"

# πŸ’  Slicing a string
# ➝ Hello (First 5 characters) βœ‚οΈ
print(greeting[:5])

# πŸ’  String methods
# ➝ ['Hello', 'world!'] 🧩
split_str = greeting.split(", ")

# ➝ 'Hello-world!' ➑️
joined_str = "-".join(split_str)  

# πŸ’  Removing whitespaces
str_with_spaces = "   lots of space   "
print(str_with_spaces.strip())
# ➝ 'lots of space' βœ‚οΈ

Lists

Python lists are dynamic arrays (like ArrayList in Java or arrays in JavaScript).

List Creation, Indexing, and Slicing

# Creating a list with values
nums = [10, 20, 30, 40]

# Creating an empty list
empty_list = [] 

# Mixed type list (integer, string, float)
mixed = [1, "hello", 3.14]  

# Nested list (list inside a list)
nested = [[1, 2], [3, 4]] 

# Accessing elements by index
print(nums[0])  #first element)
print(nums[-1]) #(last element)

# Slicing the list (Start index inclusive, end exclusive)
print(nums[1:3]) #from index 1 to 2
print(nums[:2])  #first 2 elements
print(nums[-3:]) #last 3 elements

List Methods

# Append value to the list
nums.append(50)

# Insert value at a specific index
nums.insert(2, 99)  #inserts 99 at index 

# Pop removes and returns the last item
nums.pop()

# Remove first occurrence of value
nums.remove(99)

# Reverse the list
nums.reverse()

# Sort the list in ascending order
nums.sort(

# Sort in descending order
nums.sort(reverse=True)

List Comprehensions

# Creating a list of squares
squares = [x**2 for x in range(5)]

# Creating a list of even numbers
evens = [x for x in range(10) if x % 2 == 0]

Tuples

Tuples are immutable sequences, useful for fixed collections of items.

Tuple Creation and Unpacking

# Creating a tuple
tup = (1, 2, 3)

# Single element tuple (comma is needed)
single_element_tuple = (10,)

# Unpacking tuple values into variables
a, b, c = tup  # a=1, b=2, c=3

# Nested tuples
nested_tup = ((1, 2), (3, 4))

Dictionaries

Dictionaries store data as key-value pairs.

Dictionary Creation and Methods

# Creating a dictionary
my_dict = {"name": "Alice", "age": 25, "city": "Wonderland"}

# Accessing value by key
print(my_dict["name"])

# Adding or updating a key-value pair
my_dict["age"] = 26  # Updates
my_dict["country"] = "Utopia"  # Adds

# Removing a key-value pair
del my_dict["city"]  # Removes 'city'

# Dictionary methods
keys = my_dict.keys() 
values = my_dict.values() 
items = my_dict.items()

Sets

Sets are unordered collections of unique elements.

Set Operations

# Creating a set
my_set = {1, 2, 3, 4}

# Adding an element to the set
my_set.add(5)

# Removing an element from the set
my_set.remove(3) 

# Union of sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1.union(set2) 

# Intersection of sets
intersection = set1.intersection(set2)

Functions

Functions allow you to group code into reusable blocks.

Function Definition & Usage

# Function definition with parameters and return value
def greet(name):
    # Function that greets the person by name
    return f"Hello, {name}!"

# Calling the function
print(greet("Alice"))

Arguments

# Positional Arguments
def add(a, b):
    return a + b
print(add(3, 4))

# Keyword Arguments
def greet(name, message="Hello"):
    return f"{message}, {name}!"
print(greet(name="Bob", message="Good morning"))
print(greet(name="Alice"))

# Default Argument
def multiply(a, b=2):
    return a * b
print(multiply(5))  # ➝ 10 (b defaults to 2)
print(multiply(5, 3))  # ➝ 15 (b is overridden)

# *args (Variable Positional Arguments)
def add_numbers(*args):
    return sum(args)  
print(add_numbers(1, 2, 3, 4))

# **kwargs (Variable Keyword Arguments)
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}") 
print_info(name="John", age=25, city="NY")

Lambda Functions

# Lambda function definition (an anonymous function)
square = lambda x: x**2 

# Using the lambda function
print(square(5))

Scope

# Local and Global Scope
x = 10  # Global variable 🌎

def my_function():
    x = 5  # Local variable inside function 🏠
    print(x)  # ➝ 5 (local variable is used here)

my_function()
print(x)  # ➝ 10 (global variable is accessed here)

# Nonlocal keyword to modify variable from enclosing scope
def outer_function():
    x = 10  # Enclosing scope variable πŸ“¦
    
    def inner_function():
        nonlocal x  # Refers to x in outer function's scope
        x = 20  # Modifies x in enclosing scope
        
    inner_function()
    print(x)  # ➝ 20 (modified by inner_function)

outer_function()

Object-Oriented Pythoning

Defining Classes & Objects

class Car:
    def __init__(self, brand, model):
        self.brand = brand  # Instance variable
        self.model = model

my_car = Car("Tesla", "Model S")  # Creating an object
print(my_car.brand)  # ➝ Tesla

Instance & Class Variables

class Employee:
    company = "TechCorp"  # Class variable

    def __init__(self, name, salary):
        self.name = name  # Instance variable
        self.salary = salary

emp1 = Employee("Alice", 60000)
emp2 = Employee("Bob", 75000)
print(emp1.company) 
print(emp2.salary)

Methods & Static Methods

class MathUtils:
    # Instance method
    def add(self, a, b):  
        return a + b

    @staticmethod
    def multiply(a, b):
        return a * b

math = MathUtils()
print(math.add(5, 3))
print(MathUtils.multiply(4, 2))

Encapsulation & Private Variables

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private variable

    def get_balance(self):
        return self.__balance  # Access via method

account = BankAccount(5000)
print(account.get_balance())
# print(account.__balance)

Inheritance

class Animal:
    def speak(self):
        return "Animal speaks"

# Inheriting from Animal
class Dog(Animal):  
    def speak(self):
        return "Woof!"

d = Dog()
print(d.speak())

Polymorphism

class Bird:
    def make_sound(self):
        return "Chirp!"

class Cat:
    def make_sound(self):
        return "Meow!"

def play_sound(animal):
    print(animal.make_sound())

play_sound(Bird())  # ➝ Chirp!
play_sound(Cat())   # ➝ Meow!

Dunder Methods (Magic Methods)

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):  # Overloading '+'
        return Vector(self.x + other.x, self.y + other.y)

v1, v2 = Vector(3, 4), Vector(1, 2)
v3 = v1 + v2
print(v3.x, v3.y)  # ➝ 4, 6

Common Errors

IndentationError

Cause : Inconsistent spaces/tabs in indentation
Fix : Use 4 spaces per indent (PEP 8 standard)
# ❌ Wrong
def hello():
      print("Hello") 
      # Mixed tab and space

# βœ… Correct
def hello():
    print("Hello")

TypeError: 'NoneType' object is not subscriptable

Cause : Trying to index a function that returns None
Fix : Ensure the function actually returns a list/dict
def get_data():
    return None

data = get_data()
print(data[0])  # ❌ TypeError

# βœ… Fix
if data:
    print(data[0])

File Handling

Opening & Closing Files

# Open file (default 'r' mode)  
file = open('data.txt')  
file.close()  

# Using with statement (auto-closes)  
with open('data.txt') as file:  
    pass

Reading Files

# Read entire content  
with open('data.txt') as f:  
    content = f.read()  

# Read line by line  
with open('data.txt') as f:  
    for line in f:  
        print(line.strip())  

Writing Files

# Overwrite file ('w' mode)  
with open('output.txt', 'w') as f:  
    f.write('New content')  

# Write multiple lines  
lines = ['First', 'Second']  
with open('data.txt', 'w') as f:  
    f.writelines(lines)  

Appending to Files

# Add to existing file  
with open('logs.txt', 'a') as f:  
    f.write('New log entry');

File Modes

r - Read (default)
w - Write (overwrite)
a - Append
r+ - Read + Write
b - Binary mode
t - Text mode (default)

Working with CSV

import csv  

# Read CSV  
with open('data.csv', 'r') as f:  
    reader = csv.reader(f)  
    for row in reader:  
        print(row)  

# Write CSV  
data = [['Name', 'Age'], ['Alice', 28]]  
with open('data.csv', 'w') as f:  
    writer = csv.writer(f)  
    writer.writerows(data) 

JSON Handling

import json  

# Write JSON  
data = {'name': 'Alice', 'age': 30}  
with open('data.json', 'w') as f:  
    json.dump(data, f)  

# Read JSON  
with open('data.json') as f:  
    loaded = json.load(f) 

Exception Handling

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("Cleanup actions here")

Multi-Threading & Async

import asyncio

async def fetch_data():
    print("Fetching...")
    await asyncio.sleep(2)  # Simulates delay
    print("Done!")

asyncio.run(fetch_data())

Why Solo Dev?

This reference website is not for beginners
Solo Dev is strictly for devs who already know the game and need a beautiful cheat sheet on their second monitor which looks better than GeeksforGeeks


this portion goes away when you shrink the screen ;)

Our popular languages: