Ziyad Yehia

In this article, I will present five practical Python programming examples to show you how Python can be used to write short but useful real-life scripts.

Python is best known for its ability to make programming accessible to everyone, even total beginners. Python is a highly expressive language that allows us to write rather sophisticated programs in relatively few lines of code.

According to Stack Overflow, Python is among the most loved programming languages in the world, and developers who do not currently use it put it at the top of their list for technologies they want to learn.  

The Python Bible™ | Everything You Need to Program in Python

Last Updated April 2021

  • 74 lectures
  • Beginner Level
4.7 (32,673)

Build 11 Projects and go from Beginner to Pro in Python with the World’s Most Fun Project-Based Python Course! | By Ziyad Yehia, Internet of Things Academy

Explore Course

1. Automated desktop cleaner

Have you ever used cleaning your computer desktop screen as a procrastination tactic? Well, that tactic is about to get even more effective.

In Python, we can automatically sort files on our desktop into different folders based on their file type.

Let’s say that we want a script that will:

Here’s how a script could execute this:

  1. First, it will get a list of the files on the desktop (ignoring the directories).
  2. Then loop through each file and move the files to the appropriate folder based on the file extension using its “get_new_file_path” function.

Here is how that script would look in Python code:

import os

# Step 1: Move to the Desktop
DESKTOP_PATH = r'INSERT_PATH_TO_YOUR DESKTOP'
os.chdir(DESKTOP_PATH)

# Step 2:
# Get all the files on desktop (ignore directories)
files = [entry for entry in os.scandir() if entry.is_file()]

# This is just a function that makes the code a bit neater later.
def new_file_path(folder_name):
     return os.path.join(DESKTOP_PATH, 
                         folder_name,
                         f"{filename}.{extension}")

# Step 3: Loop through each file and move it based on its file extension.

for file in files:
     filename, extension = file.name.split(".")
     current_file_path = os.path.join(
                            DESKTOP_PATH, 
                            f"{filename}.{extension}"
                         )

     if extension in ['txt', 'docx', 'pdf']:
          os.rename(current_file_path, new_file_path('documents'))

     elif extension in ["png", "jpg"]:
          os.rename(current_file_path, new_file_path('images'))

Voila! In just about 30 lines, including blank lines and comments, we now have a script that can tidy up our desktop.

If you want to add different file types, just add another “elif” condition at the bottom.

Advantages of this script: 

Disadvantages of this script:

2. Text processor 

Have you ever written an online review for a product, movie, or restaurant?

One of the common applications of text processing these days is to read customer reviews and use them to generate insights. As a part of this task, it becomes increasingly important to understand the number of times each word occurs in the datasets. 

We can process text by building the following Python program:

# Define the statement
sentence = "the person to the left of me was teaching python to the person to the right of me"

#split the statement to find the words
words = sentence.split(' ')

#Initialize a dictionary
word_dict = {}

#Loop through ‘words’ list  and find the frequency of each word 
for word in words:
    if word in list(word_dict.keys() ):
        word_dict[word] = word_dict[word] + 1
    
    else:
        word_dict[word] = 1

#Let's print it out
print(word_dict)

Output:

{'the': 4, 
'person': 2, 
'next': 1, 
'to': 3, 
'left': 1, 
'of': 2, 
'me': 2, 
'was': 1, 
'teaching': 1, 
'python': 1, 
'right': 1}

Scripts like this are a useful part of natural language processing. 

3. Restaurant price tracker

I’m sure a lot of us have dreamt of owning restaurants. However, like any other business, running a restaurant can get tricky and complicated. 

The first thing a customer may look for after coming to your restaurant is the menu. Let’s see how we can design a menu using Python’s dictionaries. 

# Initialize a dictionary named menucard using curly brackets
menu = {}

# Add the different items
menu['Sandwich'] = 3.99
menu['Burger'] = 4.99
menu['Pizza'] = 7.99

# Print the prices
print(menucard)

Output

{'Sandwich': 3.99, 'Burger': 4.99, 'Pizza': 7.99}

Suppose your first customer orders a burger. Let’s try to print out the price of a burger. To find this value, we call the ‘Burger’ key in the dictionary, as is shown below:

print(menu['Burger'])

Output:

4.99

Now, let’s take this a step further. What if your restaurant had three different pizza sizes to choose from: small, medium, and large?

Well, here’s where nested dictionaries come into the picture. 

# Initialize a dictionary named menucard
menu = {}

# Add the different items
menu['Sandwich'] = 3.99
menu['Burger'] = 4.99
menu['Pizza'] = {'S': 7.99, 'M': 10.99, 'L':13.99}

#This is how the dictionary looks like
print(menu)

Output:

{'Sandwich': 3.99,
 'Burger': 4.99,
 'Pizza': {'S': 7.99, 'M': 10.99, 'L':13.99}
}

Let’s say a new customer now comes in and orders a medium size pizza. Here’s how you could retrieve the corresponding price. 

print(menu['Pizza']['M'])

Output:

10.99

What a deal!

The next step for this would be to create a graphical user interface (GUI) to represent the different selections. 

To do this, check out Python’s great GUI libraries, such as TkInter and Kivy

4. Finding common hobbies

In this example, we’ll use Python to find common hobbies between you and your friend. 

To do this, we are going to use Python sets. 

First, we will create a set of our hobbies, a set of our friend’s hobbies, and then use the set union operator to find the overlap.

Here we go:

my_hobbies = {'Python', 'Cooking', 'Tennis', 'Reading'}

friend_hobbies = {'Tennis', 'Soccer', 'Python'}

# Find overlap using the '&' operator
common_hobbies = my_hobbies & friend_hobbies
print(common_hobbies)

Output

{'Tennis', 'Python'}

See, everyone likes Python!

5. Weather predictor 

Imagine you’d like to receive suggestions on whether you should play your favorite sport based on the current weather. 

You like to play when it is overcast, but not when it’s raining. When it’s sunny, you only want to play if the temperature is below 20 degrees celsius.

Here’s what that would look like in Python:

# Define today's conditions
weather = 'sunny'
temperature = 18

#write the conditions to decide
if weather == 'overcast':
    action = 'play'
    
elif weather == 'rainy':
    action = 'do not play'
    
elif weather == 'sunny' and temperature <= 20:
    action = 'play'
    
elif weather == 'sunny' and temperature > 20:
    action = 'do not play'
    
print(action)

Output:

Play

With some more advanced code, we can import the current weather and temperature conditions from Google, and receive automatic notifications to our desktop to tell us that now is an opportunity to play. Cool, right?

Wrapping up

I hope you have enjoyed learning five ways to use Python programming to write short and effective scripts.

If you want to learn Python and build apps for yourself, then I invite you to check out my Beginner’s Python course: The Python Bible.

Top courses in Python

2021 Complete Python Bootcamp From Zero to Hero in Python
Jose Portilla
4.6 (358,706)
Bestseller
Learn Python & Ethical Hacking From Scratch
Zaid Sabih, z Security
4.7 (13,162)
The Complete Python Programmer Bootcamp 2021
365 Careers, Giles McMullen-Klein
4.6 (3,224)
Design Patterns in Python
Dmitri Nesteruk
4.4 (1,269)
Artificial Intelligence: Reinforcement Learning in Python
Lazy Programmer Team, Lazy Programmer Inc.
4.6 (8,478)
Bestseller
Natural Language Processing with Deep Learning in Python
Lazy Programmer Team, Lazy Programmer Inc.
4.6 (6,431)

More Python Courses

Python students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo

Courses by Ziyad Yehia

The Python Bible™ | Everything You Need to Program in Python
Ziyad Yehia, Internet of Things Academy
4.7 (32,673)
Linux Mastery: Master the Linux Command Line in 11.5 Hours
Ziyad Yehia, Internet of Things Academy
4.7 (13,398)
Bestseller
Bash Mastery: The Complete Guide to Bash Shell Scripting
Ziyad Yehia, Internet of Things Academy
4.9 (26)
Bestseller

Courses by Ziyad Yehia