Featured Post

Python Regex: The 5 Exclusive Examples

 Regular expressions (regex) are powerful tools for pattern matching and text manipulation in Python. Here are five Python regex examples with explanations: 01 Matching a Simple Pattern import re text = "Hello, World!" pattern = r"Hello" result = re.search(pattern, text) if result:     print("Pattern found:", result.group()) Output: Output: Pattern found: Hello This example searches for the pattern "Hello" in the text and prints it when found. 02 Matching Multiple Patterns import re text = "The quick brown fox jumps over the lazy dog." patterns = [r"fox", r"dog"] for pattern in patterns:     if re.search(pattern, text):         print(f"Pattern '{pattern}' found.") Output: Pattern 'fox' found. Pattern 'dog' found. It searches for both "fox" and "dog" patterns in the text and prints when they are found. 03 Matching Any Digit   import re text = "The price of the

10 Exclusive Python Projects for Interviews

Here are ten Python projects along with code and possible solutions for your practice.

10 top projects

01. Palindrome Checker:

Description: Write a function that checks if a given string is a palindrome (reads the same backward as forward).

def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

# Test the function
print(is_palindrome("radar"))  # Output: True
print(is_palindrome("hello"))  # Output: False

02. Word Frequency Counter:

Description: Create a program that takes a text file as input and counts the frequency of each word in the file.

def word_frequency(file_path):
    with open(file_path, 'r') as file:
        text = file.read().lower()
        words = text.split()
        word_count = {}
        for word in words:
            word_count[word] = word_count.get(word, 0) + 1
    return word_count

# Test the function
file_path = 'sample.txt'
word_count = word_frequency(file_path)

03. Guess the Number Game:

Description: Develop a simple game where the computer randomly generates a number, and the user tries to guess it.

import random

def guess_the_number():
    target_number = random.randint(1, 100)
    attempts = 0
    while True:
        guess = int(input("Guess the number (1-100): "))
        attempts += 1
        if guess == target_number:
            print(f"Congratulations! You guessed the number in {attempts} attempts.")
        elif guess < target_number:
            print("Try a higher number.")
            print("Try a lower number.")

# Test the game

04. Contact Book:

Description: Build a contact management application that allows users to add, view, search, and delete contacts.

class ContactBook:
    def __init__(self):
        self.contacts = {}
    def add_contact(self, name, phone):
        self.contacts[name] = phone
    def view_contacts(self):
        for name, phone in self.contacts.items():
            print(f"{name}: {phone}")
    def search_contact(self, name):
        if name in self.contacts:
            return self.contacts[name]
            return "Contact not found."
    def delete_contact(self, name):
        if name in self.contacts:
            del self.contacts[name]
            print(f"{name} has been deleted from contacts.")
            print(f"{name} not found in contacts.")

# Test the ContactBook class
contacts = ContactBook()
contacts.add_contact("John", "1234567890")
contacts.add_contact("Alice", "9876543210")

05. File Encryption/Decryption:

Description: Create a program that encrypts and decrypts a file using a simple encryption algorithm.

def encrypt_file(file_path):
    with open(file_path, 'r') as file:
        text = file.read()
        encrypted_text = ''.join(chr(ord(c) + 1) for c in text)
    with open(f'{file_path}.enc', 'w') as encrypted_file:

def decrypt_file(encrypted_file_path):
    with open(encrypted_file_path, 'r') as encrypted_file:
        encrypted_text = encrypted_file.read()
        decrypted_text = ''.join(chr(ord(c) - 1) for c in encrypted_text)
    with open(f'{encrypted_file_path[:-4]}.dec', 'w') as decrypted_file:

# Test the encryption and decryption functions
file_path = 'data.txt'

06. Web Scraping and Data Visualization:

Description: Write a script that scrapes data from a website and creates visualizations using libraries like Matplotlib.
(Note: This project may require you to select a specific website for scraping and installing necessary libraries.)

# Example web scraping with BeautifulSoup:
import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# ... extract data from the website and create visualizations with Matplotlib or other libraries.

07. Rock, Paper, Scissors Game:

Description: Develop a command-line game where the user plays against the computer in the classic rock-paper-scissors.

import random

def rock_paper_scissors():
    choices = ["rock", "paper", "scissors"]
    computer_choice = random.choice(choices)
    user_choice = input("Enter your choice (rock/paper/scissors): ").lower()
    if user_choice not in choices:
        print("Invalid choice.")
        print(f"Computer chose: {computer_choice}")
        if user_choice == computer_choice:
            print("It's a tie!")
        elif (
            (user_choice == "rock" and computer_choice == "scissors") or
            (user_choice == "paper" and computer_choice == "rock") or
            (user_choice == "scissors" and computer_choice == "paper")
            print("You win!")
            print("Computer wins!")

# Test the game

08. Weather Forecast Telegram Bot:

Description: Build a Telegram bot that provides weather forecasts for a given location using an API.
(Note: This project may require you to create a Telegram bot and obtain an API key for weather data.)

# Example Telegram bot using the 'python-telegram-bot' library:
from telegram import Update
from telegram.ext import Updater, CommandHandler

def start(update: Update, _) -> None:
    update.message.reply_text("Hello! I am your Weather Forecast Bot.")

def weather(update: Update, _) -> None:
    location = update.message.text.split()[1]
    # Fetch weather data using API and send the forecast back to the user.
    update.message.reply_text(f"Weather forecast for {location}: ...")

# Set up the bot and handlers
updater = Updater("YOUR_TELEGRAM_BOT_TOKEN", use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("weather", weather))

# Start the bot

09. URL Status Checker:

Description: Create a script that checks the status codes of a list of URLs to identify broken or inaccessible links.

import requests

def check_url_status(url_list):
    for url in url_list:
            response = requests.head(url)
            status_code = response.status_code
            if status_code == 200:
                print(f"{url} is accessible.")
                print(f"{url} is not accessible. Status code: {status_code}")
        except requests.exceptions.RequestException:
            print(f"{url} is not accessible.")

# Test the function
urls = ["https://example.com", "https://google.com", "https://nonexistent.com"]

10. Currency Exchange Rate Calculator:

Description: Write a program that fetches exchange rates from an API and calculates currency conversions.
(Note: This project may require you to choose a specific currency exchange rate API.)

import requests

def get_exchange_rate(base_currency, target_currency):
    url = f'https://api.example.com/rates?base={base_currency}&symbols={target_currency}'
    response = requests.get(url)
    data = response.json()
    return data['rates'][target_currency]

def currency_converter(amount, base_currency, target_currency):
    exchange_rate = get_exchange_rate(base_currency, target_currency)
    converted_amount = amount * exchange_rate
    return converted_amount

# Test the currency_converter function
amount = 100
base_currency = 'USD'
target_currency = 'EUR'
converted_amount = currency_converter(amount, base_currency, target_currency)
print(f"{amount} {base_currency} is equal to {converted_amount:.2f} {target_currency}")

Remember to install any required libraries (e.g., BeautifulSoup, python-telegram-bot) using pip before running the scripts. Happy coding!


Popular posts from this blog

Explained Ideal Structure of Python Class

6 Python file Methods Real Usage

How to Decode TLV Quickly