用python写要求输入一串数字 判断是否为手机号
时间: 2023-05-20 15:06:58 浏览: 134
可以使用正则表达式来判断是否为手机号,以下是示例代码:
import re
def is_phone_number(number):
pattern = r'^1[3-9]\d{9}$'
if re.match(pattern, number):
return True
else:
return False
number = input("请输入一个数字:")
if is_phone_number(number):
print("这是一个手机号")
else:
print("这不是一个手机号")
相关问题
Python用户输入由一组手机号码构成的列表(元素为字符串)编写程序判断它们是否符合手机号码的规则,即由11为阿拉伯数字组成,先判断字符串位数是否正确,如果不对则输出wrong weishu;如果字符串包含非数字字符则输出wrong char,如果符合要求则输出ok。输出分行显示。定义2个Exception的子类WeishuError和CharError,分别处理上述2种异常
好的,我理解了你的问题。以下是 Python 代码实现:
```python
class WeishuError(Exception):
pass
class CharError(Exception):
pass
phone_numbers = input("请输入手机号码列表,用逗号隔开:").split(",")
for phone_number in phone_numbers:
try:
if len(phone_number) != 11:
raise WeishuError("wrong weishu")
elif not phone_number.isdigit():
raise CharError("wrong char")
else:
print("ok")
except WeishuError as e:
print(e)
except CharError as e:
print(e)
```
代码解释:
- 首先定义了两个异常类 WeishuError 和 CharError,分别用于处理位数错误和非数字字符错误。
- 用户输入手机号码列表,使用 `split` 方法将字符串转换为列表。
- 遍历列表,对每一个手机号码进行判断。
- 如果手机号码长度不是 11,则抛出 WeishuError 异常。
- 如果手机号码包含非数字字符,则抛出 CharError 异常。
- 如果手机号码符合要求,则输出 "ok"。
- 使用 try-except 语句捕获异常,如果出现异常则输出相应的错误信息。
用python编写程序,用户输入由一组手机号码构成的列表(元素为字符串),编写程序判断它们是否符合手机号码的规则,即由11位阿拉伯数字组成。先判断字符串位数是否正确,如果不对则输出wrong weishu;如果字符串包含非数字字符则输出wrong char,如果符合要求则输出ok。输出分行显示。定义2个Exception的子类WeishuError和CharError,分别处理上述2种异常。
好的,以下是你需要的程序代码:
```python
class WeishuError(Exception):
pass
class CharError(Exception):
pass
def check_phone_numbers(numbers):
for number in numbers:
try:
if not number.isdigit():
raise CharError
if len(number) != 11:
raise WeishuError
print("ok")
except WeishuError:
print("wrong weishu")
except CharError:
print("wrong char")
numbers = input("请输入由一组手机号码构成的列表(用逗号分隔):").split(",")
check_phone_numbers(numbers)
```
你可以将一组手机号码以逗号分隔的形式输入,程序会自动判断每个手机号码是否符合要求并输出相应的结果。如果有任何不明白的地方,可以随时向我提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)