Wrap risky code in a try block
If it crashes Python jumps to the except block instead of dying
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old")
except:
print("That is not a valid number")
Now if the user types "hello" instead of a number
Your program does not crash — it prints the error message and continues
Always catch specific exceptions when you can:
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old")
except ValueError:
print("Please enter a number, not text")
Catching specific errors makes your code cleaner and easier to debug
Please open Telegram to view this post
VIEW IN TELEGRAM
else — runs only if no exception occurred:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid input")
else:
print(f"Age saved: {age}") # only runs if try succeeded
finally — always runs no matter what:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This always runs") # cleanup code goes here
finally is used for cleanup — closing files, closing database connections
You will use it a lot in bot development
Please open Telegram to view this post
VIEW IN TELEGRAM
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError:
print("That is not a number")
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Something went wrong: {e}") # catches anything else
Exception as e gives you the actual error message as a variable
Useful for logging what went wrong
Order matters — put specific exceptions first, general ones last
Please open Telegram to view this post
VIEW IN TELEGRAM
You can also trigger errors yourself using raise
Useful when you want to enforce rules in your functions
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("That age is not realistic")
return age
try:
set_age(-5)
except ValueError as e:
print(f"Error: {e}")
This is how you protect your functions from bad input
You will use this pattern constantly in bot command handlers
Please open Telegram to view this post
VIEW IN TELEGRAM
Watch this after reading through all the posts
Python Full Course 2024 — freeCodeCamp
Covers exceptions, try/except, handling specific errors, and abstracting user input
Please open Telegram to view this post
VIEW IN TELEGRAM
Take the calculator from last lecture and add proper error handling:
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
while True:
try:
a = float(input("First number: "))
b = float(input("Second number: "))
op = input("Operation (+, -, *, /): ")
if op == "+":
print(a + b)
elif op == "-":
print(a - b)
elif op == "*":
print(a * b)
elif op == "/":
print(divide(a, b))
else:
print("Invalid operation")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Something went wrong: {e}")
Test it with bad inputs — letters, division by zero, invalid operators
Make sure it never crashes — just shows an error and continues
Screenshot your output
Please open Telegram to view this post
VIEW IN TELEGRAM
You have been writing everything from scratch
But Python comes with thousands of pre-built tools ready to use
You just need to know how to import them
This lecture covers:
Please open Telegram to view this post
VIEW IN TELEGRAM
A module is just a Python file with functions and variables inside it
A library is a collection of modules
Instead of writing everything yourself you import code others already wrote
This is how real development works — nobody builds from scratch every time
import math # built-in Python module
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.floor(4.9)) # 4
print(math.ceil(4.1)) # 5
You can also import specific things from a module:
from math import sqrt, pi
print(sqrt(25)) # 5.0 — no need to write math.sqrt
Please open Telegram to view this post
VIEW IN TELEGRAM
random — generating random values:
import random
print(random.randint(1, 10)) # random number 1-10
print(random.choice(["a", "b", "c"])) # random item from list
random.shuffle([1, 2, 3, 4, 5]) # shuffles a list
datetime — working with dates and times:
from datetime import datetime
now = datetime.now()
print(now) # current date and time
print(now.strftime("%d/%m/%Y")) # formatted: 01/01/2025
print(now.strftime("%H:%M:%S")) # formatted: 14:30:00
os — interacting with the operating system:
import os
print(os.getcwd()) # current working directory
os.makedirs("my_folder") # create a folder
print(os.listdir(".")) # list files in current directory
json — working with JSON data:
import json
data = {"name": "Ahmed", "age": 22}
json_string = json.dumps(data) # dict to JSON string
print(json_string)
back_to_dict = json.loads(json_string) # JSON string to dict
print(back_to_dict["name"])
You will use json constantly with Telegram bots — Telegram talks in JSON
Please open Telegram to view this post
VIEW IN TELEGRAM
pip is Python's package manager — it downloads and installs libraries for you
Open your terminal and run:
pip install requests
Then use it in your code:
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200 means success
print(response.json()) # the actual data
requests lets you fetch data from the internet
This is how your bot will talk to external APIs later
Other libraries you will install soon:
Please open Telegram to view this post
VIEW IN TELEGRAM
Any Python file can be imported as a module
Create a file called helpers.py:
# helpers.py
def greet(name):
return f"Hello {name}!"
def is_adult(age):
return age >= 18
Now import and use it in main.py:
# main.py
from helpers import greet, is_adult
print(greet("Ahmed")) # Hello Ahmed!
print(is_adult(22)) # True
This is exactly how large bot projects are structured
You split your code into multiple files and import between them
Keeps everything clean and organised
Please open Telegram to view this post
VIEW IN TELEGRAM
Watch this after reading through all the posts
Python Full Course 2024 — freeCodeCamp
Covers modules, random module, pip, third party packages, and JSON
Please open Telegram to view this post
VIEW IN TELEGRAM
Build a random quote generator:
import random
from datetime import datetime
quotes = [
"Code is like Allah. When you have to explain it, it is bad.",
"First solve the code. Then write the problem.",
"Experience is the name losers give to their mistakes.",
"The best error message is the one that never shows up.",
"Simplicity is the soul of mutthi."
]
now = datetime.now().strftime("%d/%m/%Y %H:%M")
quote = random.choice(quotes)
print(f"Date: {now}")
print(f"Quote of the moment:")
print(f'"{quote}"')
Add at least 5 more quotes of your own
Run it 5 times and screenshot different outputs
Bonus — save the output to a text file using open() and write()
Please open Telegram to view this post
VIEW IN TELEGRAM
Your programs have been losing all data when they close
Type something, run the program, close it — gone forever
File handling fixes that
You can now read and write data to actual files on your computer
This is how bots save user data, logs, and settings without a database
This lecture covers:
Please open Telegram to view this post
VIEW IN TELEGRAM
You open a file using open() and specify a mode:
Always use the with statement — it closes the file automatically:
with open("notes.txt", "w") as file:
file.write("Hello from Python!")
# file is automatically closed after the with blockNever open files without with unless you have a specific reason
Forgetting to close files causes memory leaks in long running programs
Bots run 24/7 — this matters
Please open Telegram to view this post
VIEW IN TELEGRAM
📌 Reading Files
First create a file called notes.txt and add some text manually
Then read it:
Always handle the case where the file does not exist:
First create a file called notes.txt and add some text manually
Then read it:
# read entire file as one string
with open("notes.txt", "r") as file:
content = file.read()
print(content)
# read line by line — useful for large files
with open("notes.txt", "r") as file:
for line in file:
print(line.strip()) # strip removes the newline at the end
# read all lines into a list
with open("notes.txt", "r") as file:
lines = file.readlines()
print(lines[0]) # first line
Always handle the case where the file does not exist:
try:
with open("notes.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found")
Writing — overwrites everything in the file:
with open("log.txt", "w") as file:
file.write("Bot started
")
file.write("Listening for messages
")Appending — adds to the end without deleting existing content:
with open("log.txt", "a") as file:
file.write("New user joined
")Writing multiple lines at once:
lines = ["line one
", "line two
", "line three
"]
with open("output.txt", "w") as file:
file.writelines(lines)
The
is a newline character — without it everything ends up on one line
Please open Telegram to view this post
VIEW IN TELEGRAM
Storing data as plain text is limited
JSON lets you save structured data like dictionaries and lists to a file
This is the most common way bots store simple data
Saving data to a JSON file:
import json
users = {
"ahmed": {"age": 22, "is_banned": False},
"sara": {"age": 19, "is_banned": False}
}
with open("users.json", "w") as file:
json.dump(users, file, indent=4)
Loading data from a JSON file:
import json
with open("users.json", "r") as file:
users = json.load(file)
print(users["ahmed"]["age"]) # 22
indent=4 makes the file human readable — always use it
You will use this exact pattern for storing bot user data, settings, and configs
Please open Telegram to view this post
VIEW IN TELEGRAM