#定义函数fun,拥有参数x,判断x是否为平方数。
时间: 2024-02-25 22:52:18 浏览: 28
可以使用Python的math模块中的sqrt函数来判断一个数是否为平方数。代码如下:
```python
import math
def fun(x):
if math.sqrt(x).is_integer():
return True
else:
return False
```
函数中先导入了math模块,然后使用sqrt函数求出x的平方根,判断是否为整数,若为整数则返回True,否则返回False。
相关问题
定义函数fun1,用来判断n是否是质数
可以使用以下的函数定义来判断一个数是否是质数:
```
def fun1(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
```
这个函数的思路是,首先判断n是否小于2,如果小于2,则不是质数;否则,从2到n的平方根遍历所有的数字,判断n是否能够整除这些数字,如果能,说明n不是质数;否则,n是质数。
在函数中,使用了内置函数int()来将浮点数转换为整数,使用了运算符**来计算平方,使用了range()函数来遍历数字,使用了%运算符来进行取模运算。
可以通过调用这个函数来判断一个数是否是质数,例如:
```
print(fun1(7)) # True
print(fun1(12)) # False
```
输出结果分别为True和False。
定义一个函数fun(n),根据正整数参数n,返回其各位数字的平方和,并在主程序中调用。
以下是一个Python实现的函数fun(n):
```python
def fun(n):
"""
根据正整数参数n,返回其各位数字的平方和
"""
s = 0
while n > 0:
digit = n % 10
s += digit ** 2
n //= 10
return s
```
在主程序中,我们可以调用这个函数并输出结果:
```python
n = 123
print(fun(n)) # 输出14
```
以上程序会输出14,因为1^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)