带你用Python制作7个程序,让你感受到端午节的快乐
在Python中,我们可以用不同的方式来制作程序,以下是一些例子:
- 用Python制作一个简单的计算器:
# 用Python制作一个简单的计算器
def add(x,y):
return x + y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
def divide(x,y):
if y==0:
return "Cannot Divided by Zero"
else:
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# 用户输入选择
choice = input("Enter choice(1/2/3/4):")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
- 用Python制作一个简单的随机密码生成器:
# 用Python制作一个简单的随机密码生成器
import string
import random
def generate_password(length=8):
password_characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(password_characters) for _ in range(length))
print(generate_password())
- 用Python制作一个简单的图片压缩工具:
# 用Python制作一个简单的图片压缩工具
from PIL import Image
def image_compress(img_path, to_size):
img = Image.open(img_path)
img.thumbnail(to_size)
img.save(img_path, "JPEG")
image_compress('test.jpg', (500, 500))
- 用Python制作一个简单的文本转语音工具:
# 用Python制作一个简单的文本转语音工具
import pyttsx3
def text_to_speech(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
text_to_speech('Hello, World!')
- 用Python制作一个简单的天气预报应用:
# 用Python制作一个简单的天气预报应用
import requests
def get_weather(city):
api_key = 'YOUR_API_KEY'
url = 'http://api.openweathermap.org/data/2.5/weather?appid=' + api_key + '&q=' + city
response = requests.get(url)
weather = response.json()
temp = weather['main']['temp']
return temp
print("Temperature in " + city + ": " + str(get_weather(city)) + " degree Celsius")
- 用Python制作
评论已关闭