Python中math.sqrt()方法详解:如何计算平方根及其实际应用
sqrt() 方法返回 x 的平方根 (x>0)。

语法
以下是 sqrt() 方法的语法:
导入 mathmath.sqrt(x)
注意:该函数不能直接访问,所以我们需要导入math模块,然后使用math的静态对象来调用该函数。
范围
x——这是一个数值表达式。
返回值
当 x>0 时,此方法返回 x 的平方根。
例子
以下示例显示了 sqrt() 方法的使用。
#!/usr/bin/pythonimport math # 这将导入数学模块print "math.sqrt(100) : ", math.sqrt(100)print "math.sqrt(7) : ", math.sqrt(7)print " math.sqrt(math.pi) : ", math.sqrt(math.pi)
当我们运行上面的程序时,它会产生以下结果:
数学.sqrt(100) : 10.0数学.sqrt(7) : 2.64575131106数学.sqrt(数学.pi) : 1.77245385091
round() 方法返回 x 四舍五入到 n 位的小数点。
语法
以下是 round() 方法的语法:
轮( x [, n] )
范围
x --这是一个数值表达式 n --这也是一个数值表达式
返回值
此方法返回 x 的小数点四舍五入到 n 位
例子
下面的例子展示了round()方法的使用
#!/usr/bin/pythonprint "round(80.23456, 2) : ", round(80.23456, 2)print "round(100.000056, 3) : ", round(100.000056, 3)print "round(-100.000056, 3) :“,圆形(-100.000056, 3)
当我们运行上面的程序时,它会产生以下结果:
回合(80.23456, 2) : 80.23回合(100.000056, 3) : 100.0回合(-100.000056, 3) : -100.0
choice() 方法从列表、元组或字符串中返回一个随机项。
语法
以下是 choice() 方法的语法:
选择(顺序)
注意:该函数不能直接访问,所以我们需要导入random模块,然后需要使用random对象来调用该函数。
范围
seq – 这可能是列表、元组或字符串...
返回值
此方法返回一个随机项。
例子
以下示例显示了 choice() 方法的使用。
#!/usr/bin/pythonimport randomprint "choice([1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9])print "choice('A String) ') : ", random.choice('A String')
当我们运行上面的程序时,它会产生以下结果:
choice([1, 2, 3, 5, 9]) : 2choice('A String') : n