Python打卡Day14
Question 51
Question
Write a function to compute 5/0 and use try/except to catch the exceptions.
Hints
Use try/except to catch exceptions.
Main author's Solution: Python 2
1def throws():
2 return 5/0
3
4try:
5 throws()
6except ZeroDivisionError:
7 print "division by zero!"
8except Exception, err:
9 print 'Caught an exception'
10finally:
11 print 'In finally block for cleanup'
My Solution: Python 3
1def divide():
2 return 5/0
3
4try:
5 divide()
6except ZeroDivisionError as ze:
7 print("Why on earth you are dividing a number by ZERO!!")
8except:
9 print("Any other exception")
Question 52
Question
Define a custom exception class which takes a string message as attribute.
Hints
To define a custom exception, we need to define a class inherited from Exception.
Main author's Solution: Python 2
1class MyError(Exception):
2 """My own exception class
3
4 Attributes:
5 msg -- explanation of the error
6 """
7
8 def __init__(self, msg):
9 self.msg = msg
10
11error = MyError("something wrong")
My Solution: Python 3
1
2class CustomException(Exception):
3 """Exception raised for custom purpose
4
5 Attributes:
6 message -- explanation of the error
7 """
8
9 def __init__(self, message):
10 self.message = message
11
12
13num = int(input())
14
15try:
16 if num < 10:
17 raise CustomException("Input is less than 10")
18 elif num > 10:
19 raise CustomException("Input is grater than 10")
20except CustomException as ce:
21 print("The error raised: " + ce.message)
Question 53
Question
Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only.
Example: If the following email address is given as input to the program:
1john@google.com
Then, the output of the program should be:
1john
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints
Use \w to match letters.
Main author's Solution: Python 2
1import re
2emailAddress = raw_input()
3pat2 = "(\w+)@((\w+\.)+(com))"
4r2 = re.match(pat2,emailAddress)
5print r2.group(1)
My Solution: Python 3
1email = "john@google.com"
2email = email.split('@')
3print(email[0])
OR
1import re
2
3email = "john@google.com elise@python.com"
4pattern = "(\w+)@\w+.com"
5ans = re.findall(pattern,email)
6print(ans)