25 python program you must try

Basic Programs:

1. Hello world

print("Hello, World!")

2. Calculator

def calculator():
    num1 = float(input("Enter first number: "))
    op = input("Enter operator (+, -, *, /): ")
    num2 = float(input("Enter second number: "))

    if op == '+':
        print(num1 + num2)
    elif op == '-':
        print(num1 - num2)
    elif op == '*':
        print(num1 * num2)
    elif op == '/':
        if num2 != 0:
            print(num1 / num2)
        else:
            print("Error: Division by zero")
    else:
        print("Invalid operator")

calculator()

3. Palindrome Checker

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

print(is_palindrome("A man a plan a canal Panama"))

4. Factorial Calculator

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))

5. Prime Number Generator

def generate_primes(limit):
    primes = []
    for num in range(2, limit + 1):
        is_prime = True
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(num)
    return primes

print(generate_primes(20))

6. Fibonacci Sequence

def fibonacci(n):
    fib = [0, 1]
    for i in range(2, n):
        fib.append(fib[-1] + fib[-2])
    return fib[:n]

print(fibonacci(10))

7. Number Guessing Game

import random

def guessing_game():
    number = random.randint(1, 100)
    guess = None
    attempts = 0

    while guess != number:
        guess = int(input("Guess a number between 1 and 100: "))
        attempts += 1
        if guess < number:
            print("Too low!")
        elif guess > number:
            print("Too high!")

    print(f"Congratulations! You guessed the number {number} in {attempts} attempts.")

guessing_game()

8. Rock Paper Scissors Game

def rock_paper_scissors(player_choice):
    import random
    choices = ['rock', 'paper', 'scissors']
    computer_choice = random.choice(choices)

    if player_choice == computer_choice:
        return "It's a tie!"
    elif (player_choice == 'rock' and computer_choice == 'scissors') or \
         (player_choice == 'paper' and computer_choice == 'rock') or \
         (player_choice == 'scissors' and computer_choice == 'paper'):
        return "You win!"
    else:
        return "Computer wins!"

print(rock_paper_scissors('rock'))

9. Temperature Converter

def celsius_to_fahrenheit(celsius):
    return celsius * 9/5 + 32

def fahrenheit_to_celsius(fahrenheit):
    return (fahrenheit - 32) * 5/9

print(celsius_to_fahrenheit(25))
print(fahrenheit_to_celsius(77))

10. Simple Todo List

class TodoList:
    def __init__(self):
        self.tasks = []

    def add_task(self, task):
        self.tasks.append(task)

    def view_tasks(self):
        for index, task in enumerate(self.tasks, start=1):
            print(f"{index}. {task}")

todo = TodoList()
todo.add_task("Do laundry")
todo.add_task("Buy groceries")
todo.view_tasks()

Intermediate Programs:

11. File Reader/Writer

# Reading a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

# Writing to a file
with open("output.txt", "w") as file:
    file.write("Hello, World!")

12. Word Counter

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

print(word_counter("example.txt"))

13. Web Scraper


import requests
from bs4 import BeautifulSoup

def scrape_website(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    # Example: Extract all links
    links = [link.get('href') for link in soup.find_all('a')]
    return links

print(scrape_website("https://example.com"))

14. URL Shortener

import pyshorteners

def shorten_url(url):
    s = pyshorteners.Shortener()
    return s.tinyurl.short(url)

print(shorten_url("https://example.com"))

15. RSS Feed Reader

import feedparser

def read_feed(url):
    feed = feedparser.parse(url)
    for entry in feed.entries:
        print(entry.title)

read_feed("https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml")

16. Chatbot

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('MyBot')
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('chatterbot.corpus.english')

response = chatbot.get_response("Hello, how are you?")
print(response)

17. Image Downloader

import requests

def download_image(url, filename):
    response = requests.get(url)
    with open(filename, 'wb') as file:
        file.write(response.content)
    print(f"Downloaded {filename}")

download_image("https://example.com/image.jpg", "image.jpg")

18. Currency Converter

from forex_python.converter import CurrencyRates

def convert_currency(amount, from_currency, to_currency):
    c = CurrencyRates()
    return c.convert(from_currency, to_currency, amount)

print(convert_currency(100, 'USD', 'EUR'))

19. Regex Tester

import re

def match_pattern(pattern, text):
    matches = re.findall(pattern, text)
    return matches

pattern = r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b'
text = "Contact us at support@example.com"
print(match_pattern(pattern, text))

20. Password Generator

import random
import string

def generate_password(length=12):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

print(generate_password())

21. Machine Learning Model

from sklearn.linear_model import LinearRegression
import numpy as np

X = np.array([[1], [2], [3]])
y = np.array([3, 5, 7])

model = LinearRegression()
model.fit(X, y)

print(model.predict([[4]]))

22. Web Framework Application

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)

23. Sentiment Analysis

from textblob import TextBlob

def analyze_sentiment(text):
    analysis = TextBlob(text)
    return analysis.sentiment

print(analyze_sentiment("I love Python"))

24. OCR (Optical Character Recognition)

from PIL import Image
import pytesseract

def ocr_image(image_path):
    img = Image.open(image_path)
    text = pytesseract.image_to_string(img)
    return text

print(ocr_image("image.jpg"))

25. Data Visualization

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Sine Wave')
plt.show()

500+ Free Google Certificate Courses

Leave a Comment