Learn Coding
57 subscribers
21 links
Download Telegram
📌 Most Useful Built-in Modules

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
📌 Installing External Libraries with pip

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:
➡️ aiogram — for building Telegram bots
➡️ pyrogram — for MTProto bots and userbots
➡️ python-dotenv — for managing secret tokens safely
Please open Telegram to view this post
VIEW IN TELEGRAM
📌 Creating Your Own Modules

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
🚨 Video Reference

Watch this after reading through all the posts

Python Full Course 2024 — freeCodeCamp

🔖 Watch from 4:50:31 → 5:48:12
Covers modules, random module, pip, third party packages, and JSON
Please open Telegram to view this post
VIEW IN TELEGRAM
✏️ Lecture 10 Homework

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()

⚠️ Next lecture drops in 2 days — File Handling
🔥 After that we go straight into Telegram Bots
Please open Telegram to view this post
VIEW IN TELEGRAM
This media is not supported in your browser
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:
➡️ Opening and closing files
➡️ Reading files
➡️ Writing and appending to files
➡️ Working with JSON files
➡️ The with statement
Please open Telegram to view this post
VIEW IN TELEGRAM
📌 Opening and Closing Files

You open a file using open() and specify a mode:

➡️ "r" — read (file must exist)
➡️ "w" — write (creates file, overwrites if exists)
➡️ "a" — append (adds to end, creates if not exists)
➡️ "x" — create (fails if file already exists)

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 block


Never 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:

# 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 and Appending

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
📌 Working with JSON Files

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
🚨 Video Reference

Watch this after reading through all the posts

Python Full Course 2024 — freeCodeCamp

🔖 Watch from 6:56:46 → 8:26:54
Covers file I/O, appending, with keyword, reading files, CSV files, and binary files
Please open Telegram to view this post
VIEW IN TELEGRAM
✏️ Lecture 11 Homework

Build a persistent to-do list — one that saves and loads from a file:

import json
import os

FILENAME = "todos.json"

def load_todos():
if os.path.exists(FILENAME):
with open(FILENAME, "r") as f:
return json.load(f)
return []

def save_todos(todos):
with open(FILENAME, "w") as f:
json.dump(todos, f, indent=4)

todos = load_todos()

while True:
print("
1. View todos")
print("2. Add todo")
print("3. Delete todo")
print("4. Exit")

choice = input("Choose: ")

if choice == "1":
for i, task in enumerate(todos):
print(f"{i + 1}. {task}")

elif choice == "2":
task = input("New task: ").strip()
todos.append(task)
save_todos(todos)
print("Saved!")

elif choice == "3":
num = int(input("Task number to delete: ")) - 1
removed = todos.pop(num)
save_todos(todos)
print(f"Deleted: {removed}")

elif choice == "4":
break


Run it, add tasks, close it, run it again — your tasks are still there
That is persistence
Screenshot your output

⚠️ Next lecture drops in 2 days — OOP
🔥 After that we start Telegram Bots
Please open Telegram to view this post
VIEW IN TELEGRAM
This media is not supported in your browser
VIEW IN TELEGRAM
while (alive) {
repeat();
}

void repeat() {
eat();
sleep();
code();
}
📚 𝗟𝗲𝗰𝘁𝘂𝗿𝗲 𝟭𝟮 — 𝗢𝗯𝗷𝗲𝗰𝘁 𝗢𝗿𝗶𝗲𝗻𝘁𝗲𝗱 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴

Everything you have learned so far is procedural programming
Code that runs step by step, top to bottom

OOP is a different way of thinking about code
Instead of writing functions that do things
You create objects that have their own data and their own functions

Every major library you will use — aiogram, pyrogram, telethon — is built with OOP
You need to understand it to read and write real code

This lecture covers:
➡️ Classes and objects
➡️ Attributes and methods
➡️ The init method
➡️ Inheritance
➡️ How OOP appears in real bot code
Please open Telegram to view this post
VIEW IN TELEGRAM
📌 Classes and Objects

A class is a blueprint
An object is something built from that blueprint

Think of a class as the design for a car
An object is the actual car built from that design
You can build many cars from one design — each a separate object

class Dog:
pass # empty class for now

dog1 = Dog() # create an object from the class
dog2 = Dog() # another object — completely separate

print(type(dog1)) # <class 'main.Dog'>


dog1 and dog2 are both Dogs but they are separate objects
Changes to one do not affect the other
Please open Telegram to view this post
VIEW IN TELEGRAM
📌 init and Attributes

init runs automatically when you create an object
It is where you set the initial data for the object
self refers to the object itself

class User:
def init(self, name, age):
self.name = name
self.age = age

user1 = User("Ahmed", 22)
user2 = User("Sara", 19)

print(user1.name) # Ahmed
print(user2.age) # 19


self.name and self.age are attributes — data that belongs to each object
user1 has its own name and age, user2 has its own
They do not share data
Please open Telegram to view this post
VIEW IN TELEGRAM
📌Methods

Methods are functions that belong to a class
They always take self as the first parameter

class User:
def init(self, name, age):
self.name = name
self.age = age
self.is_banned = False

def greet(self):
print(f"Hello I am {self.name} and I am {self.age} years old")

def ban(self):
self.is_banned = True
print(f"{self.name} has been banned")

def status(self):
if self.is_banned:
print(f"{self.name}: Banned")
else:
print(f"{self.name}: Active")

user1 = User("Ahmed", 22)
user1.greet()
user1.ban()
user1.status()


Output:
Hello I am Ahmed and I am 22 years old
Ahmed has been banned
Ahmed: Banned
Please open Telegram to view this post
VIEW IN TELEGRAM