当前位置:网站首页 > Python编程 > 正文

简单好玩的编程代码Python(简单好玩的编程代码大全)



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

到此这篇简单好玩的编程代码Python(简单好玩的编程代码大全)的文章就介绍到这了,更多相关内容请继续浏览下面的相关推荐文章,希望大家都能在编程的领域有一番成就!

版权声明


相关文章:

  • 编程入门教学零基础python(编程入门教学零基础)2026-04-09 19:54:08
  • python函数(python函数def讲解)2026-04-09 19:54:08
  • python字典增加和删除(python中字典的删除)2026-04-09 19:54:08
  • 服务器怎么运行python(服务器怎么运行exe文件)2026-04-09 19:54:08
  • py文件用什么运行(python3运行py文件)2026-04-09 19:54:08
  • python函数没有return,返回什么(python 没有return返回none)2026-04-09 19:54:08
  • python删除venv虚拟环境(python3 venv 虚拟环境)2026-04-09 19:54:08
  • 服务器部署python环境(服务器部署python程序)2026-04-09 19:54:08
  • bs4库安装(安装bs4的python库)2026-04-09 19:54:08
  • pivot函数(pivot函数 python)2026-04-09 19:54:08
  • 全屏图片