亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python计算平方的6种高效方法

利用Python内置库或函数可求数字平方。平方即数字自乘。本文汇总六种求平方途径。

方法1:pow()函数

pow属math模块内置函数,求幂。求平方指数设为2。

语法: pow(base, exponent)
# base: 底数 | exponent: 指数

示例:

Base = input("Provide base integer")
if Base.isdigit():
    Base = int(Base)
    result = pow(Base, 2)
    print("The square result is", result)
else:
    print("please provide an integer for base")

输出: The square result is 4(输入2)

方法2:幂运算符**

**为幂运算符,指数为2得平方。

语法: base ** exponent

示例:

Base = input("Provide base integer")
Exponent = input("Provide exponent integer")
if Base.isdigit() and Exponent.isdigit():
    Base = int(Base); Exponent = int(Exponent)
    result = Base ** Exponent
    print("The square result is", result)

方法3:直接乘法

语法: base * base

示例:

Base = input("Provide base integer")
if Base.isdigit():
    Base = int(Base)
    result = Base * Base
    print("The square result is", result)

方法4:列表批量求平方

列表存储多值,遍历逐个求平方。

sqr_list = [2,4,6,8]
for Base in sqr_list:
    result = Base ** 2
    print("The square result is", result)

输出: 4, 16, 36, 64

方法5:while循环累积求平方

n_start = 1
while n_start <= 5:
    result = n_start ** 2
    print("The square result is", result)
    n_start += 1

输出: 1, 4, 9, 16, 25

方法6:NumPy数组np.square()

import numpy as np
NumpyArray = np.array([2,4,6,8])
print("Square of elements:", np.square(NumpyArray))

输出: [4 16 36 64]

总结

Python

  1. Python round() 函数详解与实战示例
  2. Python 面向对象编程完全指南:从基础到进阶
  3. Python 图像处理库 Pillow 完全指南
  4. Flask 与 Django:核心差异、特性与框架选型指南
  5. Python 循环完全指南:for、while、break、continue、enumerate 详解
  6. Python打造井字游戏:分步代码教程
  7. 精通Python数据类型:实战指南
  8. Python 与 JavaScript:核心差异、特性及选型指南
  9. Python 面向对象编程基础:类、对象、继承与构造函数详解
  10. Django 入门指南:特性、架构、历史与核心组件全解析
  11. Python 函数详解:构建可复用代码模块的最佳实践
  12. 加入Real Python:创建账号解锁高级Python教程