22 Python Mini Programs Worth Learning (with Code)

Introduction

Python's rich development ecology is one of its major advantages. Various third-party libraries, frameworks and codes are all "wheels" created by predecessors, which can complete many operations and make your development more efficient.

Here are 22 projects built with Python to learn Python programming.

These examples are simple and practical, perfect for beginners to practice with. You can also try to build a solution by yourself according to the purpose and tips of the project to improve the programming level.

If you want to get more complete source code and Python learning materials, you can click this line of fonts

①Dice Simulator

Purpose: Create a program to simulate rolling dice.

Tip: Use the random module to generate a number between 1 and 6 when the user asks

②Rock paper scissors game

Goal: Create a command-line game where players can choose between rock, scissors, and paper, and play against the computer. If the player wins, the score is added until the end of the game, the final score is shown to the player.

Hint: Receive the player's choice and compare it with the computer's choice. The choice of computer is randomly selected from a selection list. If the player wins, add 1 point.

import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
    player = input("Rock, Paper or  Scissors?").capitalize()
    # 判断游戏者和电脑的选择
    if player == computer:
        print("Tie!")
    elif player == "Rock":
        if computer == "Paper":
            print("You lose!", computer, "covers", player)
            cpu_score+=1
        else:
            print("You win!", player, "smashes", computer)
            player_score+=1
    elif player == "Paper":
        if computer == "Scissors":
            print("You lose!", computer, "cut", player)
            cpu_score+=1
        else:
            print("You win!", player, "covers", computer)
            player_score+=1
    elif player == "Scissors":
        if computer == "Rock":
            print("You lose...", computer, "smashes", player)
            cpu_score+=1
        else:
            print("You win!", player, "cut", computer)
            player_score+=1
    elif player=='E':
        print("Final Scores:")
        print(f"CPU:{cpu_score}")
        print(f"Plaer:{player_score}")
        break
    else:
        print("That's not a valid play. Check your spelling!")
    computer = random.choice(choices)

③Random  password generator

Goal: Create a program that generates a random string of passwords with a specified password length.

Hint: Create a string of numbers + uppercase letters + lowercase letters + special characters. Randomly generate a string of passwords according to the set password length.

④Sentence  generator

Purpose: Generate random and unique sentences from user-provided input.

Tip: Take as input the nouns, pronouns, adjectives, etc. entered by the user, then add all the data to the sentence and return it in combination.

  Guess the number game

Purpose: In this game, the task is to create a script capable of generating a random number within a range. If the user guesses the number correctly in three chances, the user wins the game, otherwise the user loses.

Tip: Generate a random number, then use a loop to give the user three chances to guess, and print the final result based on the user's guess.

⑥Story  Generator

Purpose: Every time the user runs the program, a random story is generated.

TIP: The random module can be used to select random parts of the story from each list.

  Email address slicer

Purpose: Write a Python script that can get the username and domain name from an email address.

Hint: Use @ as the delimiter to split the address into two strings.

  Send emails automatically

Purpose: Write a Python script that can be used to send emails.

Tip: The email library can be used to send emails.

import smtplib 
from email.message import EmailMessage
email = EmailMessage() ## Creating a object for EmailMessage
email['from'] = 'xyz name'   ## Person who is sending
email['to'] = 'xyz id'       ## Whom we are sending
email['subject'] = 'xyz subject'  ## Subject of email
email.set_content("Xyz content of email") ## content of email
with smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp:     
## sending request to server 
    smtp.ehlo()          ## server object
smtp.starttls()      ## used to send data between server and client
smtp.login("email_id","Password") ## login id and password of gmail
smtp.send_message(email)   ## Sending email
print("email send")    ## Printing success message

  Abbreviations

Purpose: Write a Python script that generates an acronym from a given sentence.

Tip: You can get the first word by splitting and indexing, then combine it.

  Text adventure game

Goal: Write a fun Python script that takes the user on a fun adventure by choosing different options for the path

 Hangman

Purpose: To create a simple command line hangman game.

Tip: Create a list of passwords and choose a word at random. Each word is now represented by an underscore "_", giving the user an opportunity to guess the word, and if the user guesses the word correctly, replace the "_" with the word.

import time
import random
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
time.sleep(1)
print ("Start guessing...\n")
time.sleep(0.5)
## A List Of Secret Words
words = ['python','programming','treasure','creative','medium','horror']
word = random.choice(words)
guesses = ''
turns = 5
while turns > 0:         
    failed = 0             
    for char in word:      
        if char in guesses:    
            print (char,end="")    
        else:
            print ("_",end=""),     
            failed += 1    
    if failed == 0:        
        print ("\nYou won") 
        break              
    guess = input("\nguess a character:") 
    guesses += guess                    
    if guess not in word:  
        turns -= 1        
        print("\nWrong")    
        print("\nYou have", + turns, 'more guesses') 
        if turns == 0:           
            print ("\nYou Lose") 

   Alarm clock

Purpose: Write a Python script that creates an alarm clock.

Tip: You can use the date-time module to create alarms, and the playsound library to play sounds.

from datetime import datetime   
from playsound import playsound
alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n")
alarm_hour=alarm_time[0:2]
alarm_minute=alarm_time[3:5]
alarm_seconds=alarm_time[6:8]
alarm_period = alarm_time[9:11].upper()
print("Setting up alarm..")
while True:
    now = datetime.now()
    current_hour = now.strftime("%I")
    current_minute = now.strftime("%M")
    current_seconds = now.strftime("%S")
    current_period = now.strftime("%p")
    if(alarm_period==current_period):
        if(alarm_hour==current_hour):
            if(alarm_minute==current_minute):
                if(alarm_seconds==current_seconds):
                    print("Wake Up!")
                    playsound('audio.mp3') ## download the alarm sound from link
                    break

   Audiobooks

Purpose: Write a Python script for converting Pdf files to audiobooks.

Tip: Convert text to speech with the help of the pyttsx3 library.

Installation: pyttsx3, PyPDF2

 Weather app

Purpose: Write a Python script that receives the city name and uses the crawler to get the weather information of the city.

Tip: You can use the Beautifulsoup and requests libraries to scrape data directly from the Google homepage.

from bs4 import BeautifulSoup
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

def weather(city):
    city=city.replace(" ","+")
    res = requests.get(f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',headers=headers)
    print("Searching in google......\n")
    soup = BeautifulSoup(res.text,'html.parser')   
    location = soup.select('#wob_loc')[0].getText().strip()  
    time = soup.select('#wob_dts')[0].getText().strip()       
    info = soup.select('#wob_dc')[0].getText().strip() 
    weather = soup.select('#wob_tm')[0].getText().strip()
    print(location)
    print(time)
    print(info)
    print(weather+"°C") 

print("enter the city name")
city=input()
city=city+" weather"
weather(city)

Installation: requests, BeautifulSoup

⑮Face  Detection

Purpose: Write a Python script that can detect faces in an image and save all the faces in a folder.

Tip: You can use the haar cascade classifier to detect faces. The face coordinate information it returns can be saved in a file.

Installation: OpenCV.

Download: haarcascade_frontalface_default.xml

https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml

import cv2
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the input image
img = cv2.imread('images/img0.jpg')
# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
# Draw rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
    crop_face = img[y:y + h, x:x + w]  
    cv2.imwrite(str(w) + str(h) + '_faces.jpg', crop_face)
# Display the output
cv2.imshow('img', img)
cv2.imshow("imgcropped",crop_face)
cv2.waitKey()

   Reminder app

Purpose: Create a reminder app that reminds you to do something at a specific time (desktop notification).

Tip: The Time module can be used to track reminder times, and the toastnotifier library can be used to display desktop notifications.

Installation: win10toast

from win10toast import ToastNotifier
import time
toaster = ToastNotifier()
try:
    print("Title of reminder")
    header = input()
    print("Message of reminder")
    text = input()
    print("In how many minutes?")
    time_min = input()
    time_min=float(time_min)
except:
    header = input("Title of reminder\n")
    text = input("Message of remindar\n")
    time_min=float(input("In how many minutes?\n"))
time_min = time_min * 60
print("Setting up reminder..")
time.sleep(2)
print("all set!")
time.sleep(time_min)
toaster.show_toast(f"{header}",
f"{text}",
duration=10,
threaded=True)
while toaster.notification_active(): time.sleep(0.005)     

   Wikipedia article summary

Purpose: Use a simple method to generate summaries from user-provided links to articles.

Tip: You can use a crawler to get article data and generate abstracts by extracting

from bs4 import BeautifulSoup
import re
import requests
import heapq
from nltk.tokenize import sent_tokenize,word_tokenize
from nltk.corpus import stopwords

url = str(input("Paste the url"\n"))
num = int(input("Enter the Number of Sentence you want in the summary"))
num = int(num)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
#url = str(input("Paste the url......."))
res = requests.get(url,headers=headers)
summary = ""
soup = BeautifulSoup(res.text,'html.parser') 
content = soup.findAll("p")
for text in content:
    summary +=text.text 
def clean(text):
    text = re.sub(r"\[[0-9]*\]"," ",text)
    text = text.lower()
    text = re.sub(r'\s+'," ",text)
    text = re.sub(r","," ",text)
    return text
summary = clean(summary)

print("Getting the data......\n")


##Tokenixing
sent_tokens = sent_tokenize(summary)

summary = re.sub(r"[^a-zA-z]"," ",summary)
word_tokens = word_tokenize(summary)
## Removing Stop words

word_frequency = {}
stopwords =  set(stopwords.words("english"))

for word in word_tokens:
    if word not in stopwords:
        if word not in word_frequency.keys():
            word_frequency[word]=1
        else:
            word_frequency[word] +=1
maximum_frequency = max(word_frequency.values())
print(maximum_frequency)          
for word in word_frequency.keys():
    word_frequency[word] = (word_frequency[word]/maximum_frequency)
print(word_frequency)
sentences_score = {}
for sentence in sent_tokens:
    for word in word_tokenize(sentence):
        if word in word_frequency.keys():
            if (len(sentence.split(" "))) <30:
                if sentence not in sentences_score.keys():
                    sentences_score[sentence] = word_frequency[word]
                else:
                    sentences_score[sentence] += word_frequency[word]

print(max(sentences_score.values()))
def get_key(val): 
    for key, value in sentences_score.items(): 
        if val == value: 
            return key 
key = get_key(max(sentences_score.values()))
print(key+"\n")
print(sentences_score)
summary = heapq.nlargest(num,sentences_score,key=sentences_score.get)
print(" ".join(summary))
summary = " ".join(summary)

 Get Google search results

Purpose: Create a script that can fetch data from Google Search based on query criteria.

from bs4 import BeautifulSoup 
import requests

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
def google(query):
    query = query.replace(" ","+")
    try:
        url = f'https://www.google.com/search?q={query}&oq={query}&aqs=chrome..69i57j46j69i59j35i39j0j46j0l2.4948j0j7&sourceid=chrome&ie=UTF-8'
        res = requests.get(url,headers=headers)
        soup = BeautifulSoup(res.text,'html.parser')
    except:
        print("Make sure you have a internet connection")
    try:
        try:
            ans = soup.select('.RqBzHd')[0].getText().strip()

        except:
            try:
                title=soup.select('.AZCkJd')[0].getText().strip()
                try:
                    ans=soup.select('.e24Kjd')[0].getText().strip()
                except:
                    ans=""
                ans=f'{title}\n{ans}'

            except:
                try:
                    ans=soup.select('.hgKElc')[0].getText().strip()
                except:
                    ans=soup.select('.kno-rdesc span')[0].getText().strip()

    except:
        ans = "can't find on google"
    return ans

result = google(str(input("Query\n")))
print(result)

The results obtained are as follows.

 Currency Converter

Purpose: Write a Python script that can convert one currency to another user's chosen currency.

Tip: Use the API in Python, or through the forex-python module to get real-time currency exchange rates.

Install: forex-python

 Keylogger

Purpose: Write a Python script that saves all keys pressed by the user in a text file.

Tip: pynput is a library in Python for controlling keyboard and mouse movements, it can also be used to make keyloggers. Simply read the keys the user pressed and save them in a text file after a certain number of keys.

from pynput.keyboard import Key, Controller,Listener
import time
keyboard = Controller()


keys=[]
def on_press(key):
    global keys
    #keys.append(str(key).replace("'",""))
    string = str(key).replace("'","")
    keys.append(string)
    main_string = "".join(keys)
    print(main_string)
    if len(main_string)>15:
      with open('keys.txt', 'a') as f:
          f.write(main_string)   
          keys= []     
def on_release(key):
    if key == Key.esc:
        return False

with listener(on_press=on_press,on_release=on_release) as listener:
    listener.join()

 ㉑Article  Reader

Purpose: Write a Python script that automatically reads articles from the links provided.

import pyttsx3
import requests
from bs4 import BeautifulSoup
url = str(input("Paste article url\n"))

def content(url):
  res = requests.get(url)
  soup = BeautifulSoup(res.text,'html.parser')
  articles = []
  for i in range(len(soup.select('.p'))):
    article = soup.select('.p')[i].getText().strip()
    articles.append(article)
    contents = " ".join(articles)
  return contents
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)

def speak(audio):
  engine.say(audio)
  engine.runAndWait()

contents = content(url)
## print(contents)      ## In case you want to see the content

#engine.save_to_file
#engine.runAndWait() ## In case if you want to save the article as a audio file

 Short URL Generator

Purpose: Write a Python script that shortens a given URL using the API.

from __future__ import with_statement
import contextlib
try:
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlencode
try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen
import sys

def make_tiny(url):
    request_url = ('http://tinyurl.com/api-create.php?' + 
    urlencode({'url':url}))
    with contextlib.closing(urlopen(request_url)) as response:
        return response.read().decode('utf-8')

def main():
    for tinyurl in map(make_tiny, sys.argv[1:]):
        print(tinyurl)

if __name__ == '__main__':
    main()
-----------------------------OUTPUT------------------------
python url_shortener.py https://www.wikipedia.org/
https://tinyurl.com/buf3qt3

 Summarize:

Some of the projects need to be adjusted appropriately. For example, to send emails automatically, you can choose to use QQ mailbox; to query weather information, you can also use some free APIs in China; Wikipedia can correspond to Baidu Encyclopedia; Google search can correspond to Baidu search and so on.

These are all things that you need to pay attention to when running.

 end

The above is the content shared today~ I hope it will help you some! If you like it, remember to give the editor a three-stroke before leaving.

Guess you like

Origin blog.csdn.net/L010409/article/details/123177415