Python programming language cheat sheet that has more than the common or frequently used syntax and features (more details &/or the max info to know well about this programming language).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating a comprehensive Python cheat sheet that covers more than just the common or frequently used syntax and features can be quite extensive. Below is a detailed cheat sheet that includes a wide range of Python features, from basic syntax to advanced topics. This cheat sheet is organized into sections for easier navigation.
Python Cheat Sheet
1. Basic Syntax
Comments
python
# This is a single-line comment
"""
This is a
multi-line comment
"""
Variables and Data Types
python
# Integer
x = 10
# Float
y = 10.5
# String
name = "Alice"
# Boolean
is_valid = True
# List
numbers = [1, 2, 3, 4, 5]
# Tuple
coordinates = (10.0, 20.0)
# Dictionary
person = {"name": "Alice", "age": 30}
# Set
unique_numbers = {1, 2, 3, 4, 5}
Basic Operations
python
# Arithmetic
a = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus
print(a ** b) # Exponentiation
print(a // b) # Floor Division
# Comparison
print(a == b) # Equal
print(a != b) # Not Equal
print(a > b) # Greater than
print(a < b) # Less than
print(a >= b) # Greater than or equal to
print(a <= b) # Less than or equal to
2. Control Flow
Conditional Statements
python
if a > b:
print("a is greater than b")
elif a == b:
print("a is equal to b")
else:
print("a is less than b")
Loops
python
# For Loop
for i in range(5):
print(i)
# While Loop
count = 0
while count < 5:
print(count)
count += 1
Loop Control
python
# Break
for i in range(10):
if i == 5:
break
print(i)
# Continue
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Else with Loops
for i in range(5):
print(i)
else:
print("Loop completed without break")
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
4. Data Structures
Lists
python
# Creating a list
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print(fruits[0])
# Slicing
print(fruits[1:3])
# Adding elements
fruits.append("orange")
fruits.insert(1, "grape")
# Removing elements
fruits.remove("banana")
del fruits[0]
# List comprehensions
squares = [x**2 for x in range(10)]
Tuples
python
# Creating a tuple
coordinates = (10.0, 20.0)
# Accessing elements
print(coordinates[0])
# Unpacking
x, y = coordinates
Dictionaries
python
# Creating a dictionary
person = {"name": "Alice", "age": 30}
# Accessing values
print(person["name"])
# Adding/Updating elements
person["age"] = 31
person["city"] = "New York"
# Removing elements
del person["city"]
# Dictionary comprehensions
squares = {x: x**2 for x in range(6)}
Sets
python
# Creating a set
unique_numbers = {1, 2, 3, 4, 5}
# Adding elements
unique_numbers.add(6)
# Removing elements
unique_numbers.remove(3)
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Union
print(set1.intersection(set2)) # Intersection
print(set1.difference(set2)) # Difference
5. Modules and Packages
Importing Modules
python
import math
print(math.sqrt(16))
from math import sqrt
print(sqrt(16))
import my_module
my_module.my_function()
Creating Modules
python
# my_module.py
def my_function():
print("Hello from my_module!")
6. File I/O
Reading Files
python
with open("file.txt", "r") as file:
content = file.read()
print(content)
Writing Files
python
with open("file.txt", "w") as file:
file.write("Hello, World!")
Appending to Files
python
with open("file.txt", "a") as file:
file.write("\nAppending this line.")
7. Exception Handling
Try-Except
python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Try-Except-Else-Finally
python
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful!")
finally:
print("This will always execute.")
8. Advanced Topics
Generators
python
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
for value in gen:
print(value)
Context Managers
python
class MyContextManager:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting the context")
with MyContextManager() as manager:
print("Inside the context")
Metaclasses
python
class MyMeta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=MyMeta):
pass