All Cheat Sheets
Py
Python Cheat Sheet
Basics
PrintOutput to consoleprint("Hello, World!")VariablesDynamic typing, no declaration neededname = "Mishu"
age = 25
pi = 3.14CommentsSingle and multi-line# This is a comment
"""
Multi-line string
as a comment
"""InputRead user inputname = input("Enter your name: ")Data Types
StringsText datas = "hello"
s.upper()
s.replace("h", "j")ListsOrdered, mutable sequencenums = [1, 2, 3]
nums.append(4)
nums[0] # 1TuplesOrdered, immutable sequencepoint = (3, 4)
x, y = pointDictionariesKey-value pairsd = {"name": "Mishu", "age": 25}
d["name"]
d.get("key", "default")SetsUnordered unique elementss = {1, 2, 3}
s.add(4)
{1, 2} | {2, 3} # unionControl Flow
If-elif-elseConditional executionif x > 0:
print("positive")
elif x == 0:
print("zero")
else:
print("negative")For loopIterate over a sequencefor i in range(5):
print(i)
for k, v in d.items():
print(k, v)While loopLoop while condition is truewhile x > 0:
x -= 1List comprehensionConcise list creationsquares = [x**2 for x in range(10) if x % 2 == 0]Functions
DefineFunction definition using defdef greet(name, greeting="Hello"):
return f"{greeting}, {name}!"LambdaAnonymous functiondouble = lambda x: x * 2
list(map(lambda x: x**2, [1, 2, 3]))*args, **kwargsVariable argumentsdef func(*args, **kwargs):
print(args, kwargs)