Free Python Projects With Source Code
Hello Friends, Are you looking for Free Python projects with source code for Beginners to Advance to enhance your coding skills, from beginner-level tasks to advanced challenges? Look no further! In this comprehensive guide, we've compiled a wide range of Python project ideas and source code examples to help you on your programming journey. Here you can Unlock the Power of Python Programming. These projects cater to both beginners and those seeking more advanced challenges.
Python Projects with Source Code for Beginners
Number Guessing Game
The classic Number Guessing Game is a perfect introduction to Python. Create a simple program that generates a random number, prompts the user to guess it, and provides hints until they get it right.
import random
def number_guessing_game():
number_to_guess = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess the number: "))
attempts += 1
if guess == number_to_guess:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
elif guess < number_to_guess:
print("Try a higher number.")
else:
print("Try a lower number.")
number_guessing_game()
Group Anagrams using Python
Anagrams are words or phrases formed by rearranging the letters of another word or phrase. Create a Python program that groups anagrams from a list of words.
def group_anagrams(words):
anagrams = {}
for word in words:
sorted_word = "".join(sorted(word))
if sorted_word in anagrams:
anagrams[sorted_word].append(word)
else:
anagrams[sorted_word] = [word]
return list(anagrams.values())
words = ["listen", "silent", "hello", "world"]
anagram_groups = group_anagrams(words)
print(anagram_groups)
Find Missing Number
Write a Python function to find the missing number in an array of consecutive numbers.
def find_missing_number(nums):
n = len(nums) + 1
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
numbers = [1, 2, 4, 5]
missing_number = find_missing_number(numbers)
print(f"The missing number is {missing_number}")
Calculate Mean, Median, and Mode using Python
Calculate the mean, median, and mode of a list of numbers using Python.
import statistics
data = [1, 2, 3, 4, 5, 4, 3, 2, 3, 4]
mean = statistics.mean(data)
median = statistics.median(data)
mode = statistics.mode(data)
print(f"Mean: {mean}, Median: {median}, Mode: {mode}")
Calculate Execution Time of a Python Program
Learn to measure the execution time of a Python program or a specific function using the time module.
import time
start_time = time.time()
# Your code here
end_time = time.time()
execution_time = end_time - start_time
print(f"Execution time: {execution_time} seconds")
Count Number of Words in a Column
Create a Python script to count the number of words in a specific column of a text file or dataset.
def count_words_in_column(filename, column_index):
word_count = 0
with open(filename, 'r') as file:
for line in file:
words = line.strip().split()
if column_index < len(words):
word_count += len(words[column_index].split())
return word_count
filename = 'sample.txt'
column_index = 2
count = count_words_in_column(filename, column_index)
print(f"Total words in column {column_index}: {count}")
Print Emojis using Python
Enhance your Python skills by creating a program that prints emojis based on user input.
def print_emoji(emoji):
print(emoji)
emoji_input = input("Enter an emoji: ")
print_emoji(emoji_input)
Correct Spellings using Python
Use Python to create a simple spell-checker that corrects common spelling mistakes in text.
import spellchecker
def correct_spelling(text):
checker = spellchecker.SpellChecker()
words = text.split()
for word in words:
corrected_word = checker.correction(word)
text = text.replace(word, corrected_word)
return text
input_text = "Ths is sme text with mistaks."
corrected_text = correct_spelling(input_text)
print(corrected_text)
Intermediate Python Projects with Source Code
Scraping Github Profile using Python
Learn web scraping by extracting data from GitHub profiles, such as the number of repositories, followers, and contributions.
import requests
from bs4 import BeautifulSoup
def scrape_github_profile(username):
url = f"https://github.com/{username}"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
repo_count = soup.find_all('span', class_='Counter')[0].text.strip()
followers = soup.find_all('span', class_='Counter')[1].text.strip()
contributions = soup.find('h2', class_='f4 text-normal mb-2').text.strip()
print(f"Repositories: {repo_count}")
print(f"Followers: {followers}")
print(f"Contributions: {contributions}")
github_username = "your_username"
scrape_github_profile(github_username)
Visualize Linear Relationships using Python
Learn data visualization by creating scatter plots to visualize linear relationships between variables using libraries like Matplotlib or Seaborn.
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50)
y = 2 * x + 1 + np.random.rand(50) * 0.5
plt.scatter(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Linear Relationship')
plt.show()
Generate Text using Python
Create a Python program that generates random text based on specific patterns or templates.
import random
def generate_text():
templates = ["Hello, my name is [Name].", "I enjoy [Hobby] in my free time.", "[Animal] is my favorite animal."]
text = ""
for template in templates:
if '[' in template:
start = template.index('[')
end = template.index(']') + 1
variable = template[start:end]
choices = variable[1:-1].split('|')
selected_choice = random.choice(choices)
text += template[:start] + selected_choice + template[end:]
else:
text += template
return text
generated_text = generate_text()
print(generated_text)
Scrape Table From a Website using Python
Practice web scraping by extracting tabular data from a website and storing it in a structured format like a CSV file.
import requests
import pandas as pd
def scrape_table_to_csv(url, csv_filename):
response = requests.get(url)
tables = pd.read_html(response.text)
df = tables[0]
df.to_csv(csv_filename, index=False)
website_url = "https://example.com/data-table"
csv_filename = "data.csv"
scrape_table_to_csv(website_url, csv_filename)
Extract Text From PDF using Python
Learn how to extract text from PDF files using libraries like PyPDF2 or pdfminer.
import PyPDF2
def extract_text_from_pdf(pdf_file):
text = ""
pdf = PyPDF2.PdfFileReader(open(pdf_file, 'rb'))
for page in range(pdf.numPages):
text += pdf.getPage(page).extractText()
return text
pdf_file = "sample.pdf"
text = extract_text_from_pdf(pdf_file)
print(text)
Reversing a String using Python
Create a Python function that reverses a string.
def reverse_string(input_string):
return input_string[::-1]
string_to_reverse = "Hello, world!"
reversed_string = reverse_string(string_to_reverse)
print(reversed_string)
Match Sequences using Python
Write a Python program that matches sequences of characters using regular expressions.
import re
def match_sequences(text, pattern):
matches = re.findall(pattern, text)
return matches
text = "Python is fun! Pythagoras was a famous mathematician."
pattern = "Py[a-z]+"
result = match_sequences(text, pattern)
print(result)
QR Code using Python
Generate QR codes from text or URLs using libraries like qrcode.
import qrcode
def generate_qr_code(data, filename):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.save(filename)
data = "https://www.example.com"
qr_code_filename = "example_qr.png"
generate_qr_code(data, qr_code_filename)
Decode a QR Code using Python
Enhance your Python skills by creating a program that decodes QR codes and extracts data from them.
import qrcode
from pyzbar.pyzbar import decode
def decode_qr_code(image_filename):
image = qrcode.make(image_filename)
decoded = decode(image)
if decoded:
return decoded[0].data.decode('utf-8')
else:
return "No QR code found."
image_filename = "example_qr.png"
result = decode_qr_code(image_filename)
print(result)
Creating Dummy Data using Python
Generate dummy data for testing and prototyping purposes using libraries like Faker or Random.
from faker import Faker
def generate_dummy_data(num_records):
fake = Faker()
data = []
for _ in range(num_records):
record = {
"name": fake.name(),
"email": fake.email(),
"address": fake.address(),
}
data.append(record)
return data
dummy_data = generate_dummy_data(5)
print(dummy_data)
Remove Cuss Words using Python
Create a Python script that filters out profanity or offensive words from text.
def remove_cuss_words(text):
cuss_words = ["bad_word1", "bad_word2", "bad_word3"]
for word in cuss_words:
text = text.replace(word, "*censored*")
return text
input_text = "This is a bad_word1 sentence."
filtered_text = remove_cuss_words(input_text)
print(filtered_text)
Find Duplicate Values using Python
Write a Python program to find and remove duplicate values from a list or dataset.
def find_duplicates(data):
seen = set()
duplicates = []
for item in data:
if item in seen:
duplicates.append(item)
else:
seen.add(item)
return list(set(duplicates))
data = [1, 2, 2, 3, 4, 4, 5]
duplicates = find_duplicates(data)
print(f"Duplicates: {duplicates}")
Detect Questions using Python
Learn to identify questions within a text using Python and regular expressions.
import re
def detect_questions(text):
questions = re.findall(r'[A-Z][^.!?]*\?', text)
return questions
text = "Is this a question? What about this one. How are you doing today?"
result = detect_questions(text)
print(result)
Voice Recorder using Python
Create a Python program that records audio using a microphone and saves it as a sound file.
import sounddevice as sd
import soundfile as sf
def record_audio(filename, duration=10):
audio_data = sd.rec(int(duration * 44100), samplerate=44100, channels=2, dtype='int16')
sd.wait()
sf.write(filename, audio_data, 44100)
audio_filename = "recording.wav"
record_audio(audio_filename)
Reading and Writing CSV Files using Python
Practice reading and writing data to CSV files using the csv module in Python.
import csv
def read_csv_file(filename):
data = []
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
data.append(row)
return data
def write_csv_file(filename, data):
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
data_to_write = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]
write_csv_file("sample.csv", data_to_write)
data_read = read_csv_file("sample.csv")
print(data_read)
Box Plot using Python
Learn data visualization by creating a box plot to visualize the distribution and spread of data.
import matplotlib.pyplot as plt
import numpy as np
data = [85, 92, 88, 75, 96, 78, 84, 90, 88, 82]
plt.boxplot(data)
plt.ylabel("Scores")
plt.title("Box Plot of Exam Scores")
plt.show()
Age Calculator using Python
Create a Python program that calculates a person's age based on their birthdate.
from datetime import datetime
def calculate_age(birthdate):
birthdate = datetime.strptime(birthdate, "%Y-%m-%d")
today = datetime.today()
age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
return age
birthdate = "1990-05-15"
age = calculate_age(birthdate)
print(f"You are {age} years old.")
LCM (Least Common Multiple) using Python
Write a Python function to calculate the least common multiple of two numbers.
def calculate_lcm(a, b):
from math import gcd
return a * b // gcd(a, b)
num1 = 12
num2 = 18
lcm = calculate_lcm(num1, num2)
print(f"The LCM of {num1} and {num2} is {lcm}")
Price Elasticity of Demand using Python
Calculate the price elasticity of demand using Python to analyze how sensitive consumers are to price changes.
def price_elasticity(demand_initial, demand_final, price_initial, price_final):
elasticity = (demand_final - demand_initial) / demand_initial / (price_final - price_initial) / price_initial
return elasticity
demand_initial = 100
demand_final = 80
price_initial = 10
price_final = 12
elasticity = price_elasticity(demand_initial, demand_final, price_initial, price_final)
print(f"Price Elasticity of Demand: {elasticity}")
Find the Most Frequent Words in a Given File
Create a Python script to read a text file and find the most frequently occurring words.
def find_most_frequent_words(filename, n=5):
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
most_frequent_words = sorted(word_count, key=word_count.get, reverse=True)[:n]
return most_frequent_words
filename = "sample.txt"
top_words = find_most_frequent_words(filename)
print(f"Top {len(top_words)} frequent words: {', '.join(top_words)}")
Find the Number of Capital Letters in a Given File
Count the number of capital letters in a text file using Python.
def count_capital_letters(filename):
with open(filename, 'r') as file:
text = file.read()
capital_letters = sum(1 for char in text if char.isupper())
return capital_letters
filename = "sample.txt"
capital_count = count_capital_letters(filename)
print(f"Number of capital letters in the file: {capital_count}")
Index of Maximum Value in a Given Python List
Create a Python function to find the index of the maximum value in a list.
def index_of_max_value(lst):
max_value = max(lst)
max_index = lst.index(max_value)
return max_index
numbers = [10, 30, 15, 25, 50, 5]
max_index = index_of_max_value(numbers)
print(f"The index of the maximum value is: {max_index}")
Index of Minimum Value in a Given Python List
Extend your Python skills by creating a function to find the index of the minimum value in a list.
def index_of_min_value(lst):
min_value = min(lst)
min_index = lst.index(min_value)
return min_index
numbers = [10, 30, 15, 25, 5, 50]
min_index = index_of_min_value(numbers)
print(f"The index of the minimum value is: {min_index}")
Program For Voice Recorder
Create a Python program that records audio using a microphone and saves it as a sound file.
import sounddevice as sd
import soundfile as sf
def record_audio(filename, duration=10):
audio_data = sd.rec(int(duration * 44100), samplerate=44100, channels=2, dtype='int16')
sd.wait()
sf.write(filename, audio_data, 44100)
audio_filename = "recording.wav"
record_audio(audio_filename)
Send Automatic Emails using Python
Learn how to send automated emails using Python with libraries like smtplib.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(subject, message, to_email):
from_email = "your_email@gmail.com"
from_password = "your_password"
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_email, from_password)
server.sendmail(from_email, to_email, msg.as_string())
server.quit()
subject = "Automated Email"
message = "This is an automated email sent from Python."
recipient = "recipient_email@gmail.com"
send_email(subject, message, recipient)
Defang IP Address
Create a Python function that defangs an IP address, replacing '.' with '[.]'.
def defang_ip_address(ip_address):
defanged = ip_address.replace('.', '[.]')
return defanged
ip = "192.168.1.1"
defanged_ip = defang_ip_address(ip)
print(f"Defanged IP: {defanged_ip}")
Password Authentication using Python
Build a Python program that verifies user passwords using various authentication methods.
import getpass
def authenticate_user():
password = getpass.getpass("Enter your password: ")
if password == "my_password":
print("Authentication successful.")
else:
print("Authentication failed. Please try again.")
authenticate_user()
These beginner-level Python projects provide valuable experience and knowledge for anyone starting their coding journey. You can further enhance these projects and explore more complex concepts as you become more confident in your Python skills.
Advanced Python Projects with Source Code
End to End Chatbot with Python
Creating an end-to-end chatbot is a complex task involving natural language processing (NLP) and deep learning. Here's a simple example using Python and the Transformers library for chatbot development:
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer
# Load pre-trained GPT-2 model and tokenizer
model_name = "gpt2"
model = GPT2LMHeadModel.from_pretrained(model_name)
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
# Initialize chat history
chat_history_ids = []
# Define the conversation loop
while True:
user_input = input("You: ")
# Append user input to chat history
new_input_ids = tokenizer.encode(user_input, return_tensors="pt")
chat_history_ids.append(new_input_ids)
# Generate response
bot_output = model.generate(torch.cat(chat_history_ids, dim=-1), max_length=100, num_return_sequences=1)
# Decode and print the bot's response
bot_response = tokenizer.decode(bot_output[0], skip_special_tokens=True)
print("Bot:", bot_response)
This code sets up a chatbot using the Chat GPT-2 model, allowing users to interact with it.
These are simplified code examples for advanced projects. Depending on your specific use case and requirements, you may need to implement more advanced features and functionalities.
Conclusion:
In this article, we've explored a wide array of Free Python projects with source code, ranging from beginner-level projects to more advanced ones. These projects not only help you sharpen your Python programming skills but also serve as excellent additions to your portfolio. Whether you're a beginner looking to dip your toes into the world of Python or an experienced developer seeking innovative project ideas, there's something for everyone.
Remember, the best way to master Python is by doing, and these projects provide the perfect hands-on experience. Start with the beginner projects to build a strong foundation, and as you gain confidence, challenge yourself with more advanced projects. With access to source code and step-by-step guides, you'll have the resources you need to bring these projects to life.
So, what are you waiting for? Choose a project that piques your interest, roll up your sleeves, and embark on your Python coding journey. With determination and a curious mindset, you'll not only complete these projects but also acquire valuable skills that can open up a world of opportunities in the world of programming. Happy coding!
यह भी पढ़ें: Python Programming In Hindi | Python Tutorials In Hindi
यह भी पढ़ें: Python Programming In Hindi | Python Tutorials In Hindi
Tags:
Python