100+Python挑战性编程练习系列 -- day 14
Question 51
编写一个函数来计算5/0,并使用try/except来捕获异常。
def divide(): return 5/0 try: divide() except ZeroDivisionError as ze: print("Why on earth you are dividing a number by ZERO!!") except: print("Any other exception") Question 52
定义一个自定义的异常类,它接受一个字符串消息作为属性.
class CustomException(Exception): """Exception raised for custom purpose Attributes: message -- explanation of the error """ def __init__(self, message): self.message = message num = int(input()) try: if num < 10: raise CustomException("Input is less than 10") elif num > 10: raise CustomException("Input is grater than 10") except CustomException as ce: print("The error raised: " + ce.message) Question 53
假设我们有一些“www.example.com”格式的电子邮件地址[email protected],请编写程序来打印给定电子邮件地址的用户名。用户名和公司名都只由字母组成。
示例:如果将以下电子邮件地址作为程序的输入:
然后,程序的输出应该是:
john
如果输入数据被提供给问题,则应假设它是控制台输入。
email = "[email protected]" email = email.split('@') print(email[0]) import re email = "[email protected] [email protected]" pattern = "(\w+)@\w+.com" ans = re.findall(pattern,email) print(ans)