值得学习练手的五个Python迷你程序(附代码),


在使用Python的过程中,我最喜欢的就是Python的各种第三方库,能够完成很多操作。

下面就给大家介绍5个通过Python构建的项目,以此来学习Python编程。

一、石头剪刀布游戏

目标:创建一个命令行游戏,游戏者可以在石头、剪刀和布之间进行选择,与计算机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) 

二、随机密码生成器

目标:创建一个程序,可指定密码长度,生成一串随机密码。

提示:创建一个数字+大写字母+小写字母+特殊字符的字符串。根据设定的密码长度随机生成一串密码。

  1. import random  
  2. passlen = int(input("enter the length of password" ))  
  3. s=" abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKL MNOPQRSTUVIXYZ!aN$x*6*( )?"  
  4. p = ".join(random.sample(s,passlen ))  
  5. print(p)  
  6. ----------------------------  
  7. enter the length of password  
  8. 6  
  9. Za1gB0 

三、骰子模拟器

目的:创建一个程序来模拟掷骰子。

提示:当用户询问时,使用random模块生成一个1到6之间的数字。

  1. import random;  
  2. while int(input('Press 1 to roll the dice or 0 to exit:\n')): print( random. randint(1,6))  
  3. --------------------------------------------------------------------  
  4. Press 1 to roll the dice or 0 to exit  
  5. 1  

四、自动发送邮件

目的:编写一个Python脚本,可以使用这个脚本发送电子邮件。

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

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

五、闹钟

目的:编写一个创建闹钟的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  

鸿蒙官方战略合作共建——HarmonyOS技术社区

评论关闭