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提供六大求平方方式
pow()来自math模块,适配函数式编程- NumPy数组适合科学计算批量处理
- 列表推导/遍历适合多数据场景
- 直接乘法最直观,幂运算符
**最通用 - 平方与平方根截然不同,勿混淆
Python
- Python round() 函数详解与实战示例
- Python 面向对象编程完全指南:从基础到进阶
- Python 图像处理库 Pillow 完全指南
- Flask 与 Django:核心差异、特性与框架选型指南
- Python 循环完全指南:for、while、break、continue、enumerate 详解
- Python打造井字游戏:分步代码教程
- 精通Python数据类型:实战指南
- Python 与 JavaScript:核心差异、特性及选型指南
- Python 面向对象编程基础:类、对象、继承与构造函数详解
- Django 入门指南:特性、架构、历史与核心组件全解析
- Python 函数详解:构建可复用代码模块的最佳实践
- 加入Real Python:创建账号解锁高级Python教程