generate_random_number
这个程序使用random模块生成一个指定范围内的随机数,通过用户输入确定范围,并输出生成的随机数。
2. 简单密码生成器
一个简单的密码生成器可以帮助你生成随机的安全密码。
python
复制代码
import random
import string
def generate_password(length=8):
characters = string.ascii_letters + string.digits + string.punctuation
password = “.join(random.choice(characters) for i in range(length))
print(f”生成的密码是:{password}“)
generate_password(12)
这个程序使用string模块和random模块生成一个包含字母、数字和特殊字符的随机密码,默认长度为8个字符。
3. 计时器
编写一个简单的计时器程序,可以用来测量时间间隔。
python
复制代码
import time
def timer(seconds):
print(f”计时器开始,倒计时{seconds}秒”)
while seconds:
mins, secs = divmod(seconds, 60)
time_format = f”{mins:02d}:{secs:02d}”
print(time_format, end=‘r’)
time.sleep(1)
seconds -= 1
print(“时间到!”)
timer(10)
这个程序使用time模块实现一个倒计时功能,用户可以输入倒计时时间,程序每秒更新一次显示,直到时间结束。
4. 简单的计算器
编写一个简单的计算器程序,支持加、减、乘、除运算。
python
复制代码
def calculator:
operation = input(“请输入操作(+、-、、/):”)
num1 = float(input(“请输入第一个数字:”))
num2 = float(input(“请输入第二个数字:”))
if operation == “+”:
print(f”结果:{num1 + num2}“)
elif operation == “-”:
print(f”结果:{num1 - num2}“)
elif operation == “”:
print(f”结果:{num1 * num2}“)
ningxia.tgoi.cn/P9l902/
jiangxi.tgoi.cn/5Cyzqs/
jilin.tgoi.cn/9ngh4N/
heilongjiang.tgoi.cn/sORUDg/
guangxi.tgoi.cn/9otVut/
elif operation == “/”:
if num2 != 0:
print(f”结果:{num1 / num2}“)
else:
print(“除数不能为零!”)
else:
print(“无效的操作符!”)
calculator
这个程序通过用户输入选择运算符和数字,并根据运算符执行相应的计算,输出结果。
5. 简单天气查询
通过调用一个天气API,可以获取当前天气信息。
python
复制代码
import requests
def get_weather(city):
api_key = “your_api_key” # 替换为你的API密钥
base_url = “http://api.openweathermap.org/data/2.5/weather?”
complete_url = base_url + “q=” + city + “&appid=” + api_key + “&units=metric”
response = requests.get(complete_url)
data = response.json
if data[“cod”] != “404”:
main = data[“main”]
weather = data[“weather”][0]
print(f”城市:{city}“)
print(f”温度:{main[‘temp’]}°C”)
print(f”天气:{weather[‘description’]}“)
else:
print(“城市未找到!”)
city_name = input(“请输入城市名称:”)
get_weather(city_name)
这个程序使用requests库调用OpenWeatherMap API获取指定城市的天气信息,并将结果打印到控制台。你需要在程序中替换为你自己的API密钥。
结论
以上五个简单有趣的Python代码示例展示了Python在生成随机数、密码生成、时间管理、数学计算和数据获取方面的应用。通过这些项目,你可以在实践中掌握Python的基本语法和库的使用,并在编程中找到乐趣。希望这些示例能够激发你的编程兴趣,带你进入Python编程的奇妙世界。继续探索和尝试,你会发现Python的更多可能性。
来源:https://www.top168.com/news/show-175424.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/192413.html