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

preface

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!")
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") 

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_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

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:
        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)

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()
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)     

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()
    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

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
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()

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()


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()

epilogue

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