python中sqrt的用法_Python math sqrt()用法及代码示例

sqrt()function是Python编程语言中的内置函数,可返回任何数字的平方根。

用法:

math.sqrt(x)

参数:

x is any number such that x>=0

返回:

It returns the square root of the number

passed in the parameter.

# Python3 program to demonstrate the

# sqrt() method

# import the math module

import math

# print the square root of  0

print(math.sqrt(0))

# print the square root of 4

print(math.sqrt(4))

# print the square root of 3.5

print(math.sqrt(3.5))

输出:

0.0

2.0

1.8708286933869707

错误:当x <0时,由于运行时错误而无法执行。

# Python3 program to demonstrate the error in

# sqrt() method

# import the math module

import math

# print the error when x<0

print(math.sqrt(-1))

输出:

Traceback (most recent call last):

File "/home/67438f8df14f0e41df1b55c6c21499ef.py", line 8, in

print(math.sqrt(-1))

ValueError:math domain error

实际应用:给定一个数字,检查其是否为质数。

方法:运行从2到sqrt(n)的循环,并检查范围(2-sqrt(n))中是否有任何数字除以n。

# Python program for practical application of sqrt() function

# import math module

import math

# function to check if prime or not

def check(n):

if n == 1:

return False

# from 1 to sqrt(n)

for x in range(2, (int)(math.sqrt(n))+1):

if n % x == 0:

return False

return True

# driver code

n = 23

if check(n):

print("prime")

else:

print("not prime")

输出:

prime

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值