


Recommended collection, five Python mini projects (with source code)
In the process of using Python, what I like most is Python’s various third-party libraries, which can complete many operations.
The following will introduce you to 5 projects built through Python to learn Python programming.
1. Rock, Paper, Scissors Game
Objective: Create a command line game where players can choose between rock, scissors and paper to compete with the computer. If the player wins, points are added until the end of the game, when the final score is displayed to the player.
Tip: Receive the player's choice and compare it with the computer's choice. The computer's selection is chosen randomly from a selection list. If the player wins, 1 point is 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 orScissors?).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(fCPU:{cpu_score}) print(fPlaer:{player_score}) break else: print(That's not a valid play. Check your spelling!) computer = random.choice(choices)
2. Random password generator
Goal: Create a program that can specify the password length and generate a string of random passwords.
Tip: Create a string of numbers, uppercase letters, lowercase letters, and special characters. Randomly generate a string of passwords based on the set password length.
import random passlen = int(input(enter the length of password )) s= abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKL MNOPQRSTUVIXYZ!aN$x*6*( )? p = .join(random.sample(s,passlen )) print(p) ---------------------------- enter the length of password 6 Za1gB0
3. Dice Simulator
Purpose: Create a program to simulate throwing dice.
Tip: Use the random module to generate a number between 1 and 6 when the user asks.
import random; while int(input('Press 1 to roll the dice or 0 to exit:n')): print( random. randint(1,6)) -------------------------------------------------------------------- Press 1 to roll the dice or 0 to exit 1 4
4. Automatically send emails
Purpose: Write a Python script that can be used to send emails.
Tip: The email library can be used to send emails.
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
5. Alarm clock
Purpose: Write a Python script to create an alarm clock.
Tip: You can use the date-time module to create an alarm clock, and the playsound library to play sounds.
from datetime import datetime from playsound import playsound alarm_time = input(Enter the time of alarm to be set:HH:MM:SSn) 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
The above is the detailed content of Recommended collection, five Python mini projects (with source code). For more information, please follow other related articles on the PHP Chinese website!

Pythonisbothcompiledandinterpreted.WhenyourunaPythonscript,itisfirstcompiledintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).Thishybridapproachallowsforplatform-independentcodebutcanbeslowerthannativemachinecodeexecution.

Python is not strictly line-by-line execution, but is optimized and conditional execution based on the interpreter mechanism. The interpreter converts the code to bytecode, executed by the PVM, and may precompile constant expressions or optimize loops. Understanding these mechanisms helps optimize code and improve efficiency.

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor
