1.此为GitHub项目的学习记录,记录着我的思考,代码基本都有注释。
2.可以作为Python初学者巩固基础的绝佳练习,原题有些不妥的地方我也做了一些修正。
3.建议大家进行Python编程时使用英语。
4.6~17题为level1难度,18-22题为level3难度,其余都为level1难度。
项目名称:
100+ Python challenging programming exercises for Python 3
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
Define a class named Shape and its subclass Square.
The Square class has an init function which takes a length as argument.
Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
"""
'''
Hints:
To override a method in super class, we can define a method with the same name in the super class.
'''
class Shape(object):
"""面积默认值为0"""
def __init__(self):
pass
def shape_area(self):
print('0')
class Square(object):
"""计算正方形的面积"""
def __init__(self, r):
self.length = r
def square_area(self):
x = self.length ** 2
print("The square's area is", x)
aShape = Square(6)
Square.square_area(aShape)
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
1.Please raise a RuntimeError exception.
2.Write a function to compute 5/0 and use try/except to catch the exceptions.
"""
'''Hints:
1.Use raise() to raise an exception.
2.Use try/except to catch exceptions.
'''
# 第一个问题
# raise RuntimeError("something is wrong") # raise函数引发异常
# 演示raise用法
"""try:
s = None
if s is None:
print("s 是空对象")
raise NameError('name wrong') # 如果引发NameError异常,后面的代码将不能执行
print(len(s)) # 这句不会执行,但是后面的except还是会走到
except TypeError:
print("空对象没有长度")
s = None
if s is None:
raise NameError
print('is here?') # 如果不使用try......except这种形式,那么直接抛出异常,不会执行到这里"""
# 第二个问题,
def throw_error():
return 5 / 0
try:
throw_error()
except ZeroDivisionError: # 在一个except语句只捕捉其后声明的异常类型,如果可能会抛出的是其他类型的异常就需要再增加一个except语句
print("divisor cannot be zero!")
except Exception: # 一个更通用的异常类型
print('caught an exception')
finally: # finally子句和try子句联合使用但是和except语句不同,finally不管try子句内部是否有异常发生,都会执行finally子句内的代码。
print('In finally block for cleanup')
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*--
"""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:
john@google.com
Then, the output of the program should be:
john
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.
'''
import re
email_address = input('Please input your email address:')
parted = re.compile(r'(\w+)@((\w+.)(com))') # 创建了一个pattern对象格式
match = parted.match(email_address) # 按照创建的pattern对象进行匹配
print(match.groups()) # 返回匹配成功的子串
"""
>>> print (match) # 匹配成功,返回一个 Match 对象
<re.Match object; span=(0, 14), match='lily@gmail.com'>
>>> match.group(0) # 返回匹配成功的整个子串
‘lily@gmail.com’
>>> match.span(0) # 返回匹配成功的整个子串的索引
(0, 14)
>>> match.group(1) # 返回第一个分组匹配成功的子串
‘lily’
>>> match.span(1) # 返回第一个分组匹配成功的子串的索引
(0, 4)
>>> match.group(2) # 返回第二个分组匹配成功的子串
‘gmail.com’
>>> match.span(2) # 返回第二个分组匹配成功的子串
(5, 11)
>>> match.groups() # 等价于 (match.group(1), match.group(2), …)
('lily', 'gmail.com', 'gmail.', 'com')
>>> match.group(3) # 返回第3个分组匹配成功的子串
gmail.
>>> match.group(4) # 返回第4个分组匹配成功的子串
com
>>> match.group(5) # 没有第5个分组的子串
print(match.group(5)) #
IndexError: no such group
"""
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
Assuming that we have some email addresses in the "username@companyname.com" format,
please write program to print the company 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:
john@google.com
Then, the output of the program should be:
google
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.
'''
import re
email_address = input('Please input your email address:')
parted = re.compile(r'(\w+)@((\w+).(com))') # 创建了一个pattern对象格式
match = parted.match(email_address) # 按照创建的pattern对象进行匹配
print(match.group(3)) # 返回匹配成功的子串
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
Write a program which accepts a sequence of words separated by whitespace as input
to print the words composed of digits only.
Example: If the following words is given as input to the program:
2 cats and 3 dogs.
Then, the output of the program should be:
['2', '3']
In case of input data being supplied to the question, it should be assumed to be a console input.
"""
'''
Hints:
Use re.findall() to find all substring using regex.
'''
import re
temp = input('Please input your words:')
pat1 = re.compile(r'\d+') # 建立一个正则表达式匹配格式
z = pat1.findall(temp) # findall()函数搜索整个字符串并返回所有匹配结果
print(z)
# 源代码,更加简洁,进阶写法
'''import re
s = input()
print(re.findall(r'\d+', s))'''
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
Print a unicode string "hello world".
"""
'''
Hints:
Use u'strings' format to define unicode string.
'''
unicodeString = u'Hello,world!'
print(unicodeString)
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.
"""
'''
Hints:
Use str.encode().decode()
'''
s = u'\u4f60\u597d' # 输入ASCII码
u = s.encode("utf-8").decode("utf-8") # 将ASCII码进行UTF-8格式的编码和解码
print(u)
"""
unicode.encode() -> bytes:只有对于unicode对象我们才应该使用.encode()方法。这一方法用来将一系列unicode编码为bytes流。
bytes.decode() -> unicode: 只有对于bytes,或说Python2中的str对象,我们才应该调用.decode()方法。
这一方法将一系列bytes流解码为原本的unicode码点。
"""
#!usr/bin/env Python3.9
# -*- coding:utf-8 -*- # 这一行就是该问题的答案
"""
Write a special comment to indicate a Python source code file is in unicode.
(写一个特殊的注释来表明Python源代码文件是unicode格式的。)
"""
#!usr/bin/env Python3.9
# -*- coding:utf-8 -*-
"""
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
Example: If the following n is given as input to the program:
5
Then, the output of the program should be:
3.55
"""
'''
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints: Use float() to convert an integer to a float
'''
i = 1
sum = 0.0
n = int(input('Please input a number:'))
while i < n: # while条件语句
sum += 1 / n # 求和
n -= 1
print(float(sum)) # 利用float()函数将int类型转为浮点数类型
# 源代码,更加简洁高级
"""n = int(input())
sum = 0.0
for i in range(1, n + 1): # for循环语句
sum += float(float(i) / (i + 1))
print(sum)"""
#!usr/bin/env Python3.9
# -*- coding:utf-8 -*-
"""
Write a program to compute:
f(n)=f(n-1)+100 when n>0 and f(0)=1
with a given n input by console (n>0).
Example: If the following n is given as input to the program:
5
Then, the output of the program should be:
500
"""
'''
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
We can define recursive function in Python.
'''
"""
def common_cal():
f = 0
n = int(input("Please input a number:"))
for i in range(1, n+1): # for 循环
f += 100 # 加100
print(f)
common_cal() # 调用函数
"""
# 源代码,递归思想
def f(n):
if n == 0:
return 0
else:
return f(n - 1) + 100 # 在函数内部调用自身函数,即递归思想
n = int(input())
print(f(n))
# 附加示例,斐波那契数列
"""
#第一个数字是一,第二个数字也是一,从第三个开始,每一个数字等于前俩个数字相加的和
#公式为:f(1)=1,f(2)=1,f(n)=f(n-1)+f(n-2) 例如:1,1,2,3,5,8,13....
def fib(N):
if N == 1:
return 1
if N < 1:
return 1
return fib(N-1)+fib(N-2)
print(fib)
"""
第六期先到这儿,共十期。
“自主学习,快乐学习”
再附上Python常用标准库供大家学习使用:
Python一些常用标准库解释文章集合索引(方便翻看)
“学海无涯苦作舟”