编写一个函数,接收一个10位的数字串为参数,判断第7位到9位组成的三位数能否被5整除
时间: 2024-03-07 21:48:24 浏览: 18
好的,以下是Python函数实现:
```python
def is_divisible_by_5(num_str):
if len(num_str) != 10:
print("Error: num_str should be 10 digits long!")
return False
sub_num = num_str[6:9]
if int(sub_num) % 5 == 0:
return True
else:
return False
```
解释一下函数的思路:
首先,我们定义了一个名为 `is_divisible_by_5` 的函数,它接收一个字符串参数 `num_str`。该函数首先检查 `num_str` 的长度是否为10,如果不是,则输出错误信息并返回 `False`。
接着,我们从 `num_str` 中取出第7位到第9位组成的子串,并将其转换为整数类型。然后,我们检查该子串是否能被5整除,如果是,则返回 `True`,否则返回 `False`。
下面是一个示例,演示如何调用这个函数:
```python
num_str = "1234567890"
result = is_divisible_by_5(num_str)
print(result) # 输出:True
```
在这个示例中,我们将字符串 `1234567890` 作为参数传递给函数 `is_divisible_by_5`。由于该字符串的第7位到第9位组成的子串 `789` 能被5整除,因此函数返回 `True`,并将其保存在变量 `result` 中。最后,我们输出 `result` 的值,即 `True`。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)