Python Cheatsheet

Quick reference for Python programming with examples

Basic Syntax
# Print to console
print("Hello, World!")

# Get user input
name = input("Enter your name: ")

# Comments
# This is a single line comment
"""This is a multi-line comment"""
print() Print to console
input() Get user input
len() Get length
type() Get data type
str() Convert to string
int() Convert to integer
float() Convert to float
Data Types
# Numbers
x = 10 # int
y = 3.14 # float
z = 1j # complex

# Strings
text = "Python"
multiline = """Line 1 Line 2"""

# Boolean
is_active = True
str String type
int Integer type
float Float type
bool Boolean type
list List type
tuple Tuple type
dict Dictionary type
List Operations
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
my_list.insert(0, 0)
my_list.remove(3)
popped = my_list.pop()
list.append() Add element
list.insert() Insert at position
list.pop() Remove last element
list.remove() Remove element
list.sort() Sort list
list.reverse() Reverse list
list.index() Find index
list.count() Count elements
Dictionary Operations
my_dict = {"name": "Python", "age": 30}
my_dict["city"] = "New York"
del my_dict["age"]
value = my_dict.get("name")
dict.keys() Get all keys
dict.values() Get all values
dict.items() Get key-value pairs
dict.get() Get value
dict.update() Update dictionary
dict.pop() Remove element
dict.clear() Clear dictionary
Conditional Statements
if x > 10:
  print("Greater than 10")
elif x == 10:
  print("Equal to 10")
else:
  print("Less than 10")
if Check condition
elif Check another condition
else Default case
and Logical AND
or Logical OR
not Logical NOT
in Membership test
Loops
# For loop
for i in range(5):
  print(i)

# While loop
count = 0
while count < 5:
  print(count)
  count += 1
for For loop
while While loop
range() Generate range
break Break loop
continue Skip iteration
enumerate() Index and value
Functions
def my_function(param1, param2="default"):
  """This is a function"""
  return param1 + " " + param2

result = my_function("Hello")
def Define function
return Return value
lambda Anonymous function
*args Variable arguments
**kwargs Keyword arguments
global Global variable
nonlocal Nonlocal variable
File Operations
# Write to file
with open("file.txt", "w") as f:
  f.write("Hello Python")

# Read from file
with open("file.txt", "r") as f:
  content = f.read()
open() Open file
"r" Read mode
"w" Write mode
"a" Append mode
f.read() Read file
f.write() Write to file
f.close() Close file
OOP Concepts
class Person:
  def __init__(self, name):
    self.name = name

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

p = Person("John")
class Define class
__init__ Constructor
self Instance reference
inheritance Inheritance
super() Parent class
@property Property decorator
@staticmethod Static method
Popular Libraries
numpy Numerical computing
pandas Data analysis
matplotlib Data visualization
requests HTTP requests
flask Web framework
django Web framework
scrapy Web scraping
tensorflow Machine learning
Debugging & Tips
print() Debug print
pdb Python debugger
try/except Error handling
finally Always execute
raise Throw error
assert Assertion check
logging Logging module
help() Help function

What is CodeSikhoWithAJ?

CodeSikhoWithAJ is a coding education platform dedicated to teaching programming to everyone. Our mission is to make coding accessible and help people start their journey in the tech industry.

Founded by Ajeet Yadav, CodeSikhoWithAJ provides comprehensive tutorials, practical examples, and hands-on projects to help you master web development and other programming skills.

Trusted by these companies:

Google
Microsoft
Facebook
Amazon
Netflix
Twitter