python中计算n次方运算的四种方法

本文介绍了Python中实现幂运算的四种方式:基本语法`**`、内置`pow()`函数、对象的`__pow__()`方法以及使用`numpy`库的`power()`函数。通过示例代码展示了每种方法的用法,并且所有方法均得到相同的结果,即求2的平方。这为Python初学者提供了清晰的参考资料。
摘要由CSDN通过智能技术生成

这里介绍一下python中n次方运算的四种书写形式,代码如下:

# -*- coding:utf-8 -*-
"""
author: 15025
time: 10.08.2021   18:12:20
software: PyCharm

Description:
"""

import numpy as np


class PythonStudy:
    @staticmethod
    def powerAlgorithm():
        # basic python method
        x = 2
        x1 = x ** 2
        print(f"The value of x1 is {x1}")
        x2 = pow(x, 2)
        print(f"The value of x2 is {x2}")
        x3 = x.__pow__(2)
        print(f"The value of x3 is {x3}")
        # numpy method
        x4 = np.power(x, 2)
        print(f"The value of x4 is {x4}")


if __name__ == '__main__':
    main = PythonStudy()
    main.powerAlgorithm()
"""
输出结果:
The value of x1 is 4
The value of x2 is 4
The value of x3 is 4
The value of x4 is 4
"""

可以看到,四种方法均成功输出了我们想要的平方运算。

码字不易,如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

勤奋的大熊猫

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

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

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

打赏作者

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

抵扣说明:

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

余额充值