logo
eng-flag

Python Cheatsheet

Table of Contents

  1. Basic Syntax
  2. Data Types
  3. Variables
  4. Operators
  5. Control Flow
  6. Functions
  7. Data Structures
  8. File Handling
  9. Exception Handling
  10. Object-Oriented Programming
  11. Modules and Packages

Basic Syntax

Comments

# This is a single-line comment

"""
This is a
multi-line comment
"""

Indentation

Python uses indentation to define code blocks. Typically, 4 spaces are used for indentation.

if True:
    print("This is indented")
    if True:
        print("This is further indented")

Data Types

Numeric Types

# Integer
x = 5
print(type(x))  # <class 'int'>

# Float
y = 5.0
print(type(y))  # <class 'float'>

# Complex
z = 1 + 2j
print(type(z))  # <class 'complex'>

String

s1 = 'Single quotes'
s2 = "Double quotes"
s3 = '''Triple quotes for
multi-line strings'''

# String operations
print(len(s1))  # 13
print(s1 + " " + s2)  # Concatenation
print(s1[0])  # 'S'
print(s1[0:6])  # 'Single'

Boolean

a = True
b = False
print(type(a))  # <class 'bool'>

Variables

# Variable assignment
x = 5
y = "Hello"

# Multiple assignment
a, b, c = 1, 2, 3

# Constants (by convention, use uppercase)
PI = 3.14159

Operators

Arithmetic Operators

a, b = 10, 3

print(a + b)  # Addition: 13
print(a - b)  # Subtraction: 7
print(a * b)  # Multiplication: 30
print(a / b)  # Division: 3.3333...
print(a // b)  # Floor division: 3
print(a % b)  # Modulus: 1
print(a ** b)  # Exponentiation: 1000

Comparison Operators

x, y = 5, 10

print(x == y)  # Equal to: False
print(x != y)  # Not equal to: True
print(x > y)   # Greater than: False
print(x < y)   # Less than: True
print(x >= y)  # Greater than or equal to: False
print(x <= y)  # Less than or equal to: True

Logical Operators

a, b = True, False

print(a and b)  # Logical AND: False
print(a or b)   # Logical OR: True
print(not a)    # Logical NOT: False

Control Flow

If-Else Statement

x = 10

if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")

For Loop

# Iterating over a sequence
for i in [1, 2, 3]:
    print(i)

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

# Enumerate
for index, value in enumerate(['a', 'b', 'c']):
    print(f"Index: {index}, Value: {value}")

While Loop

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

Break and Continue

for i in range(10):
    if i == 3:
        continue  # Skip 3
    if i == 8:
        break  # Stop at 8
    print(i)

Functions

Defining and Calling Functions

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))  # Hello, Alice!

Default Arguments

def power(base, exponent=2):
    return base ** exponent

print(power(3))     # 9
print(power(3, 3))  # 27

*args and **kwargs

def func(*args, **kwargs):
    print("Positional:", args)
    print("Keyword:", kwargs)

func(1, 2, 3, a=4, b=5)
# Positional: (1, 2, 3)
# Keyword: {'a': 4, 'b': 5}

Lambda Functions

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

Data Structures

Lists

fruits = ['apple', 'banana', 'cherry']

# Accessing elements
print(fruits[0])  # apple

# Modifying elements
fruits[1] = 'blueberry'

# Adding elements
fruits.append('date')
fruits.insert(1, 'orange')

# Removing elements
fruits.remove('cherry')
popped = fruits.pop()

# Slicing
print(fruits[1:3])  # ['orange', 'blueberry']

# List comprehension
squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

Tuples

# Tuples are immutable
coordinates = (3, 4)
x, y = coordinates  # Unpacking

# Creating a tuple with one element
single_element = (1,)

Dictionaries

person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# Accessing values
print(person['name'])  # John

# Adding/modifying key-value pairs
person['job'] = 'Engineer'
person['age'] = 31

# Removing key-value pairs
del person['city']

# Dictionary methods
print(person.keys())
print(person.values())
print(person.items())

# Dictionary comprehension
squared = {x: x**2 for x in range(5)}
print(squared)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Sets

fruits = {'apple', 'banana', 'cherry'}

# Adding elements
fruits.add('date')

# Removing elements
fruits.remove('banana')

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2)  # Union
print(set1 & set2)  # Intersection
print(set1 - set2)  # Difference

File Handling

Reading from a File

# Reading entire file
with open('file.txt', 'r') as f:
    content = f.read()

# Reading line by line
with open('file.txt', 'r') as f:
    for line in f:
        print(line.strip())

Writing to a File

# Writing to a file
with open('output.txt', 'w') as f:
    f.write('Hello, World!')

# Appending to a file
with open('output.txt', 'a') as f:
    f.write('
Appended line')

Exception Handling

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"An error occurred: {e}")
else:
    print("No exception occurred")
finally:
    print("This always executes")

Object-Oriented Programming

Defining a Class

class Dog:
    def __init__(self, name):
        self.name = name
    
    def bark(self):
        return f"{self.name} says Woof!"

# Creating an instance
my_dog = Dog("Buddy")
print(my_dog.bark())  # Buddy says Woof!

Inheritance

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        pass

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

cat = Cat("Whiskers")
print(cat.speak())  # Whiskers says Meow!

Modules and Packages

Importing Modules

import math
print(math.pi)

from datetime import datetime
print(datetime.now())

import random as rd
print(rd.randint(1, 10))

Creating a Module

# In mymodule.py
def greet(name):
    return f"Hello, {name}!"

# In main.py
import mymodule
print(mymodule.greet("Alice"))

Working with Packages

# Assuming a package structure:
# mypackage/
#     __init__.py
#     module1.py
#     module2.py

# In main.py
from mypackage import module1
from mypackage.module2 import some_function

2024 © All rights reserved - buraxta.com