Interesting Python Projects With Code for Beginners – Part 2
Python has become the go-to language for Artificial Intelligence (AI) and Machine Learning (ML) development. Its simplicity and expressiveness, combined with a vast ecosystem of powerful libraries, make it an ideal choice for both beginners and experienced practitioners looking to build AI/ML applications.
In this article, we‘ll explore several Python projects that provide a hands-on introduction to practical AI/ML development. We‘ll focus especially on one common task: sending automated emails with Python and Outlook. Being able to programmatically generate and send emails is a critical skill for building AI/ML systems that need to communicate with users or alert developers.
But first, let‘s look at some key reasons why Python has become so dominant in the AI/ML world.
Why Python for AI and ML?
According to the 2021 Stack Overflow Developer Survey, Python is the 3rd most popular programming language overall, behind only JavaScript and HTML/CSS. But when it comes to data science and machine learning, Python is far and away the leader. A 2022 survey by Kaggle found that 82% of data scientists and ML engineers use Python daily!
So what makes Python so well-suited for AI/ML?
Simplicity and Expressiveness
Python prioritizes simplicity and readability, with a clean, expressive syntax that‘s easy for beginners to learn. Its lack of clutter and boilerplate code allows developers to focus on the core logic of their AI/ML algorithms without getting bogged down in the language itself.
At the same time, Python supports complex functional and object-oriented programming paradigms that allow for building large, sophisticated AI/ML systems. Its strong typing and error handling help with writing robust, maintainable code.
Extensive AI/ML Ecosystem
Perhaps Python‘s greatest strength for AI/ML is its unparalleled ecosystem of libraries and frameworks. These tools, built on top of Python‘s core, provide optimized, well-tested implementations of virtually every major AI and ML algorithm.
Some key Python libraries for AI/ML development include:
- NumPy for efficient numerical computing with large, multi-dimensional arrays and matrices
- Pandas for data manipulation and analysis, providing data structures like DataFrames
- Matplotlib for creating static, animated, and interactive visualizations
- scikit-learn for all the core ML algorithms like classification, regression, clustering, and dimensionality reduction
- TensorFlow for building and training deep neural networks
- PyTorch for building deep neural networks with strong GPU acceleration
- Keras for a beginner-friendly, high-level neural networks API
This is just scratching the surface – there are also domain-specific libraries for everything from natural language processing to computer vision to reinforcement learning. Virtually any AI/ML system you can imagine can be built in Python.
Automated Email Sending for AI/ML Systems
Now let‘s apply our Python skills to a practical project – writing a Python script to automatically generate and send emails. This is a super common need for AI/ML systems that need to interact with users or convey information to stakeholders.
Some example use cases:
- Sending an email with the output/insights from a ML model after each time it runs
- Emailing a daily/weekly summary of an AI system‘s performance metrics to the development team
- Alerting users via email when an AI model makes a certain prediction or recommendation relevant to them
In this project, we‘ll build an AI application that runs a ML model to predict customer churn daily, and emails the results to the customer retention team each morning.
Project Setup
We‘ll assume you‘ve already trained and saved a customer churn classification ML model using one of the many great Python ML libraries like scikit-learn, TensorFlow, or PyTorch. We‘ll load this model from a file.
We also need to install the pywin32 package to interact with Microsoft Outlook:
pip install pywin32
Loading the ML Model and Getting Predictions
Let‘s assume we‘ve saved our trained ML model using the pickle module, a common way to serialize Python objects. Here‘s how we‘d load the model from a file:
import pickle
with open(‘churn_model.pkl‘, ‘rb‘) as file:
model = pickle.load(file)
And let‘s say we have a churn_data.csv file with the daily customer interaction data we want predictions for, with columns like "customer_id", "total_purchases", "support_tickets", etc.
We can load this using the pandas library:
import pandas as pd
data = pd.read_csv(‘churn_data.csv‘)
To get churn predictions from our model, we‘d just do:
predictions = model.predict(data)
Composing the Email
Let‘s format our email to include the date, number of customers at risk of churning, and the full predictions in a nice HTML table:
import datetime
from tabulate import tabulate
today = datetime.datetime.today().strftime(‘%Y-%m-%d‘)
num_churn_risk = (predictions == 1).sum()
churn_table = tabulate(data.assign(churn_prediction=predictions), headers=‘keys‘, tablefmt=‘html‘)
email_body = f"""
<p>Date: {today}</p>
<p>Customers at risk of churn: {num_churn_risk}</p>
{churn_table}
"""
This uses the handy tabulate library to convert our DataFrame to an HTML table. Here‘s what the resulting email body might look like:

Sending the Email with Outlook
Now that we‘ve generated the content for our email, sending it with Outlook is straightforward:
import win32com.client as win32
outlook = win32.Dispatch(‘outlook.application‘)
mail = outlook.CreateItem(0)
mail.To = "[email protected]"
mail.Subject = f"Daily Churn Predictions - {today}"
mail.HTMLBody = email_body
mail.Send()
This creates a new email in Outlook, sets the recipient, subject, and HTML body, and sends it!
Scheduling the Daily Email
To run this email sending script each morning, you can use the built-in schedule library. Here‘s the full code to send our churn prediction email at 8am every day:
import pickle
import pandas as pd
import datetime
from tabulate import tabulate
import win32com.client as win32
import schedule
import time
def send_churn_email():
# Load the trained model
with open(‘churn_model.pkl‘, ‘rb‘) as file:
model = pickle.load(file)
# Load the daily data and get predictions
data = pd.read_csv(‘churn_data.csv‘)
predictions = model.predict(data)
# Generate the email body
today = datetime.datetime.today().strftime(‘%Y-%m-%d‘)
num_churn_risk = (predictions == 1).sum()
churn_table = tabulate(data.assign(churn_prediction=predictions), headers=‘keys‘, tablefmt=‘html‘)
email_body = f"""
<p>Date: {today}</p>
<p>Customers at risk of churn: {num_churn_risk}</p>
{churn_table}
"""
# Send the email via Outlook
outlook = win32.Dispatch(‘outlook.application‘)
mail = outlook.CreateItem(0)
mail.To = "[email protected]"
mail.Subject = f"Daily Churn Predictions - {today}"
mail.HTMLBody = email_body
mail.Send()
# Schedule the email to be sent each day at 8am
schedule.every().day.at("08:00").do(send_churn_email)
while True:
schedule.run_pending()
time.sleep(1)
Just run this script, and it will send an email with your ML model‘s latest churn predictions to the retention team every morning at 8am!
Best Practices for AI Email Automation
When automating email sending with AI/ML, there are a few key best practices to keep in mind:
- Be careful not to overwhelm recipients with too many automated emails. If users feel spammed, they‘re likely to ignore the emails or even mark them as junk. Aim for a cadence that delivers value without being intrusive.
- Be transparent that the email content is generated by an AI system. Users should understand when they‘re interacting with machine-generated text. You can include a disclaimer like "This email was generated by an AI system and may contain errors or irrelevant information."
- Make sure there‘s human oversight and the ability to pause or stop the automated emails if something goes wrong. AI/ML systems can sometimes output inappropriate or nonsensical text. There should be a human in the loop to monitor the automated emails and cut them off if needed.
Conclusion
In this article, we explored why Python is an ideal language for AI/ML development and walked through a practical project of using Python to send automated emails with AI-generated content.
I hope this has given you a taste of the kind of powerful AI/ML applications you can build with Python! The possibilities are truly endless. The key is to start practicing and building your own projects – that‘s the only way to develop real mastery.
If you‘re interested to learn more about Python for AI and ML, I highly recommend checking out:
- The official Python data science tutorial: https://docs.python.org/3/tutorial/datastructures.html
- Google‘s Python Class: https://developers.google.com/edu/python
- DataCamp‘s Python data science courses: https://www.datacamp.com/tracks/data-scientist-with-python
- Coursera‘s Machine Learning course, which uses Python: https://www.coursera.org/learn/machine-learning
Remember, the most important thing is to keep practicing and pushing yourself to build increasingly complex and interesting projects. Python and AI/ML can take you to incredible places – enjoy the journey!