Sign In
Sign In

How to Create and Set Up a Telegram Chatbot

How to Create and Set Up a Telegram Chatbot
Hostman Team
Technical writer
Python
12.03.2025
Reading time: 18 min

Chatbots are software programs that simulate communication with users. Today, we use them for a wide range of purposes, from simple directories to complex services integrated with CRM systems and payment platforms.

People create bots for Telegram, Viber, Facebook Messenger, and other messaging platforms. Each platform has its own rules and capabilities—some lack payment integration, while others don't support flexible keyboards. This article focuses on user-friendly Telegram, which has a simple API and an active audience.

In this article, we will cover:

  • How to create a Telegram bot on your own
  • When it's convenient to use chatbot builders for development
  • How to integrate a chatbot with external services and APIs
  • What is needed for the bot to function smoothly
  • The key features of Aiogram, a popular Python library for chatbot development

Creating a Telegram Chatbot Without Programming Skills

Chatbot builders are becoming increasingly popular. These services allow you to create a bot using a simple "drag-and-drop" interface. No programming knowledge is required—you just build logic blocks like in a children's game.

However, there are some drawbacks to using chatbot builders:

  • Limited functionality. Most chatbot builders provide only a portion of Telegram API's capabilities. For example, not all of them allow integration with third-party services via HTTP requests. Those that do often have expensive pricing plans.
  • Generic scenarios. The minimal flexibility of builders leads to chatbots that look and function similarly.
  • Dependence on the service. If the platform goes offline or its pricing increases, you may have to migrate your bot elsewhere.

Builders are useful for prototyping and simple use cases—such as a welcome message, answering a few questions, or collecting contact information. However, more complex algorithms require knowledge of variables, data processing logic, and the Telegram API. Even when using a builder, you still need to understand how to address users by name, how inline keyboards work, and how to handle bot states.

Free versions of chatbot builders often come with limitations:

  • They may include advertising messages.
  • Some prevent integration with essential APIs.
  • Others impose limits on the number of users.

These restrictions can reduce audience engagement, making the chatbot ineffective. In the long run, premium versions of these builders can end up costing more than developing a bot from scratch and hosting it on your own server.

If you need a chatbot to handle real business tasks, automate processes, or work with databases, builders are often not sufficient. In such cases, hiring a developer is a better solution. A developer can design a flexible architecture, choose optimal technologies, and eliminate technical constraints that might hinder the project's scalability. If you already have a prototype built with a chatbot builder, you can use its logic as a starting point for technical specifications.

How to Create a Telegram Chatbot

Now, let's discuss how to create a Telegram chatbot using Python. You’ll need basic knowledge of variables, conditional statements, loops, and functions in Python.

To create chatbots, you can use a framework which is a set of tools, libraries, and ready-made solutions that simplify software development. You can work with the raw Telegram API and implement functionality using HTTP requests, but even for simple tasks, this approach requires writing thousands of lines of code.

In this guide, we’ll use Aiogram, one of the most popular frameworks for building Telegram chatbots in Python.

Step 1: Create a Virtual Environment for Your Project

Using a virtual environment in any Python project is considered good practice. Additionally, chatbots are often deployed on cloud servers where dependencies need to be installed. A virtual environment makes it easy to export a list of dependencies specific to your project.

Install the Python virtual environment:

sudo apt install python3-venv -y

Create a virtual Python environment in the working directory:

python -m venv venv

Activate the environment:

source ./venv/bin/activate

Step 2: Install Required Libraries

Install the Aiogram framework using pip:

pip install aiogram

Add a library for working with environment variables. We recommend this method for handling tokens in any project, even if you don’t plan to make it public. This reduces the risk of accidentally exposing confidential data.

pip install python-dotenv

You can also install any other dependencies as needed.

Step 3: Initialize Your Chatbot via BotFather

This is a simple step, but it often causes confusion. We need to interact with a Telegram bot that will generate and provide us with a token for our project.

  1. Open Telegram and start a chat with @BotFather.
  2. Click the Start button.
  3. The bot will send a welcome message. Enter the following command:
/newbot
  1. BotFather will ask for a name for your bot—this is what users will see in their chat list.
  2. Then, enter a username for your bot. It must be unique and end with "bot" (e.g., mycoolbot).
  3. Once completed, BotFather will create your chatbot, assign it a username, and provide you with a token.

Keep your token secret. Anyone with access to it can send messages on behalf of your chatbot. If your token is compromised, immediately generate a new one via BotFather.

Next, open a chat with your newly created bot and configure the following:

  1. Click the Edit button.
  2. Update the profile picture.
  3. Set a welcome message.
  4. Add a description.
  5. Configure default commands.

Step 4: Store Your Token Securely

Create an environment file named .env (this file has no name, only an extension). Add the following line:

BOT_TOKEN = your_generated_token

On Linux and macOS, you can quickly save the token using the following command:

echo "BOT_TOKEN = your_generated_token" > .env

Step 4: Create the Script

In your working directory, create a file called main.py—this will be the main script for your chatbot.

Now, import the following test code, which will send a welcome message to the user when they enter the /start command:

import asyncio  # Library for handling asynchronous code
import os  # Module for working with environment variables
from dotenv import load_dotenv  # Function to load environment variables from the .env file
from aiogram import Bot, Dispatcher, Router  # Import necessary classes from aiogram
from aiogram.types import Message  # Import Message class for handling incoming messages
from aiogram.filters import CommandStart  # Import filter for handling the /start command
 
# Create a router to store message handlers
router = Router()
 
# Load environment variables from .env
load_dotenv()
 
# Handler for the /start command
@router.message(CommandStart())  # Filter to check if the message is the /start command
async def cmd_start(message: Message) -> None:
    # Retrieve the user's first name and last name (if available)
    first_name = message.from_user.first_name
    last_name = message.from_user.last_name or ""  # If no last name, use an empty string
 
    # Send a welcome message to the user
    await message.answer(f"Hello, {first_name} {last_name}!")
 
# Main asynchronous function to start the bot
async def main():
    # Create a bot instance using the token from environment variables
    bot = Bot(token=os.getenv("BOT_TOKEN"))
 
    # Create a dispatcher to handle messages
    dp = Dispatcher()
 
    # Include the router with command handlers
    dp.include_router(router)
 
    # Start the bot in polling mode
    await dp.start_polling(bot)
 
# If the script is run directly (not imported as a module),
# execute the main() function
if __name__ == "__main__":
    asyncio.run(main())

The script is well-commented to help you understand the essential parts.If you don't want to dive deep, you can simply use Dispatcher and Router as standard components in Aiogram. We will explore their functionality later in this guide.

This ready-made structure can serve as a solid starting point for any chatbot project. As you continue development, you will add more handlers, keyboards, and states.

Step 5: Run and Test the Chatbot

Now, launch your script using the following command:

python main.py

Now you can open a chat with your bot in Telegram and start interacting with it.

Aiogram Framework v3.x Features Overview 

You only need to understand a few key components and functions of Aiogram to create a Telegram chatbot.

This section covers Aiogram v3.x, which was released on September 1, 2023. Any version starting with 3.x will work. While older projects using Aiogram 2.x still exist, version 2.x is now considered outdated.

Key Components of Aiogram

Bot

The Bot class serves as the interface to the Telegram API. It allows you to send messages, images, and other data to users.

bot = Bot(token=os.getenv("TOKEN"))

You can pass the token directly when initializing the Bot class, but it's recommended to use environment variables to prevent accidental exposure of your bot token.

Dispatcher

The Dispatcher is the core of the framework. It receives updates (incoming messages and events) and routes them to the appropriate handlers.

dp = Dispatcher()

In Aiogram v3, a new structure with Router is used (see below), but the Dispatcher is still required for initialization and launching the bot.

Router

In Aiogram v3, handlers are grouped within a Router. This is a separate entity that stores the bot's logic—command handlers, message handlers, callback handlers, and more.

from aiogram import Router
router = Router()

After defining handlers inside the router, developers register it with the Dispatcher:

dp.include_router(router)

Handling Commands

The most common scenario is responding to commands like /start or /help.

from aiogram import F
from aiogram.types import Message

@router.message(F.text == "/start")
async def cmd_start(message: Message):
    await message.answer("Hello! I'm a bot running on Aiogram.")
  • F.text == "/start" is a new filtering method in Aiogram v3.
  • message.answer(...) sends a reply to the user.

Handling Regular Messages

To react to any message, simply remove the filter or define a different condition:

@router.message()
async def echo_all(message: Message):
    await message.answer(f"You wrote: {message.text}")

In this example, the bot echoes whatever text the user sends.

Inline Buttons and Keyboards

from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup

inline_kb = InlineKeyboardMarkup(
    inline_keyboard=[
        [InlineKeyboardButton(text="Click me!", callback_data="press_button")]
    ]
)

@router.message(F.text == "/buttons")
async def show_buttons(message: Message):
    await message.answer("Here are my buttons:", reply_markup=inline_kb)

When the user clicks the button, the bot receives callback_data="press_button", which can be handled separately:

from aiogram.types import CallbackQuery

@router.callback_query(F.data == "press_button")
async def handle_press_button(callback: CallbackQuery):
    await callback.message.answer("You clicked the button!")
    await callback.answer()  # Removes the "loading" animation in the chat

Regular Buttons (Reply Keyboard)

Regular buttons differ from inline buttons in that they replace the keyboard. The user immediately sees a list of available response options. These buttons are tracked by the message text, not callback_data.

from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove

# Creating a reply keyboard
reply_kb = ReplyKeyboardMarkup(
    keyboard=[
        [
            KeyboardButton(text="View Menu"),
            KeyboardButton(text="Place Order")
        ]
    ],
    resize_keyboard=True  # Automatically adjusts button size
)

# Handling the /start command and showing the reply keyboard
@router.message(F.text == "/start")
async def start_cmd(message: Message):
    await message.answer(
        "Welcome! Choose an action:",
        reply_markup=reply_kb
    )

# Handling "View Menu" button press
@router.message(F.text == "View Menu")
async def show_menu(message: Message):
    await message.answer("We have pizza and drinks.")

# Handling "Place Order" button press
@router.message(F.text == "Place Order")
async def make_order(message: Message):
    await message.answer("What would you like to order?")

# Command to hide the keyboard
@router.message(F.text == "/hide")
async def hide_keyboard(message: Message):
    await message.answer("Hiding the keyboard", reply_markup=ReplyKeyboardRemove())

Filters and Middlewares

Filters

Filters help define which messages should be processed. You can also create custom filters.

from aiogram.filters import Filter

# Custom filter to check if a user is an admin
class IsAdmin(Filter):
    def __init__(self, admin_id: int):
        self.admin_id = admin_id

    async def __call__(self, message: Message) -> bool:
        return message.from_user.id == self.admin_id

# Using the filter to restrict a command to the admin
@router.message(IsAdmin(admin_id=12345678), F.text == "/admin")
async def admin_cmd(message: Message):
    await message.answer("Hello, Admin! You have special privileges.")

Middlewares

Middlewares act as intermediary layers between an incoming request and its handler. You can use them to intercept, modify, validate, or log messages before they reach their respective handlers.

import logging
from aiogram.types import CallbackQuery, Message
from aiogram.dispatcher.middlewares.base import BaseMiddleware

# Custom middleware to log incoming messages and callbacks
class LoggingMiddleware(BaseMiddleware):
    async def __call__(self, handler, event, data):
        if isinstance(event, Message):
            logging.info(f"[Message] from {event.from_user.id}: {event.text}")
        elif isinstance(event, CallbackQuery):
            logging.info(f"[CallbackQuery] from {event.from_user.id}: {event.data}")

        # Pass the event to the next handler
        return await handler(event, data)

async def main():
    load_dotenv()
    logging.basicConfig(level=logging.INFO)

    bot = Bot(token=os.getenv("BOT_TOKEN"))
    dp = Dispatcher()

    # Attaching the middleware
    dp.update.middleware(LoggingMiddleware())

    dp.include_router(router)
    await dp.start_polling(bot)

Working with States (FSM) in Aiogram 3

Aiogram 3 supports Finite State Machine (FSM), which is useful for step-by-step data collection (e.g., user registration, order processing). FSM is crucial for implementing multi-step workflows where users must complete one step before moving to the next.

For example, in a pizza ordering bot, we need to ask the user for pizza size and delivery address, ensuring the process is sequential. We must save each step's data until the order is complete.

Step 1: Declare States

from aiogram.fsm.state import State, StatesGroup

class OrderPizza(StatesGroup):
    waiting_for_size = State()
    waiting_for_address = State()

These states define different stages in the ordering process.

Step 2: Switch between states

from aiogram.fsm.context import FSMContext

@router.message(F.text == "/order")
async def cmd_order(message: Message, state: FSMContext):
    # Create inline buttons for selecting pizza size
    size_keyboard = InlineKeyboardMarkup(
        inline_keyboard=[
            [
                InlineKeyboardButton(text="Large", callback_data="size_big"),
                InlineKeyboardButton(text="Medium", callback_data="size_medium"),
                InlineKeyboardButton(text="Small", callback_data="size_small")
            ]
        ]
    )

    await message.answer(
        "What size pizza would you like? Click one of the buttons:",
        reply_markup=size_keyboard
    )
    # Set the state to wait for the user to choose a size
    await state.set_state(OrderPizza.waiting_for_size)

# Step 2: Handle button click for size selection
@router.callback_query(OrderPizza.waiting_for_size, F.data.startswith("size_"))
async def choose_size_callback(callback: CallbackQuery, state: FSMContext):
    # Callback data can be size_big / size_medium / size_small
    size_data = callback.data.split("_")[1]  # e.g., "big", "medium", or "small"

    # Save the selected pizza size in the temporary state storage
    await state.update_data(pizza_size=size_data)

    # Confirm the button press (removes "loading clock" in Telegram's UI)
    await callback.answer()

    await callback.message.answer("Please enter your delivery address:")
    await state.set_state(OrderPizza.waiting_for_address)

# Step 2a: If the user sends a message instead of clicking a button (in waiting_for_size state),
# we can handle it separately. For example, prompt them to use the buttons.
@router.message(OrderPizza.waiting_for_size)
async def handle_text_during_waiting_for_size(message: Message, state: FSMContext):
    await message.answer(
        "Please select a pizza size using the buttons above. "
        "We cannot proceed without this information."
    )

# Step 3: User sends the delivery address
@router.message(OrderPizza.waiting_for_address)
async def set_address(message: Message, state: FSMContext):
    address = message.text
    user_data = await state.get_data()
    pizza_size = user_data["pizza_size"]

    size_text = {
        "big": "large",
        "medium": "medium",
        "small": "small"
    }.get(pizza_size, "undefined")

    await message.answer(f"You have ordered a {size_text} pizza to be delivered at: {address}")
    # Clear the state — the process is complete
    await state.clear()

Notice how the temporary storage keeps track of user responses at each step. This storage is user-specific and does not require a database.

The user progresses through a chain of questions, and at the end, the order details can be sent to an internal API. 

Deploying the Bot: Running on a Server

Let's go through two main deployment methods.

Quick Method: Docker + Hostman App Platform

This method does not require any system administration knowledge; the entire deployment process is automated. Additionally, it helps save costs. Follow these steps:

  1. Export all project dependencies to a requirements.txt file. Using a virtual environment is recommended to avoid pulling in libraries from the entire system. Run the following command in the project directory terminal:

pip freeze > requirements.txt
  1. Add a deployment file to the project directory — Dockerfile. This file has no extension, just the name. Insert the following content:

FROM python:3.11
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 9999
CMD ["python", "main.py"]
  1. Create a Git repository and push it to GitHub. You can use a minimal set of Git commands from our guide by running these commands in sequence. Add the environment variables file (.env) to .gitignore to prevent it from being exposed publicly.
  2. Go to the Hostman control panel, select the App platform section, and click Create app. Go to the Docker tab and select Dockerfile.

Ad949683 3903 4dc5 Beac B7c88452105a

  1. Link your GitHub account or connect your Git repository via URL.
  2. Select the repository from the list after linking your GitHub account.
  3. Choose a configuration. Hostman Apps offers a configuration of 1 CPU x 3.3GHz, 1GB RAM, NVMe storage, which is ideal for simple text-based bots, projects with small inline keyboards, basic FSM logic, low-demand API requests, working with SQLite, or lightweight JSON files. This configuration can handle 50-100 users per minute.
  4. Add the bot token to environment variables. In the App settings, click + Add, enter BOT_TOKEN as the key, and paste the token obtained from BotFather as the value.
  5. Start the deployment and wait for it to complete. Once finished, the bot will be up and running.

Standard Method: Ubuntu + systemd

  1. Export all project dependencies to the requirements.txt file. Run the following command in the Terminal while in the project directory:

pip freeze > requirements.txt
  1. Create a cloud server in the Hostman panel with the desired configuration and Ubuntu OS.

Dda3122c E80d 416e 90bc B3fdb2a70b97

  1. Transfer project files to the directory on the remote server. The easiest way to do this is using the rsync utility if you're using Ubuntu/MacOS:

rsync -av --exclude="venv" --exclude=".idea" --exclude=".git" ./ root@176.53.160.13:/root/project

Don’t forget to replace the server IP and correct the destination directory. 

Windows users can use FileZilla to transfer files. 

  1. Connect to the server via SSH.

  2. Install the package for virtual environments:

sudo apt install python3.10-venv
  1. Navigate to the project directory where you transferred the files. Create a virtual environment and install the dependencies:

python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
  1. Test the bot functionality by running it:

python main.py

If everything works, proceed to the next step.

  1. Create the unit file /etc/systemd/system/telegram-bot.service:

sudo nano /etc/systemd/system/telegram-bot.service
  1. Add the following content to the file:

[Unit]
Description=Telegram Bot Service
After=network.target

[Service]
User=root
WorkingDirectory=/root/project
ExecStart=/root/proj/venv/bin/python /root/proj/main.py
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
  • WorkingDirectory — the project directory
  • ExecStart — the command to start the chatbot in the format <interpreter> <full path to the file>.

If using a virtual environment, the path to the interpreter will be as in the example. If working without venv, use /usr/local/bin/python3.

  1. Reload systemd and enable the service:

sudo systemctl daemon-reload
sudo systemctl enable telegram-bot.service
sudo systemctl start telegram-bot.service
  1. Check the status of the service and view logs if necessary:

sudo systemctl status telegram-bot.service

If the bot is running correctly, the Active field should show active (running).

View bot logs:

sudo journalctl -u telegram-bot.service -f

Manage the service with the following commands:

Restart the bot:

sudo systemctl restart telegram-bot.service

Stop the bot:

sudo systemctl stop telegram-bot.service

Remove the service (if needed):

sudo systemctl disable telegram-bot.service
sudo rm /etc/systemd/system/telegram-bot.service
sudo systemctl daemon-reload

Conclusion

Creating a Telegram chatbot in Python is a task that can be accomplished even without programming experience using bot builders. However, if you need flexibility and more options, it's better to master the aiogram framework and deploy your own project. This gives you full control over the code, the ability to enhance functionality, manage integrations, and avoid the limitations of paid plans.

To run the bot in production, simply choose an appropriate configuration on the Hostman App Platform and set up automatic deployment. Pay attention to security by storing the token in an environment variable and encrypting sensitive data. In the future, you can scale the bot, add webhook support, integrate payment systems and analytics systems, and work with ML models if AI features are required.

Python
12.03.2025
Reading time: 18 min

Similar

Python

Command-Line Option and Argument Parsing using argparse in Python

Command-line interfaces (CLIs) are one of the quickest and most effective means of interacting with software. They enable you to provide commands directly which leads to quicker execution and enhanced features. Developers often build CLIs using Python for several applications, utilities, and automation scripts, ensuring they can dynamically process user input. This is where the Python argparse module steps in. The argparse Python module streamlines the process of managing command-line inputs, enabling developers to create interactive and user-friendly utilities. As part of the standard library, it allows programmers to define, process, and validate inputs seamlessly without the need for complex logic. This article will discuss some of the most important concepts, useful examples, and advanced features of the argparse module so that you can start building solid command-line tools right away. How to Use Python argparse for Command-Line Interfaces This is how to use argparse in your Python script: Step 1: Import Module First import the module into your Python parser script: import argparse This inclusion enables parsing .py arg inputs from the command line. Step 2: Create an ArgumentParser Object The ArgumentParser class is the most minimal class of the Python argumentparser module's API. To use it, begin by creating an instance of the class: parser = argparse.ArgumentParser(description="A Hostman tutorial on Python argparse.") Here: description describes what the program does and will be displayed when someone runs --help. Step 3: Add Inputs and Options Define the parameters and features your program accepts via add_argument() function: parser.add_argument('filename', type=str, help="Name of the file to process") parser.add_argument('--verbose', action='store_true', help="Enable verbose mode") Here: filename is a mandatory option. --verbose is optional, to allow you to set the flag to make it verbose. Step 4: Parse User Inputs Process the user-provided inputs by invoking the parse_args() Python method: args = parser.parse_args() This stores the command-line values as attributes of the args object for further use in your Python script.  Step 5: Access Processed Data Access the inputs and options for further use in your program: For example: print(f"File to process: {args.filename}") if args.verbose:     print("Verbose mode enabled") else:     print("Verbose mode disabled") Example CLI Usage Here are some scenarios to run this script: File Processing Without Verbose Mode python3 file.py example.txt File Processing With Verbose Mode python3 file.py example.txt --verbose Display Help If you need to see what arguments the script accepts or their description, use the --help argument: python3 file.py --help Common Examples of argparse Usage Let's explore a few practical examples of the module. Example 1: Adding Default Values Sometimes, optional inputs in command-line interfaces need predefined values for smoother execution. With this module, you can set a default value that applies when someone doesn’t provide input. This script sets a default timeout of 30 seconds if you don’t specify the --timeout parameter. import argparse # Create the argument parser parser = argparse.ArgumentParser(description="Demonstrating default argument values.") # Pass an optional argument with a default value parser.add_argument('--timeout', type=int, default=30, help="Timeout in seconds (default: 30)") # Interpret the arguments args = parser.parse_args() # Retrieve and print the timeout value print(f"Timeout value: {args.timeout} seconds") Explanation Importing Module: Importing the argparse module. Creating the ArgumentParser Instance: An ArgumentParser object is created with a description so that a short description of the program purpose is provided. This description is displayed when the user runs the program via the --help option. Including --timeout: The --timeout option is not obligatory (indicated by the -- prefix). The type=int makes the argument for --timeout an integer. The default=30 is provided so that in case the user does not enter a value, then the timeout would be 30 seconds. The help parameter adds a description to the argument, and it will also appear in the help documentation. Parsing Process: The parse_args() function processes user inputs and makes them accessible as attributes of the args object. In our example, we access args.timeout and print out its value. Case 1: Default Value Used If the --timeout option is not specified, the default value of 30 seconds is used: python file.py Case 2: Custom Value Provided For a custom value for --timeout (e.g., 60 seconds), apply: python file.py --timeout 60 Example 2: Utilizing Choices The argparse choices parameter allows you to restrict an argument to a set of beforehand known valid values. This is useful if your program features some specific modes, options, or settings to check. Here, we will specify a --mode option with two default values: basic and advanced. import argparse # Creating argument parser parser = argparse.ArgumentParser(description="Demonstrating the use of choices in argparse.") # Adding the --mode argument with predefined choices parser.add_argument('--mode', choices=['basic', 'advanced'], help="Choose the mode of operation") # Parse the arguments args = parser.parse_args() # Access and display the selected mode if args.mode: print(f"Mode selected: {args.mode}") else: print("No mode selected. Please choose 'basic' or 'advanced'.") Adding --mode: The choices argument indicates that valid options for the --mode are basic and advanced. The application will fail when the user supplies an input other than in choices. Help Text: The help parameter gives valuable information when the --help command is executed. Case 1: Valid Input To specify a valid value for --mode, utilize: python3 file.py --mode basic Case 2: No Input Provided For running the program without specifying a mode: python3 file.py Case 3: Invalid Input If a value is provided that is not in the predefined choices: python3 file.py --mode intermediate Example 3: Handling Multiple Values The nargs option causes an argument to accept more than one input. This is useful whenever your program requires a list of values for processing, i.e., numbers, filenames, or options. Here we will show how to use nargs='+' to accept a --numbers option that can take multiple integers. import argparse # Create an ArgumentParser object parser = argparse.ArgumentParser(description="Demonstrating how to handle multiple values using argparse.") # Add the --numbers argument with nargs='+' parser.add_argument('--numbers', nargs='+', type=int, help="List of numbers to process") # Parse the arguments args = parser.parse_args() # Access and display the numbers if args.numbers: print(f"Numbers provided: {args.numbers}") print(f"Sum of numbers: {sum(args.numbers)}") else: print("No numbers provided. Please use --numbers followed by a list of integers.") Adding the --numbers Option: The user can provide a list of values as arguments for --numbers. type=int interprets the input as an integer. If a non-integer input is provided, the program raises an exception. The help parameter gives the information.  Parsing Phase: After parsing the arguments, the input to --numbers is stored in the form of a list in args.numbers. Utilizing the Input: You just need to iterate over the list, calculate statistics (e.g., sum, mean), or any other calculation on the input. Case 1: Providing Multiple Numbers To specify multiple integers for the --numbers parameter, execute: python3 file.py --numbers 10 20 30 Case 2: Providing a Single Number If just one integer is specified, run: python3 file.py --numbers 5 Case 3: No Input Provided If the script is run without --numbers: python3 file.py Case 4: Invalid Input In case of inputting a non-integer value: python3 file.py --numbers 10 abc 20 Example 4: Required Optional Arguments Optional arguments (those that begin with the --) are not mandatory by default. But there are times when you would like them to be mandatory for your script to work properly. You can achieve this by passing the required=True parameter when defining the argument. In this script, --config specifies a path to a configuration file. By leveraging required=True, the script enforces that a value for --config must be provided. If omitted, the program will throw an error. import argparse # Create an ArgumentParser object parser = argparse.ArgumentParser(description="Demonstrating required optional arguments in argparse.") # Add the --config argument parser.add_argument('--config', required=True, help="Path to the configuration file") # Parse the arguments args = parser.parse_args() # Access and display the provided configuration file path print(f"Configuration file path: {args.config}") Adding the --config Option: --config is considered optional since it starts with --. However, thanks to the required=True parameter, users must include it when they run the script. The help parameter clarifies what this parameter does, and you'll see this information in the help message when you use --help. Parsing: The parse_args() method takes care of processing the arguments. If someone forgets to include --config, the program will stop and show a clear error message. Accessing the Input: The value you provide for --config gets stored in args.config. You can then use this in your script to work with the configuration file. Case 1: Valid Input For providing a valid path to the configuration file, use: python3 file.py --config settings.json Case 2: Missing the Required Argument For running the script without specifying --config, apply: python3 file.py Advanced Features  While argparse excels at handling basic command-line arguments, it also provides advanced features that enhance the functionality and usability of your CLIs. These features ensure your scripts are scalable, readable, and easy to maintain. Below are some advanced capabilities you can leverage. Handling Boolean Flags Boolean flags allow toggling features (on/off) without requiring user input. Use the action='store_true' or action='store_false' parameters to implement these flags. parser.add_argument('--debug', action='store_true', help="Enable debugging mode") Including --debug enables debugging mode, useful for many Python argparse examples. Grouping Related Arguments Use add_argument_group() to organize related arguments, improving readability in complex CLIs. group = parser.add_argument_group('File Operations') group.add_argument('--input', type=str, help="Input file") group.add_argument('--output', type=str, help="Output file") Grouped arguments appear under their own section in the --help documentation. Mutually Exclusive Arguments To ensure users select only one of several conflicting options, use the add_mutually_exclusive_group() method. group = parser.add_mutually_exclusive_group() group.add_argument('--json', action='store_true', help="Output in JSON format") group.add_argument('--xml', action='store_true', help="Output in XML format") This ensures one can choose either JSON or XML, but not both. Conclusion The argparse Python module simplifies creating reliable CLIs for handling Python program command line arguments. From the most basic option of just providing an input to more complex ones like setting choices and nargs, developers can build user-friendly and robust CLIs. Following the best practices of giving proper names to arguments and writing good docstrings would help you in making your scripts user-friendly and easier to maintain.
21 July 2025 · 10 min to read
Python

How to Get the Length of a List in Python

Lists in Python are used almost everywhere. In this tutorial we will look at four ways to find the length of a Python list: by using built‑in functions, recursion, and a loop. Knowing the length of a list is most often required to iterate through it and perform various operations on it. len() function len() is a built‑in Python function for finding the length of a list. It takes one argument—the list itself—and returns an integer equal to the list’s length. The same function also works with other iterable objects, such as strings. Country_list = ["The United States of America", "Cyprus", "Netherlands", "Germany"] count = len(Country_list) print("There are", count, "countries") Output: There are 4 countries Finding the Length of a List with a Loop You can determine a list’s length in Python with a for loop. The idea is to traverse the entire list while incrementing a counter by  1 on each iteration. Let’s wrap this in a separate function: def list_length(list): counter = 0 for i in list: counter = counter + 1 return counter Country_list = ["The United States of America", "Cyprus", "Netherlands", "Germany", "Japan"] count = list_length(Country_list) print("There are", count, "countries") Output: There are 5 countries Finding the Length of a List with Recursion The same task can be solved with recursion: def list_length_recursive(list): if not list: return 0 return 1 + list_length_recursive(list[1:]) Country_list = ["The United States of America", "Cyprus", "Netherlands","Germany", "Japan", "Poland"] count = list_length_recursive(Country_list) print("There are", count, "countries") Output: There are 6 countries How it works. The function list_length_recursive() receives a list as input. If the list is empty, it returns 0—the length of an empty list. Otherwise it calls itself recursively with the argument list[1:], a slice of the original list starting from index 1 (i.e., the list without the element at index 0). The result of that call is added to 1. With each recursive step the returned value grows by one while the list shrinks by one element. length_hint() function The length_hint() function lives in the operator module. That module contains functions analogous to Python’s internal operators: addition, subtraction, comparison, and so on. length_hint() returns the length of iterable objects such as strings, tuples, dictionaries, and lists. It works similarly to len(): from operator import length_hint Country_list = ["The United States of America", "Cyprus", "Netherlands","Germany", "Japan", "Poland", "Sweden"] count = length_hint(Country_list) print("There are", count, "countries") Output: There are 7 countries Note that length_hint() must be imported before use. Conclusion In this guide we covered four ways to determine the length of a list in Python. Under equal conditions the most efficient method is len(). The other approaches are justified mainly when you are implementing custom classes similar to list.
17 July 2025 · 3 min to read
Python

Understanding the main() Function in Python

In any complex program, it’s crucial to organize the code properly: define a starting point and separate its logical components. In Python, modules can be executed on their own or imported into other modules, so a well‑designed program must detect the execution context and adjust its behavior accordingly.  Separating run‑time code from import‑time code prevents premature execution, and having a single entry point makes it easier to configure launch parameters, pass command‑line arguments, and set up tests. When all important logic is gathered in one place, adding automated tests and rolling out new features becomes much more convenient.  For exactly these reasons it is common in Python to create a dedicated function that is called only when the script is run directly. Thanks to it, the code stays clean, modular, and controllable. That function, usually named main(), is the focus of this article. All examples were executed with Python 3.10.12 on a Hostman cloud server running Ubuntu 22.04. Each script was placed in a separate .py file (e.g., script.py) and started with: python script.py The scripts are written so they can be run just as easily in any online Python compiler for quick demonstrations. What Is the main() Function in Python The simplest Python code might look like: print("Hello, world!")  # direct execution Or a script might execute statements in sequence at file level: print("Hello, world!")       # action #1 print("How are you, world?") # action #2 print("Good‑bye, world...")  # action #3 That trivial arrangement works only for the simplest scripts. As a program grows, the logic quickly becomes tangled and demands re‑organization: # function containing the program’s main logic (entry point) def main():     print("Hello, world!") # launch the main logic if __name__ == "__main__":     main()                    # call the function with the main logic With more actions the code might look like: def main(): print("Hello, world!") print("How are you, world?") print("Good‑bye, world...") if __name__ == "__main__": main() This implementation has several important aspects, discussed below. The main() Function The core program logic lives inside a separate function. Although the name can be anything, developers usually choose main, mirroring C, C++, Java, and other languages.  Both helper code and the main logic are encapsulated: nothing sits “naked” at file scope. # greeting helper def greet(name): print(f"Hello, {name}!") # program logic def main(): name = input("Enter your name: ") greet(name) # launch the program if __name__ == "__main__": main() Thus main() acts as the entry point just as in many other languages. The if __name__ == "__main__" Check Before calling main() comes the somewhat odd construct if __name__ == "__main__":.  Its purpose is to split running from importing logic: If the script runs directly, the code inside the if block executes. If the script is imported, the block is skipped. Inside that block, you can put any code—not only the main() call: if __name__ == "__main__":     print("Any code can live here, not only main()") __name__ is one of Python’s built‑in “dunder” (double‑underscore) variables, often called magic or special. All dunder objects are defined and used internally by Python, but regular users can read them too. Depending on the context, __name__ holds: "__main__" when the module runs as a standalone script. The module’s own name when it is imported elsewhere. This lets a module discover its execution context. Advantages of Using  main() Organization Helper functions and classes, as well as the main function, are wrapped separately, making them easy to find and read. Global code is minimal—only initialization stays at file scope: def process_data(data): return [d * 2 for d in data] def main(): raw = [1, 2, 3, 4] result = process_data(raw) print("Result:", result) if __name__ == "__main__": main() A consistent style means no data manipulation happens at the file level. Even in a large script you can quickly locate the start of execution and any auxiliary sections. Isolation When code is written directly at the module level, every temporary variable, file handle, or connection lives in the global namespace, which can be painful for debugging and testing. Importing such a module pollutes the importer’s globals: # executes immediately on import values = [2, 4, 6] doubles = [] for v in values: doubles.append(v * 2) print("Doubled values:", doubles) With main() everything is local; when the function returns, its variables vanish: def double_list(items): return [x * 2 for x in items] # create a new list with doubled elements def main(): values = [2, 4, 6] result = double_list(values) print("Doubled values:", result) if __name__ == "__main__": main() That’s invaluable for unit testing, where you might run specific functions (including  main()) without triggering the whole program. Safety Without the __name__ check, top‑level code runs even on import—usually undesirable and potentially harmful. some.py: print("This code will execute even on import!") def useful_function(): return 42 main.py: import some print("The logic of the imported module executed itself...") Console: This code will execute even on import! The logic of the imported module executed itself... The safer some.py: def useful_function():     return 42 def main():     print("This code will not run on import") main() plus the __name__ check guard against accidental execution. Inside main() you can also verify user permissions or environment variables. How to Write main() in Python Remember: main() is not a language construct, just a regular function promoted to “entry point.” To ensure it runs only when the script starts directly: Tools – define helper functions with business logic. Logic – assemble them inside main() in the desired order. Check – add the if __name__ == "__main__" guard.  This template yields structured, import‑safe, test‑friendly code—excellent practice for any sizable Python project. Example Python Program Using main() # import the standard counter from collections import Counter # runs no matter how the program starts print("The text‑analysis program is active") # text‑analysis helper def analyze_text(text): words = text.split() # split text into words total = len(words) # total word count unique = len(set(words)) # unique word count avg_len = sum(len(w) for w in words) / total if total else 0 freq = Counter(words) # build frequency counter top3 = freq.most_common(3) # top three words return { 'total': total, 'unique': unique, 'avg_len': avg_len, 'top3': top3 } # program’s main logic def main(): print("Enter text (multiple lines). Press Enter on an empty line to finish:") lines = [] while True: line = input() if not line: break lines.append(line) text = ' '.join(lines) stats = analyze_text(text) print(f"\nTotal number of words: {stats['total']}") print(f"Unique words: {stats['unique']}") print(f"Average word length: {stats['avg_len']:.2f}") print("Top‑3 most frequent words:") for word, count in stats['top3']: print(f" {word!r}: {count} time(s)") # launch program if __name__ == "__main__": main() Running the script prints a prompt: Enter text (multiple lines). Press Enter on an empty line to finish: Input first line: Star cruiser Orion glided silently through the darkness of intergalactic space. Second line: Signals of unknown life‑forms flashed on the onboard sensors where the nebula glowed with a phosphorescent light. Third line: The cruiser checked the sensors, then the cruiser activated the defense system, and the cruiser returned to its course. Console output: The text‑analysis program is active Total number of words: 47 Unique words: 37 Average word length: 5.68 Top‑3 most frequent words: 'the': 7 time(s) 'cruiser': 4 time(s) 'of': 2 time(s) If you import this program (file program.py) elsewhere: import program         # importing program.py Only the code outside main() runs: The text‑analysis program is active So, a moderately complex text‑analysis utility achieves clear logic separation and context detection. When to Use main() and When Not To Use  main() (almost always appropriate) when: Medium/large scripts – significant code with non‑trivial logic, multiple functions/classes. Libraries or CLI utilities – you want parts of the module importable without side effects. Autotests – you need to test pure logic without extra boilerplate. You can skip main() when: Tiny one‑off scripts – trivial logic for a quick data tweak. Educational snippets – short examples illustrating a few syntax features. In short, if your Python program is a standalone utility or app with multiple processing stages, command‑line arguments, and external resources—introduce  main(). If it’s a small throw‑away script, omitting main() keeps things concise. Conclusion The  main() function in Python serves two critical purposes: Isolates the program’s core logic from the global namespace. Separates standalone‑execution logic from import logic. Thus, a Python file evolves from a straightforward script of sequential actions into a fully‑fledged program with an entry point, encapsulated logic, and the ability to detect its runtime environment.
14 July 2025 · 8 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support