整理了适合新手的20个Python练手小程序 含代码
时间: 2024-01-27 16:04:24 浏览: 147
几个python入门级小程序
好的,以下是适合新手的20个Python练手小程序的代码实现:
1. 猜数字游戏
```python
import random
number = random.randint(1, 100)
guess = int(input("Guess a number between 1 and 100: "))
while guess != number:
if guess < number:
print("Too low!")
else:
print("Too high!")
guess = int(input("Guess again: "))
print("You guessed it! The number was", number)
```
2. 石头、剪子、布游戏
```python
import random
options = ["rock", "paper", "scissors"]
player = input("Choose rock, paper, or scissors: ")
computer = random.choice(options)
print("You chose", player)
print("The computer chose", computer)
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
print("You win!")
elif player == "paper" and computer == "rock":
print("You win!")
elif player == "scissors" and computer == "paper":
print("You win!")
else:
print("Computer wins!")
```
3. 打印九九乘法表
```python
for i in range(1, 10):
for j in range(1, 10):
print(i, "*", j, "=", i*j)
print()
```
4. 计算器小程序
```python
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1 / num2)
else:
print("Invalid operator")
```
5. 猜单词游戏
```python
import random
words = ["apple", "banana", "orange", "grape", "watermelon"]
word = random.choice(words)
print("Guess the word!")
guess = input("Enter your guess: ")
while guess != word:
print("Wrong! Try again.")
guess = input("Enter your guess: ")
print("You guessed it! The word was", word)
```
6. 简单的文本编辑器
```python
filename = input("Enter filename: ")
try:
with open(filename, "r") as file:
contents = file.read()
except FileNotFoundError:
contents = ""
new_contents = input("Enter new contents: ")
with open(filename, "w") as file:
file.write(new_contents)
```
7. 文件拷贝小工具
```python
import shutil
source = input("Enter source filename: ")
destination = input("Enter destination filename: ")
shutil.copy(source, destination)
```
8. 网络爬虫小程序
```python
import requests
from bs4 import BeautifulSoup
url = input("Enter URL: ")
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
for link in soup.find_all("a"):
print(link.get("href"))
```
9. 简单的日历应用程序
```python
import calendar
year = int(input("Enter year: "))
month = int(input("Enter month: "))
print(calendar.month(year, month))
```
10. 命令行版的日程管理器
```python
schedule = {}
while True:
command = input("Enter command (add, view, quit): ")
if command == "quit":
break
elif command == "add":
date = input("Enter date (YYYY-MM-DD): ")
event = input("Enter event: ")
schedule[date] = event
elif command == "view":
for date, event in schedule.items():
print(date, event)
else:
print("Invalid command")
```
11. 电子邮件客户端
```python
import smtplib
sender = input("Enter sender email: ")
password = input("Enter sender password: ")
recipient = input("Enter recipient email: ")
subject = input("Enter email subject: ")
body = input("Enter email body: ")
message = f"Subject: {subject}\n\n{body}"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(sender, password)
server.sendmail(sender, recipient, message)
server.quit()
```
12. 音乐播放器
```python
import pygame
pygame.init()
file = input("Enter filename: ")
pygame.mixer.music.load(file)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
```
13. 生成随机密码
```python
import random
import string
length = int(input("Enter password length: "))
characters = string.ascii_letters + string.digits + string.punctuation
password = "".join(random.choice(characters) for i in range(length))
print(password)
```
14. 生成随机验证码
```python
import random
import string
length = 6
characters = string.ascii_uppercase + string.digits
code = "".join(random.choice(characters) for i in range(length))
print(code)
```
15. 生成随机数序列
```python
import random
length = int(input("Enter sequence length: "))
numbers = [random.randint(1, 100) for i in range(length)]
print(numbers)
```
16. 图片转换小工具
```python
from PIL import Image
filename = input("Enter filename: ")
image = Image.open(filename)
new_filename = input("Enter new filename: ")
image.save(new_filename)
```
17. 图片压缩小工具
```python
from PIL import Image
filename = input("Enter filename: ")
image = Image.open(filename)
quality = int(input("Enter quality (1-100): "))
new_filename = input("Enter new filename: ")
image.save(new_filename, optimize=True, quality=quality)
```
18. 生成条形码和二维码
```python
import barcode
from barcode.writer import ImageWriter
from qrcode import QRCode, constants
from qrcode.exceptions import DataOverflow
data = input("Enter data: ")
barcode_type = input("Enter barcode type (EAN13, Code128): ")
if barcode_type == "EAN13":
barcode_class = barcode.get_barcode_class("ean13")
elif barcode_type == "Code128":
barcode_class = barcode.get_barcode_class("code128")
else:
print("Invalid barcode type")
barcode_image = barcode_class(data, writer=ImageWriter())
barcode_image.save("barcode")
qr_code = QRCode(version=None, error_correction=constants.ERROR_CORRECT_L, box_size=10, border=4)
try:
qr_code.add_data(data)
qr_code.make(fit=True)
qr_code_image = qr_code.make_image(fill_color="black", back_color="white")
qr_code_image.save("qr_code")
except DataOverflow:
print("Data too long for QR code")
```
19. 短信发送小工具
```python
import requests
url = "https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json"
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
from_number = input("Enter from number: ")
to_number = input("Enter to number: ")
message_body = input("Enter message body: ")
payload = {"To": to_number, "From": from_number, "Body": message_body}
response = requests.post(url, auth=(account_sid, auth_token), data=payload)
print(response.text)
```
20. 网络图片下载工具
```python
import requests
url = input("Enter URL: ")
filename = input("Enter filename: ")
response = requests.get(url)
with open(filename, "wb") as file:
file.write(response.content)
```
阅读全文