python 28例子(持续更新)


Python是一种强大的编程语言,用于各种计算和数据处理任务。以下是一些常用的Python计算方法:
全部都运行过的

python计算

1. 基本数学运算:

  • 加法:a + b
  • 减法:a - b
  • 乘法:a * b
  • 除法:a / b
  • 取余:a % b
  • 幂运算:a b
a = 5
b = 2
result = a + b
print(result)

2. 数学函数:

Python提供了丰富的数学函数,这些函数位于math模块中。例如,可以使用math.sqrt()计算平方根,使用math.sin()计算正弦值等。

import math

x = 16
square_root = math.sqrt(x)
print(square_root)

3. 随机数生成:

使用random模块可以生成随机数。

import random

random_number = random.randint(1, 100)
print(random_number)

4. 字符串操作:

字符串是Python中的基本数据类型之一,可以进行各种操作,包括拼接、切片、查找等。

str1 = "Hello"
str2 = " World"
result = str1 + str2
print(result)

5. 列表操作:

列表是Python中的另一个常见数据类型,可以进行元素的增删改查等操作。

my_list = [1, 2, 3, 4, 5]
my_list.append(6)  # 添加元素
print(my_list)

6. 条件语句:

使用ifelifelse关键字进行条件判断。

x = 10

if x > 0:
    print("x是正数")
elif x < 0:
    print("x是负数")
else:
    print("x是零")

7. 循环语句:

使用forwhile循环进行迭代操作。

for i in range(5):
    print(i)

counter = 0
while counter < 5:
    print(counter)
    counter += 1

数字转换

8. 进制转换:

Python支持二进制、八进制和十六进制的表示。可以使用bin()oct()hex()函数将数字转换为相应进制的字符串。

decimal_number = 15

binary_representation = bin(decimal_number)
octal_representation = oct(decimal_number)
hexadecimal_representation = hex(decimal_number)

print(f"Binary: {binary_representation}")
print(f"Octal: {octal_representation}")
print(f"Hexadecimal: {hexadecimal_representation}")

9.绝对值:

使用abs()函数可以得到一个数的绝对值。

number = -10
absolute_value = abs(number)
print(absolute_value)

10. 四舍五入:

使用`round()`函数进行四舍五入。
floating_point_number = 3.14159
rounded_number = round(floating_point_number, 2)  # 保留两位小数
print(rounded_number)

11. 最大值和最小值:

使用`max()`和`min()`函数找到一组数字的最大值和最小值。
numbers = [2, 7, 1, 9, 4]
max_value = max(numbers)
min_value = min(numbers)
print(f"Max: {max_value}, Min: {min_value}")

12. 幅度与角度转换:

Python的`math`模块提供了`radians()`和`degrees()`函数,用于将角度转换为弧度,以及将弧度转换为角度。
import math

angle_in_degrees = 90
angle_in_radians = math.radians(angle_in_degrees)
print(f"{angle_in_degrees} degrees is {angle_in_radians} radians")

angle_in_radians = math.pi / 2
angle_in_degrees = math.degrees(angle_in_radians)
print(f"{angle_in_radians} radians is {angle_in_degrees} degrees")

进制位换算

13. 二进制(Binary):

在二进制中,每个位上的数字只能是0或1。0b前缀表示二进制。

binary_number = 0b1101
print(binary_number)  # 输出13(十进制)

14. 八进制(Octal):

在八进制中,每个位上的数字可以是0到7。0o前缀表示八进制。

octal_number = 0o17
print(octal_number)  # 输出15(十进制)

15. 十六进制(Hexadecimal):

在十六进制中,除了0-9,还使用A-F(或a-f)表示10-15。0x前缀表示十六进制。

hexadecimal_number = 0xA
print(hexadecimal_number)  # 输出10(十进制)

16. 进制转换:

如果你有一个数字的字符串表示,可以使用int()函数将其转换为十进制。同样,使用bin()oct()hex()函数将十进制数字转换为二进制、八进制和十六进制。

decimal_number = 42
binary_representation = bin(decimal_number)
octal_representation = oct(decimal_number)
hexadecimal_representation = hex(decimal_number)

print(f"Binary: {binary_representation}")
print(f"Octal: {octal_representation}")
print(f"Hexadecimal: {hexadecimal_representation}")

时间换算

17. 获取当前时间:

使用 datetime 模块的 datetime 类,可以获取当前的日期和时间。

from datetime import datetime

current_time = datetime.now()
print(current_time)

18. 时间差计算:

可以使用 timedelta 类来表示时间差。

from datetime import datetime, timedelta

current_time = datetime.now()
future_time = current_time + timedelta(days=7)

time_difference = future_time - current_time
print(f"Future time: {future_time}")
print(f"Time difference: {time_difference}")

19. 字符串与时间的相互转换:

将时间对象转换为字符串,或将字符串转换为时间对象。

from datetime import datetime

# 时间对象转换为字符串
current_time = datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted time: {formatted_time}")

# 字符串转换为时间对象
time_string = "2022-01-01 12:30:00"
converted_time = datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
print(f"Converted time: {converted_time}")

20. 时区处理:

如果需要处理时区,可以使用第三方库 pytz

# 需要先pip install pytz安装
from datetime import datetime
import pytz

# 获取带时区信息的时间
current_time_utc = datetime.now(pytz.utc)
print(f"Current time in UTC: {current_time_utc}")

# 转换时区
eastern_timezone = pytz.timezone('US/Eastern')
current_time_eastern = current_time_utc.astimezone(eastern_timezone)
print(f"Current time in Eastern Time: {current_time_eastern}")

年月日

21. 获取当前日期:

使用 datetime 模块的 date 类,可以获取当前的日期。

from datetime import date
   
   current_date = date.today()
   print(current_date)

22. 特定日期的创建:

可以使用 date 类来创建特定的日期。

from datetime import date

specific_date = date(2022, 1, 1)
print(specific_date)

23. 日期之间的差异计算:

使用 date 类和 timedelta 类来计算日期之间的差异。

from datetime import date, timedelta

current_date = date.today()
future_date = current_date + timedelta(days=30)

date_difference = future_date - current_date
print(f"Future date: {future_date}")
print(f"Date difference: {date_difference.days} days")

24. 字符串与日期的相互转换:

将日期对象转换为字符串,或将字符串转换为日期对象。

from datetime import date

# 日期对象转换为字符串
current_date = date.today()
formatted_date = current_date.strftime("%Y-%m-%d")
print(f"Formatted date: {formatted_date}")

# 字符串转换为日期对象
date_string = "2022-01-01"
converted_date = date.fromisoformat(date_string)
print(f"Converted date: {converted_date}")

加减法

25.日期加法:

from datetime import datetime, timedelta

current_date = datetime.now()
days_to_add = 5

new_date = current_date + timedelta(days=days_to_add)
print(f"Current date: {current_date}")
print(f"New date after adding {days_to_add} days: {new_date}")

26.日期减法:

from datetime import datetime, timedelta

current_date = datetime.now()
days_to_subtract = 3

new_date = current_date - timedelta(days=days_to_subtract)
print(f"Current date: {current_date}")
print(f"New date after subtracting {days_to_subtract} days: {new_date}")

27.结合日期和时间的加法和减法:

from datetime import datetime, timedelta

current_datetime = datetime.now()
hours_to_add = 2

new_datetime = current_datetime + timedelta(hours=hours_to_add)
print(f"Current datetime: {current_datetime}")
print(f"New datetime after adding {hours_to_add} hours: {new_datetime}")

28.xlsx每一行生成一个txt

import openpyxl

def xlsx_to_txt(file_path):
    # 加载xlsx文件
    workbook = openpyxl.load_workbook(file_path)
    # 假设数据在第一个工作表中
    sheet = workbook.active

    # 遍历每一行
    for row_num, row in enumerate(sheet.iter_rows(values_only=True), start=1):
        # 将每一行的内容写入对应的txt文件
        with open(f"{row_num}.txt", "w", encoding="utf-8") as txt_file:
            line_content = " ".join(str(cell) for cell in row if cell is not None)
            txt_file.write(line_content)

# 使用示例
xlsx_to_txt('2.xlsx')

在这里插入图片描述
在这里插入图片描述

  • 30
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XMYX-0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值