15 Python Projects for Beginners with Source Code

Created with Sketch.

Project 1: Hello World Program:

  • Writing your first Python program.
  • Understanding the “Hello World” tradition.
# Hello World Program
print("Hello, World!")

Project 2: Simple Calculator:

  • Creating a basic calculator using user input.
  • Implementing addition, subtraction, multiplication, and division.
# Simple Calculator
def calculator():
    num1 = float(input("Enter first number: "))
    operator = input("Enter operator (+, -, *, /): ")
    num2 = float(input("Enter second number: "))

    if operator == '+':
        result = num1 + num2
    elif operator == '-':
        result = num1 - num2
    elif operator == '*':
        result = num1 * num2
    elif operator == '/':
        result = num1 / num2
    else:
        result = "Invalid operator"

    print(f"Result: {result}")

calculator()

Project 3: To-Do List Application:

  • Building a simple to-do list with basic CRUD operations.
  • Understanding data storage using lists.
# To-Do List Application
tasks = []

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

def view_tasks():
    print("Tasks:")
    for task in tasks:
        print(task)

def remove_task(task):
    if task in tasks:
        tasks.remove(task)
        print(f"Task '{task}' removed.")
    else:
        print(f"Task '{task}' not found.")

# Example usage
add_task("Read a book")
add_task("Write code")
view_tasks()
remove_task("Read a book")
view_tasks()

Project 4: Web Scraping with BeautifulSoup:

  • Introduction to web scraping.
  • Extracting data from a website using BeautifulSoup.
# Web Scraping with BeautifulSoup
import requests
from bs4 import BeautifulSoup

url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Extracting and printing page title
title = soup.title.string
print(f"Page Title: {title}")

Project 5: Password Generator:

  • Creating a password generator with customizable parameters.
  • Utilizing the secrets module for secure randomization.
# Password Generator
import secrets
import string

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

# Example usage
generated_password = generate_password()
print(f"Generated Password: {generated_password}")

Project 6: Basic Chatbot:

  • Building a simple chatbot using conditional statements.
  • Responding to user input with predefined messages.
# Basic Chatbot
def simple_chatbot(user_input):
    greetings = ["hello", "hi", "hey"]
    farewells = ["bye", "goodbye", "see you"]

    if user_input.lower() in greetings:
        return "Hello! How can I assist you?"
    elif user_input.lower() in farewells:
        return "Goodbye! Have a great day."
    else:
        return "I'm just a basic chatbot. I respond to greetings and farewells."

# Example usage
user_input = input("User: ")
bot_response = simple_chatbot(user_input)
print(f"Bot: {bot_response}")

Project 7: Number Guessing Game:

  • Implementing a classic number guessing game.
  • Incorporating user input, randomization, and loops.
# Number Guessing Game
import random

def number_guessing_game():
    target_number = random.randint(1, 100)
    attempts = 0

    while True:
        user_guess = int(input("Enter your guess (1-100): "))
        attempts += 1

        if user_guess == target_number:
            print(f"Congratulations! You guessed the correct number in {attempts} attempts.")
            break
        elif user_guess < target_number:
            print("Try higher.")
        else:
            print("Try lower.")

# Example usage
number_guessing_game()

Project 8: Dice Rolling Simulator:

  • Simulating the roll of a six-sided die.
  • Generating random numbers and simulating dice rolls.
# Dice Rolling Simulator
import random

def roll_dice():
    return random.randint(1, 6)

# Example usage
result = roll_dice()
print(f"The die shows: {result}")

Project 9: Currency Converter:

  • Creating a basic currency converter.
  • Using exchange rates for conversion calculations.
# Currency Converter
def currency_converter(amount, exchange_rate):
    converted_amount = amount * exchange_rate
    return converted_amount

# Example usage
usd_amount = float(input("Enter amount in USD: "))
exchange_rate_eur = 0.85  # Example exchange rate (USD to EUR)
eur_amount = currency_converter(usd_amount, exchange_rate_eur)
print(f"{usd_amount} USD is approximately {eur_amount} EUR")

Project 10: URL Shortener:

  • Building a URL shortener using a dictionary for mapping.
  • Generating short URLs for long input URLs.
# URL Shortener
url_mapping = {}

def shorten_url(original_url):
    short_url = ''.join(random.choice(string.ascii_letters) for _ in range(6))
    url_mapping[short_url] = original_url
    return short_url

# Example usage
original_url = input("Enter the original URL: ")
shortened_url = shorten_url(original_url)
print(f"Shortened URL: {shortened_url}")

Project 11: Rock, Paper, Scissors Game:

  • Implementing a classic rock, paper, scissors game.
  • Accepting user input and simulating computer moves.
# Rock, Paper, Scissors Game
import random

def play_rps(user_choice):
    choices = ['rock', 'paper', 'scissors']
    computer_choice = random.choice(choices)

    if user_choice.lower() not in choices:
        return "Invalid choice. Please choose rock, paper, or scissors."

    if user_choice.lower() == computer_choice:
        return f"It's a tie! Both chose {user_choice}."

    if (
        (user_choice.lower() == 'rock' and computer_choice == 'scissors') or
        (user_choice.lower() == 'paper' and computer_choice == 'rock') or
        (user_choice.lower() == 'scissors' and computer_choice == 'paper')
    ):
        return f"You win! {user_choice} beats {computer_choice}."
    else:
        return f"You lose! {computer_choice} beats {user_choice}."

# Example usage
user_choice = input("Enter your choice (rock, paper, or scissors): ")
result = play_rps(user_choice)
print(result)

Project 12: Weather App:

  • Building a simple weather app using an API.
  • Making API requests and displaying weather information.
# Weather App
import requests

def get_weather(city):
    api_key = "your_api_key"  # Replace with a valid API key
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {'q': city, 'appid': api_key}

    response = requests.get(base_url, params=params)
    weather_data = response.json()

    if response.status_code == 200:
        temperature = weather_data['main']['temp']
        description = weather_data['weather'][0]['description']
        return f"Weather in {city}: {temperature}°C, {description.capitalize()}."
    else:
        return f"Error: Unable to fetch weather data for {city}."

# Example usage
city_name = input("Enter city name: ")
weather_info = get_weather(city_name)
print(weather_info)

Project 13: Basic Web Application with Flask:

  • Introduction to web development with Flask.
  • Creating a minimal web application.
# Basic Flask Web Application
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to my Flask Web App!'

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

Project 14: Alarm Clock:

  • Developing a simple alarm clock with user-settable alarms.
  • Utilizing the time module for scheduling.
# Alarm Clock
import time

def set_alarm(hour, minute):
    alarm_time = f"{hour:02d}:{minute:02d}"
    current_time = time.strftime("%H:%M")

    while current_time != alarm_time:
        current_time = time.strftime("%H:%M")
        time.sleep(1)

    print("Alarm! Wake up!")

# Example usage
alarm_hour = int(input("Enter alarm hour (24-hour format): "))
alarm_minute = int(input("Enter alarm minute: "))
set_alarm(alarm_hour, alarm_minute)

Project 15: Basic File Explorer:

  • Building a basic file explorer with file listing and navigation.
  • Using the os module for file operations.
# Basic File Explorer
import os

def list_files(directory='.'):
    print(f"Files in {directory}:")
    for file in os.listdir(directory):
        print(file)

# Example usage
directory_path = input("Enter directory path (Press Enter for current directory): ")
list_files(directory_path)

Leave a Reply

Your email address will not be published. Required fields are marked *