Small Basic Python Code — Handy Snippets
1. Hello World & Variables
# Print and variables
message = "Hello, World!"
count = 3
print(message, count)
2. Input & Type Casting
# Read a number and add 5
# (uncomment input line to use interactively)
# n = int(input("Enter a number: "))
n = 7
print("n + 5 =", n + 5)
3. If / Else
x = 10
if x > 5:
print("Greater than 5")
else:
print("5 or less")
4. For Loop
for i in range(3):
print("Loop i =", i)
5. While Loop
i = 0
while i < 3:
print("i =", i)
i += 1
6. Functions
def add(a, b):
return a + b
print("add(2, 3) =", add(2, 3))
7. Lists
nums = [1, 2, 3]
[Link](4)
print(nums) # [1, 2, 3, 4]
print(nums[0]) # 1
8. List Comprehension
squares = [n*n for n in range(5)]
print(squares) # [0, 1, 4, 9, 16]
9. Tuples & Unpacking
point = (3, 4)
x, y = point
print(x, y) # 3 4
10. Dictionaries
user = {"name": "Asha", "age": 25}
print(user["name"]) # Asha
user["country"] = "India"
print(user)
11. Sets
a = {1, 2, 3}
b = {3, 4}
print(a | b) # union -> {1, 2, 3, 4}
print(a & b) # intersection -> {3}
12. Strings
s = "Python"
print([Link](), [Link]())
print(s[:3]) # 'Pyt'
13. Try / Except
try:
val = int("12x")
except ValueError as e:
print("Conversion failed:", e)
14. Classes (OOP)
class Greeter:
def __init__(self, name):
[Link] = name
def greet(self):
return f"Hello, {[Link]}!"
g = Greeter("Asha")
print([Link]())
15. File I/O
# Write
with open("[Link]", "w", encoding="utf-8") as f:
[Link]("Hello file!")
# Read
with open("[Link]", "r", encoding="utf-8") as f:
print([Link]())