A learning tutorial of Python for intro level learners

This is a learning tutorial of Python for intro level learners.
转载自https://qingdoulearning.gitbook.io/project/
0.前期准备
1.Variables and Types - - String and Number变量和数据类型——字符串和数字
2.Operators操作符
3.List列表
4.Dictionary字典
5.Tuple元组
6.Build-In Function - slice()方法
7.Conditions条件
8.Iterations迭代
9.Functions方法
10.Classes and Objects类和对象
11.Sets集合
12.Iterators迭代器
13.Modules and Packages模块和包
14.Generators生成器
15.Serialization
16.Regular Expressions (1)正则表达式
17.Inheritance
18.Handling Exception
19.Regular Expressions (2)
20.Regular Expressions (3)

0.前期准备

请确保你的电脑上已经安装好了:
✅ Python3
✅ 一个任意类型的text editor/IDE
视频小教程中我会使用sublime。我的建议是一开始学习尽量不用带auto complete功能的text editor,因为初级阶段我们学到的syntax都是最基本最简单的,培养自己的手感很重要。

Bonus Point:
✅ 在电脑上新建一个叫30DaysOfPython的文件夹
✅ 会用terminal/command prompt运行程序

我也会在第一天的小视频里带大家走完这几步喔,敬请期待~

disclaimer:
我们的教程会出现中英文混杂的情况,先跟大家说抱歉。中英文混着用的原因,一是很多编程的概念用英文解释会更准确些,但有些时候又担心全英文的大家会看不懂,所以混杂了一下中文。学编程的话,基本的英文也是基础喔,读教程就当也是一种练习吧_
如果有不懂的地方,欢迎评论/私信留言提问。

1.Variables and Types - - String and Number变量和数据类型——字符串和数字

Variables – 变量

A variable is a name that refers to a value. In computer programs, variables are reserved memory locations to store values. Python is completely object oriented, and not “statically typed”. You do not need to declare variables before using them, or declare their type. Every variable in Python is an object.

Objects – 对象

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects.

Every object includes:
1.Identity: object’s address in memory, an object’s identity never changes once it has been created.
2.Type: type of an object, such as String, Number, etc.
3.Value

>>> bob = 'cat'                   

上面这个statement里面,bob是variable name, 'cat’是一个类型为string的object. 当我们用 = 把这两个联系在一起时,本质上我们是把‘cat’这个object assign给了bob这个变量。为了更好得理解object这个概念,试试以下的代码

>>> bob = 'cat'
>>> print(type(bob))
>>> print(id(bob))
>>> print(id('cat'))
>>> bob = 'dog'
>>> print(id(bob)) #对比一下第六行的结果和第三行有什么不同
>>> bob = 1
>>> print(type(bob)) #对比一下第八行的结果跟第二行有什么不同

Types – 数据类型

There are many data types in Python, for starter, we will introduce two of them, String and Number.

String

A string is a sequence of characters

>>> day1 = 'learning python'                                                                   
>>> print(type(day1))                                                                  
>>> print(len(day1))

Number

Python supports two types of numbers - integers and floating point numbers. It also supports complex numbers, which will not be covered here.

>>> i = 365
>>> print(type(i))
>>> f = 3.14159
>>> print(type(f))

2.Operators操作符

基于变量有很多操作,我们只介绍最简单也最常见的几种。

输出 – print

>>> print("Hello Python world!")
>>> day2 = 'Today we will learn operators'
>>> print(day2)

输入 – input

>>> num = input("Please input your favourite number:")
>>> print("Your favourite number is:", num)

加减乘除

>>> a = 2
>>> b = 3
>>> sum1 = a + b
>>> sum2 = a - b
>>> sum3 = a * b
>>> sum4 = a / b

乘方

>>> 3 ** 2
9
>>> 3 ** 3
27

数字转化成字符串

我们先来看一个错误例子

>>> year = 2019
>>> message = "This year is " + year
>>> print(message)

可以试着在python中输入上面例子,然后看报错。

TypeError: can only concatenate str (not "int") to str

这是一个典型的类型错误,意味着Python无法识别信息。在字符串中使用整数时,需要显式地指出希望Python将这个整数用作字符串。为此,可调用str()函数,它会让Python将非字符串值表示为字符串:

year = 2019
message = "This year is " + str(year)
print(message)
This year is 2019

3.List列表

Python Collections --容器

There are four collections data type in Python: List, Tuple, Set and Dictionary. Today, we will introduce list.

List --列表

List is a collection which is ordered and changeable. In Python, lists are written with square brackets.

Create a List --创建列表

>>> thislist = ["apple","banana","cherry"]
>>> print(thislist)
['apple', 'banana', 'cherry']

Access Items --访问列表中元素

列表中访问元素的方法和数组类似。注意列表中元素的位置是从0开始计数的。
打印列表中的第二个元素:

>>> thislist = ["apple","banana","cherry"]
>>> print(thislist[1])
banana

Change Item Value --改变列表中元素

通过直接赋值的方法来更改列表中的元素。
改变列表中第二个元素:

>>> thislist = ["apple","banana","cherry"]
>>> thislist[1] = "blackcurrant"
>>> print(thislist)
['apple', 'blackcurrant', 'cherry']

Add Items --添加元素

append()

To add an item to the end of the list, use the append() method:
将元素添加到列表末尾

>>> thislist = ["apple","banana","cherry"]
>>> thislist.append("orange")
>>> print(thislist)
['apple', 'banana', 'cherry', 'orange']

insert()

To add an item to the specified index, use the insert() method:
将元素添加到列表中第二个位置

>>> thislist = ["apple","banana","cherry"]
>>> thislist.insert(1, "orange")
>>> print(thislist)
['apple', 'orange', 'banana', 'cherry']

Remove Item --删除元素

remove()

当你不知道要从列表中删除的值所处的位置而只知道要删除的元素的值,使用remove()

>>> thislist = ["apple","banana","cherry"]
>>> thislist.remove("banana")
>>> print(thislist)
['apple', 'cherry']

pop()

删除列表中特定位置的元素, 注意pop()会自动print出被pop out的元素

>>> thislist = ["apple","banana","cherry"]
>>> thislist.pop(1)
'banana' 
>>> print(thislist)
['apple', 'cherry']

删除最后一个元素

>>> thislist = ["apple","banana","cherry"]
>>> thislist.pop()
'cherry'
>>> print(thislist)
['apple', 'banana']

del

删除特定位置元素

>>> thislist = ["apple","banana","cherry"]
>>> del thislist[0]
>>> print(thislist)
['banana', 'cherry']

Sort List --对列表永久性排序

按照列表中元素的字母排序。

>>> thislist = ["apple","cherry","banana"]
>>> thislist.sort()
>>> print(thislist)
['apple', 'banana', 'cherry']
>>> thislist = [1, 8, -3, 4]
>>> thislist.sort()
>>> print(thislist)
[-3, 1, 4, 8]

Sorted List --对列表进行临时性排序

保留列表中元素的排列顺序,同时以特定的顺序呈现它们。这并不影响它们在列表中的原始排列顺序。

>>> thislist = ["apple", "cherry", "banana"]
>>> print("Here is the original list: ", thislist)
Here is the original list:  ['apple', 'cherry', 'banana']
>>> print("Here is the temporary sorted list: ", sorted(thislist))
Here is the temporary sorted list:  ['apple', 'banana', 'cherry']
>>> print("Here is the original list again : ", thislist)
Here is the original list again :  ['apple', 'cherry', 'banana']

看出来这三个print statement之间的区别了吗?

Reverse List --翻转列表

按照列表原来的顺序进行翻转

>>> thislist = ["apple","cherry","banana"]
>>> thislist.reverse()
>>> print(thislist)
['banana', 'cherry', 'apple']

len() – 确定列表长度
用len()函数可以快速确定列表的长度

>>> thislist = ["apple","cherry","banana"]
>>> len(thislist)
3

4.Dictionary字典

A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionary is written with curly brackets, and they are keys and values.

Create a Dictionary --创建字典

>>> thisdict = {"brand": "Ford",
                "model": "Mustang",
                "year": 1964}
>>> print(thisdict)

Access Items – 获取字典中元素

You can access the items of a dictionary by referring to its key name, inside square brackets:

>>> x = thisdict["model"]

使用get()函数也可以获取元素

>>> x = thisdict.get("model")

Change Values --改变字典中元素

You can change the value of a specific item by referring to its key name:

#Change the “year” to 2018

>>> thisdict = {"brand": "Ford",
                "model": "Mustang",
                "year": 1964}
>>> thisdict["year"] = 2018

Dictionary Length --获取字典长度

>>> print(len(thisdict))

Add Items --添加元素

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

>>> thisdict = {"brand": "Ford",
                "model": "Mustang",
                "year": 1964}
>>> thisdict["color"] = "red"
>>> print(thisdict)

Remove Items – 删除元素

pop()

The pop() method removes the item with the specified key name:

>>> thisdict = {"brand": "Ford",
                "model": "Mustang",
                "year": 1964}
>>> thisdict.pop("model")
>>> print(thisdict)

popitem()

The popitem() method removes the last inserted item:

>>> thisdict = {"brand": "Ford",
                "model": "Mustang",
                "year": 1964}
>>> thisdict.popitem()
>>> print(thisdict)

del

The del keyword removes the item with the specified key name:

>>> thisdict = {"brand": "Ford",
                "model": "Mustang",
                "year": 1964}
>>> del thisdict["model"]
>>> print(thisdict)

5.Tuple元组

A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.

Create a tuple

>>> aTuple = ('a', 'b', 'c', 'd')
>>> print(aTuple)
('a', 'b', 'c', 'd')

To create a tuple with a single element, you have to include a final comma:

>>> s1 = 'yay'
>>> type(s1)
<class 'str'>
>>> t1 = 'yay',
>>> type(t1)
<class 'tuple'>

Accessing values in Tuple

>>> t2 = ('python', 'java', 'php', 2012, 3.14)
>>> print(t2[2])
php
>>> print(t2[1:3])
('java', 'php')

Updating Tuple

Tuples are immutable, which means the values of tuple elements cannot be updated or changed. However, we can take portions of existing tuples to create new ones.

>>> t3 = ('monday', 'tuesday')
>>> t4 = ('wednesday', 'thursday')
>>> t5 = t3 + t4
>>> print(t5)
('monday', 'tuesday', 'wednesday', 'thursday')
​

Delete Tuple

Removing individual tuple elements is not possible. Use del to explicitly remove an entire tuple.

>>> t6 = (1, 3, 5, 'a', 'c', 'e')
>>> del t6
>>> print(t6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 't6' is not defined

Basic Tuple Operations

len

>>> t7 = (2, 0, 1, 9)
>>> print(len(t7))
4

+

>>> t8 = ('Bohemian',)
>>> t9 = ('Rhapsody', 'Rami', 'Malek')
>>> t10 = t8 + t9
>>> print(t10)
('Bohemian', 'Rhapsody', 'Rami', 'Malek')

*

>>> t11 = ('hi',) * 3
>>> print(t11)
('hi', 'hi', 'hi')

in

>>> t12 = ('a', 'c', 'e')
>>> print('b' in t12)
False
>>> print('e' in t12)
True

6.Build-In Function - slice()方法

Python has a lot of built-in functions, slice() is one of the most useful built-in functions.

What does slice() do?
slice() returns a slice object representing the set of indices specified by a range.Slice object usually contains a portion of a sequence. A slice is created using the subscript notation, [] with colons between numbers.
通俗地说,slice就好比说把一串东西切开,留下其中的一部分。

Parameters in slice()

slice(start, end, step)

start: an integer number specifying at which position to start the slicing. Default is 0. OPTIONAL

end: an integer number specifying at which position to end the slicing

step: an integer number specifying the step of the slicing. Default is 1. OPTIONAL

Example

Example 1

>>> tup1 = ('bad', 'money', 'drives', 'out', 'good')
>>> x = slice(0,2)
>>> print(tup1[x])
('bad', 'money')

这个例子里,我们从0开始,到2为止,记住slice的结果不包含终止位置的item!

Example 2

>>> tup2 = ('a', 'b', 'c', 'd', 'e', 'f', 'g')
>>> x = slice(0,7,2)
>>> print(tup2[x])
('a', 'c', 'e', 'g')

这个例子包含了start,end,step,从0开始,到7为止,每两个item一次slice。

Example 3

>>> tup3 = ('try', 'harder', 'to', 'be', 'brave')
>>> x = slice(2)
>>> print(tup3[x])
('try', 'harder')

上面我们说过,只有end是必须的parameter,start 和 step 都是optional,如果没有,slice() function会直接使用默认值。
更简单的方法,是直接使用[]来进行slice。
[start : end]

Example 4

>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l2 = l1[2:4]
>>> print(l2)
[3, 4]

我们把l1这个list,从index位置为2开始,到index为4为止进行slice。记住slice的结果不包含终止位置的item!

Example 5

>>> l1 = [1, 2, 3]
>>> l2 = l1[1:]
>>> print(l2)
[2, 3]

冒号前面是start index,后面没有就默认为至末尾。

Example 6

>>> l1 = [1, 2, 3]
>>> l2 = l1[:2]
>>> print(l2)
[1, 2]

冒号也可以只写end index,前面没有就默认从index 0开始。

7.Conditions条件

Python users boolean variables to evaluate conditions.

Boolean values include True and False. A boolean value will be returned when an expression is compared or evaluated.

Relational Operators

== != > < >= <=
These operators are pretty self-explanatory, try to figure out their meanings by using examples below

>>> 5 == 5
True
>>> 5 == 6
False
>>> 5 > 3
True
>>> 5 < 2
False
>>> 4 >= 4
True
>>> 4 <= 5
True

ATTN: = is an assignment operator, and == is a relational operator. They are VERY different.

Logical Operators

and , or , not
Use some examples to understand these operators:

>>>3 > 2 and 3 > 1
True
>>>3 > 2 and 3 < 1
False
>>>3 > 2 or 3 < 1
True
>>>3 is not 2
True

The “in” Operator

The in operator can be used to check if a specific object exists within an iterable object container, such as a list:

>>>name = "jon"
>>>name in ["jon", "snow"]
True
>>>if name in ['robb', 'sansa', 'arya', 'bran', 'rickon']:
... print('yay')
...else:
... print('oops')
...
oops

Pay attention to the usage of if…else…block, we will be talking about these in the future. Python users indentation to define code blocks, that’s why you need to indent before the print in above example. We will also see more of these in the future.

8.Iterations迭代

There are two types of loops in Python, for loop and while loop. Computers are often used to do repeating identical or similar tasks.

“for” loop

For loops iterate over a given sequence, meaning Python will count/check each item within a sequence.

For loop over a string

>>> word = 'universe'
>>> count = 0
>>> for letter in word:
...     if letter == 'e':
...         count += 1
>>> print(count)
2

For loop over a list:

>>> nums = [1, 3, 5, 6, 8, 9]
>>> for n in nums:
...     if n % 2 == 0:
...         print(n)
6
8

For loop can integrate over a sequence of numbers using the “range” function. Range function is zero based.

range(start, end, step)

start is optional, default is 0.

end is required.

step is optional, default is 1.

>>> for x in range(5):
...     print(x)
0
1
2
3
4
>>> for x in range(4, 8):
...     print(x)
4
5
6
7
>>> for x in range(1, 9, 3):
...     print(x)
1
4
7

“while” loop

While loops repeat as long as a certain boolean condition is met. To understand this easily, it can been seen as “while the condition is true, do something.”

The flow of execution for a while statement looks like this:

evaluate the condition, True of False -> if condition is false, exit the while statement -> if the condition if true, execute the body and the go back to the condition evaluation

>>> count = 0
>>> while count < 5:
...     print(count)
...     count+=1
0
1
2
3
4

9.Functions函数

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

Create a Function --创建函数

在python中,用def来定义一个函数:

>>> def my_function():
>>>     print("Hello Miss Giraffe!")

Call a Function --调用函数

>>> def my_function():
>>>     print("Hello Miss Giraffe!")
>>> my_function()
​
Hello Miss Giraffe!

Parameters --参数

Information can be passed to functions as parameter.
我们先看下面的例子:

>>> def my_function(username):
    >>> print("Hello, " + username.title() + ".")
>>> my_function('giraffe')
>>> my_function('lion')
>>> my_function('hurricane')
​
Hello Giraffe.
Hello Lion.
Hello Hurricane.

username是一个形参,函数完成其工作所需的一项信息。

调用my_function函数时,传入的"giraffe", “lion”, "hurricane"是实参,这是传递给函数的信息。我们在调用函数时,将要让函数使用的信息放在括号里。

传递实参

我们介绍三种方式传递实参。

1.位置实参

Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。最简单的方式是基于实参的顺序,这种方式叫做位置实参。

>>> def describe_pet(animal_type, pet_name):
    >>> print("\nI have a " + animal_type + ".")
    >>> print("My " + animal_type + "'s name is " + pet_name.title() + ".")
>>> describe_pet('dog', 'latte')
I have a dog.
My dog's name is Latte.

2.关键字实参

关键字实参是传递给函数的名称—值对。直接在实参中就将名称和值关联起来。

>>> def describe_pet(animal_type, pet_name):
    >>> print("\nI have a " + animal_type + ".")
    >>> print("My " + animal_type + "'s name is " + pet_name.title() + ".")
>>> describe_pet(animal_type='dog', pet_name='latte')
I have a dog.
My dog's name is Latte.

3.默认值

编写函数时,可以给每个形参指定默认值。在调用函数时,如果给形参提供了实参,就使用提供的实参值,否则,就是用形参的默认值。

>>> def describe_pet(animal_type='dog', pet_name):
    >>> print("\nI have a " + animal_type + ".")
    >>> print("My " + animal_type + "'s name is " + pet_name.title() + ".")
>>> describe_pet(pet_name='latte')
I have a dog.
My dog's name is Latte.
​
>>> describe_pet(animal_type='cat', pet_name='milk')
I have a cat.
My cat's name is Milk.

Return Values --返回值

To let a function return a value, use the return statement.

>>> def my_function(x):
    >>> return 5 * x
>>> print(my_function(3))
>>> print(my_function(5))
>>> print(my_function(9))
​
15
25
45

10.Classes and Objects类和对象1

在这里插入图片描述

11.Classes and Objects类和对象2

在这里插入图片描述

12.Sets集合

Set is one of the data types in Python. A set is an unordered collection with no duplicate elements. People use sets to eliminate duplicate entries, or fast membership testing.
它最大的功能是帮助我们deduplicate(去重)

Create sets

Method 1: use {}

>>> colors = {'red', 'green', 'blue', 'blue', 'red'}
>>> print(colors)
{'green', 'red', 'blue'} 
#注意你得到的结果可能跟上一行不一致,因为set里面的element是unordered
>>> 'green' in colors
True
>>> 'purple' in colors
False

Method 2: use set() function

>>> aSet = set('abbbacdgzsgggz')
>>> aSet
{'s', 'z', 'c', 'a', 'g', 'd', 'b'}
>>> bSet = set('yoyoyoyoy')
>>> bSet
{'o', 'y'}

Set operations

Union -> get a set of all the unique elements from two sets

>>> a = set('lll')
>>> b = set('gzzqz')
>>> a.union(b)
{'z', 'q', 'l', 'g'}
>>> a | b
{'z', 'q', 'l', 'g'}

Intersection -> get the unique elements appear in both sets

>>> c = set(['March', 'April', 'May', 'June', 'May'])
>>> d = set(['May', 'June', 'July', 'May'])
>>> c.intersection(d)
{'May', 'June'}
>>> c & d
{'May', 'June'}

Difference -> get the unique element(s) that appear in one set and not the other, pay attention to the order

>>> e = set(['apple', 'google', 'facebook'])
>>> f = set(['apple', 'amazon', 'dropbox'])
>>> e.difference(f)
{'facebook', 'google'}
>>> e - f
{'facebook', 'google'}
>>> f.difference(e)
{'dropbox', 'amazon'}
>>> f - e
{'dropbox', 'amazon'}

Symmetric difference -> get the unique element(s) that appear in only one of the sets, order doesn’t matter here

>>> g = set(['sunday', 'monday', 'tuesday'])
>>> h = set(['sunday', 'friday'])
>>> g.symmetric_difference(h)
{'tuesday', 'friday', 'monday'}
>>> h.symmetric_difference(g)
{'tuesday', 'friday', 'monday'}
>>> g ^ h
{'tuesday', 'friday', 'monday'}

13.Iterators迭代器

An iterator is an object that contains a countable number of values. It can be iterated upon, which means you can traverse through all the values in this object.

Lists, Tuples, Dictionaries, and Sets are all iterable objects, they are iterable containers that you can get an iterator from.

Use iter()method to get an iterator:

>>> aList = ['Tim Apple', 'Jeff Amazon', 'Mark Facebook']
>>> aListIter = iter(aList)
>>> print(next(aListIter))
Tim Apple
>>> print(next(aListIter))
Jeff Amazon
>>> print(next(aListIter))
Mark Facebook

Now, you can create your own iterator for Tuples, Dictionaries, and Sets in the same way as the example above. Give a try!!!

Strings are also iterable objects, containing a sequence of characters. Thus we can create iterator for Strings as well.

>>> aString = "ErinacusEuropaeus"
>>> aStringIter = iter(aString)
>>> print(next(aStringIter))
E
...
#I'll skip the printing results here

Looping Through an iterable objects

We can also use for loop to iterate through an iterable objects:

>>> aTuple = ('pot', 'pan', 'boiler')
>>> for x in aTuple:
...     print(x)
pot
pan
boiler

Now it’s your turn to try using for loop to iterate through other types of iterable objects.

14.Modules and Packages模块和包

在这里插入图片描述

15.Generators生成器

一个普通的Python函数经常返回一个值,无论是List、Number还是其他对象。
但是如果想调用一个函数,并让这个函数产生一系列的值,这就需要使用生成器Generator。

生成器的工作机制是保存它停止的位置,然后给主调函数(main)返回一个值

生成器函数需要使用Python中的yield语句。

>>> def evennum_generator():
    >>> number= 2
    >>> while True:
        >>> yield number
        >>> number *= 2
        
>>> temp = evennum_generator()
>>> print(next(temp))
2
>>> print(next(temp))
4
>>> print(next(temp))
8
>>> print(type(temp))
<class 'generator'>

这个生成器创建了一个无限的序列。可以一直对它调用next方法。
我们接下来看一个有限序列的例子:

>>> def roshambo_generator():
    >>> yield "Rock"
    >>> yield "Paper"
    >>> yield "Scissors"
>>> gen = roshambo_generator()
>>> print(next(gen))
'Rock'
>>> print(next(gen))
'Paper'
>>> print(next(gen))
'Scissors'
>>> print(next(gen))
​
Traceback (most recent call last):
  File "D:test.py", line 11, in <module>
    print(next(gen))
StopIteration

当出现了StopIteration,说明已经耗尽了整个生成器。

16.Serialization 序列化

今天我们学如何用Python来读取JSON file喔?
JSON在modern browser-server communication里非常重要

Serialization

In Python, there’s built-in JSON libraries to encode and decode JSON. Before jumping into that, let’s talk a little bit about JSON.

JavaScript Object Notation (JSON) is an open-standard file format that uses human-readable text to transmit data objects consisting of attribute-value pairs and array data types (or any other serializable value). JSON is a language-independent data format, it is widely used in asynchronous browser-server communications.
JavaScript对象表示法(JSON)是一种开放标准的文件格式,它使用人类可读的文本来传输由属性值对和数组数据类型(或任何其他可序列化的值)组成的数据对象。
JSON是一种独立于语言的数据格式,广泛用于异步浏览器-服务器通信。

Encode: to encode a data structure to JSON, use the dumps method. This method takes an object and returns a string.
Encode:要将数据结构编码为JSON,请使用dump方法。这个方法接受一个对象并返回一个字符串。

>>> import json
>>> json_string = json.dumps([1, 2, 3, "a", "b"])
>>> print(json_string)
[1, 2, 3, "a", "b"]

Decode: to decode JSON back to a data structure, use the loads method. This method takes a string and turns it back to a JSON object data structure.
Decode:要将JSON解码回数据结构,请使用load方法。该方法接受一个字符串并将其返回JSON对象数据结构。

>>> #如果你已经import过json, 在同一个命令执行中,
>>> #就不需要再次import
>>> json_object = '{"name": "carol", "occupation": "captain marvel"}'
>>> json.loads(json_object)
{'name': 'carol', 'occupation': 'captain marvel'}

We will be using another example to help you understand how to read JSON files in Python.

Step 1: create a JSON file called example.json

{
    "fruits": [
        {
            "name": "apple",
            "color": "red"
        },
        {
            "name": "banana",
            "color": "yellow"
        }
    ],
    "vegetables": [
        {
            "id": "basil",
            "price": 1
        },
        {
            "id": "onion",
            "price": 3
        }
    ]
}

Step 2: create a Python file named day16.py to read/manipulate the example.json

import json
​
with open('example.json') as f:
    exampleData = json.loads(f.read())
​
print(exampleData)
print("--------------------------------")
print("Get the fruits object from the json file: ")
print(exampleData["fruits"])
print("================================")
print("Get the id of the first item vegetables from the json file: ")
print(exampleData["vegetables"][0]["id"])
​print("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
exampleData["fruits"].append({"name": "grape", "color": "purple"})
print(exampleData)

Step 3: execute this day16.py file in your terminal/command prompt

Take a look at the result printed out, do you get a better idea of reading JSON file in Python?

GIVE IT A TRY: create a JSON file and play around it!

17.ʟᴀᴍʙᴅᴀ

lambda函数是一个小型匿名函数,它可以使用lambda关键字创建。
lambda函数可以接受任意数量的参数,但只能有一个表达式。它不能包含任何语句,并且返回一个函数对象,该函数对象可以赋值给任何变量。

lambda函数的强大之处在于,您可以在另一个函数中使用它们作为匿名函数。

大多数lambda函数作为参数传递给一个函数,该函数期望函数对象作为参数,如map、reduce、filter函数。

map函数需要一个函数对象和任意数量的迭代器,如list、dictionary等。它为序列中的每个元素执行function_object,并返回函数对象修改的元素列表。
在这里插入图片描述

18.Regular Expressions (1)正则表达式

A regular expression is a sequence of characters that forms a search pattern. It can be used to check if a string contains the specified search pattern.
正则表达式是组成搜索模式的字符序列。它可用于检查字符串是否包含指定的搜索模式。

这个特殊的字符序列可以帮助你方便的检查一个字符串是否与某种模式匹配。

RegEx Module

The package is called re which can be used to work with Regular Expressions.

import re

RegEx in Python

Search the string to see if it starts with “The” and ends with “Spain”.

>>> import re
>>> txt = "The rain in Spain"
>>> x = re.search("^The.*Spain$", txt)
>>> if x:
    >>> print("YES! We have a match!")
>>> else:
    >>> print("Sorry, No match!")

RegEx Functions

Function Description
findall Returns a list containing all matches
search Returns a Match object if there is a match anywhere in the string
split Returns a list where the string has been split at each match
sub Replaces one or many matches with a string

findall返回一个包含所有匹配项的列表
如果字符串中有匹配对象,search将返回匹配对象
split返回一个列表,其中的字符串在每次匹配时都被分割
用字符串替换一个或多个匹配项
在这里插入图片描述

Metacharacters

Metacharacters are characters with a special meaning:
元字符是具有特殊意义的字符:

Character Description Example
[] A set of characters “[a-m]”
\ Signals a special sequence “\d”
. Any character “he…o”
^ Starts with “^hello”
$ Ends with “world$”

  •   Zero or more occurrences		"aix*"
    
  •   One or more occurrences		"aix+"
    

{} Exactly the specified number of occurences "al{2}"确切指定的发生次数
| Either or “falls|stays”
() Capture and group
在这里插入图片描述

>>> import re
>>> str = "The rain in Spain"
#Find all lower case characters alpabetically  按字母顺序查找所有小写字母
#between "a" and "m":
>>> x = re.findall("[a-m]", str)
>>> print(x)
['h','e','a','i','i','a','i']


>>> import re
>>> str = "That will be 59 dollars"
#Find all digit characters:查找所有数字字符:
>>> x = re.findall("\d", str)
>>> print(x)
['5','9']


>>> import re
>>> str = "Hello world"
#Search for a sequence that starts with "he", 搜索以“he”开头的序列,
#followed by two(any) characters, and an "o":后跟两个(任意)字符和一个“o”:
>>> x = re.findall("he..o", str)
>>> print(x)
['hello']


>>> import re
>>> str = "Hello world"
#Check if the string starts with 'hello':检查字符串是否以“hello”开头:
>>> x = re.findall("^hello", str)
>>> if x:
    >>> print("YES! We have a match!")
>>> else:
    >>> print("Sorry, No match!")
YES! We have a match!

>>> import re
>>> str = "Hello world"
#Check if the string ends with 'world':检查字符串是否以“world”结尾:
>>> x = re.findall("world$", str)
>>> if x:
    >>> print("YES! We have a match!")
>>> else:
    >>> print("Sorry, No match!")
YES! We have a match!


>>> import re
>>> str = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "ai" 检查字符串是否包含“ai”
#followed by 0 or more "x" characters:后跟0个或多个“x”字符:
>>> x = re.findall("aix*", str)
>>> print(x)
>>> if x:
    >>> print("Yes! We have a match")
>>> else:
    >>> print("Sorry, No match!")
['ai', 'ai', 'ai', 'ai']
Yes! We have a match


>>> import re
>>> str = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "ai" 检查字符串是否包含“ai”
#followed by 1 or more "x" characters:后跟一个或多个“x”字符:
>>> x = re.findall("aix+", str)
>>> print(x)
>>> if x:
    >>> print("Yes! We have a match")
>>> else:
    >>> print("Sorry, No match!")
[]
Sorry, No match!


>>> import re
>>> str = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "a" 检查字符串是否包含“a”
#followed by exactly two "l" characters:紧跟着两个“l”字:
>>> x = re.findall("al{2}", str)
>>> print(x)
>>> if x:
    >>> print("Yes! We have a match")
>>> else:
    >>> print("Sorry, No match!")
['all']
Yes! We have a match


>>> import re
>>> str = "The rain in Spain falls mainly in the plain!"
#Check if the string contains either "falls" or "stays":检查字符串是否包含“falls”或“stay”:
>>> x = re.findall("falls|stays", str)
>>> print(x)
>>> if x:
    >>> print("Yes! there is at least one match")
>>> else:
    >>> print("Sorry, No match!")
['falls']
Yes! there is at least one match

19.Inheritance继承

继承可以让程序更模块化,更容易被reuse,帮助我们在提高效率的同时,减少debug的成本。 ​​​​

Inheritance allows us to define a class that inherits all the methods and properties from another class.

Parent class: the class being inherited from, also called base class

Child class: the class that inherits from another class, also called derived class

下面我们用个简单的例子来帮助我们理解inheritance这个概念:

我们可以把“车”这个class当作base class, 我们给"车“四个轮子,一个发动机。现在我们创造出”小汽车“,”大巴车“,”运输车“都inherit from “车”,这个时候“小汽车”,“大巴车”,“运输车”都具有了四个轮子,一个发动机。

Create a Parent Class:

Any class can be a parent class, so the syntax is the same as creating any other class. Let’s create a class named Person, with firstName, lastName properties, and a printName method:

class Person:
  def __init__(self, fname, lname):
    self.firstname = fname
    self.lastname = lname
​
  def printName(self):
    print(self.firstname, self.lastname)
​
#Use the Person class to create an object
x = Person("Phil", "Dunphy")
x.printName()

Create a Child Class:

When creating a child class, send the parent class as a parameter, thus the child class can inherit the functionality from the parent class.
创建子类时,将父类作为参数发送,这样子类就可以继承父类的功能。

class Student(Person):
    pass

Use the pass keyword when you don’t want to add any other properties or methods to the class. Now the Student class has the same properties and methods as the Person class.
如果不想向类添加任何其他属性或方法,请使用pass关键字。现在Student类具有与Person类相同的属性和方法。

y = Student("Manny", "Delgado")
y.printName()

Override inherited function

We can add a init() function to the child class instead of the pass keyword to override the parent class’s init function.
我们可以向子类添加一个_init__()函数,而不是使用pass关键字来覆盖父类的init函数。

class Student(Person):
    #我们来试试交换first name和last name的顺序
    def __init__(self, fname, lname):
        self.firstname = lname
        self.lastname = fname
​
z = Student("Alex", "Dunphy")
z.printName()

Add properties

We can also add more properties to child class:

class Student(Person):
    def __init__(self, fname, lname, year):
        self.firstname = lname
        self.lastname = fname
        self.graduationYear = year
        
s = Student("Luke", "Dunphy", 2020)

Add methods

Of course we can add more specific methods for child class

class Student(Person):
    def __init__(self, fname, lname, year):
        self.firstname = lname
        self.lastname = fname
        self.graduationyear = year
​
    def welcomeMessage(self):
        print("Welcom ", self.firstname, self.lastname, 
        " to the class of ", self.graduationyear)
   
s = Student("Luke", "Dunphy", 2020)
s.welcomeMessage()

20.Handling Exception

Exception:
Exception is an event which occurs during the execution of a program, that disrupts the normal flow of the program. We are going to learn to handle exception today.
异常是在程序执行过程中发生的事件,它会破坏程序的正常流程。今天我们将学习如何处理异常。

There are three important key words to use when handling exception, try, except, and finally.

try block lets you test a block of code for errors
except block helps handle the error
finally block enables us to execute code, regardless of the result of try/except blocks.

try块允许您测试代码块中的错误
except块帮助处理错误
最后,块使我们能够执行代码,不管try/except块的结果如何。

Why handling exception?

When an error occurs, program will normally stop and generate an error message. Sometimes we want to continue the program execution even when there’s errors, thus we need to handle these exceptions properly to achieve our goal.
当发生错误时,程序通常会停止并生成错误消息。有时,即使出现错误,我们也希望继续执行程序,因此我们需要正确处理这些异常,以实现我们的目标。

Example:

try:
    print(x)
except:
    print("an exception occured, i'm trying to handle it")

In the example above, try block will generate an exception (error) since x is not defined. When the try block generates an error, the except block will be executed. Without the try block, the program will crash.
在上面的例子中,try块将生成一个异常(错误),因为没有定义x。当try块生成错误时,except块将被执行。如果没有try块,程序将崩溃。

Handling multiple exceptions

You can define as many exception blocks as you like.
Example:

def divide(x, y):
    try:
        result = x // y
        print(result)
    except ZeroDivisionError:
        print("error! you cannot dividing by zero")
    except:
        print("something else went wrong")

Useelse block

We can use else block to execute code if no errors occurred.
如果没有发生错误,我们可以使用else块来执行代码。
Example:

try:
    print("yay")
except:
    print("something's wrong")
else:
    print("nothing's wrong")

Results from executing code above:

yay
nothing's wrong

Use finally block

If the finally block is specified, it will be executed regardless if the try block raises an error or not.
如果指定了finally块,则无论try块是否引发错误,它都将执行。
Example:

try:
    print(x)
except:
    print("error!")
finally:
    print("try except finished")

Results from executing code above:

error!
try except finished

21.Regular Expressions (2)

特殊的序列
一个特殊的序列后面跟着下面列表中的一个字符,具有特殊的含义:
\A
如果指定的字符位于字符串的开头,则返回匹配项
“\AThe”

\ b
返回指定字符位于单词开头或结尾的匹配项
r"\bain"
r"ain\b"

\ B
返回具有指定字符的匹配项,但不在单词的开头(或结尾)
r"\Bain"
r"ain\B"

\ d
返回一个匹配项,其中字符串包含数字(从0到9的数字)
“\ d”

\ D
返回字符串不包含数字的匹配项
“\ D”

\ s
返回字符串中包含空白字符的匹配项
“\”

\ S
返回字符串不包含空白字符的匹配项
“\”

\ w
返回一个匹配项,其中字符串包含任何单词字符(从a到Z的字符,从0到9的数字,以及下划线_字符)
“\ w”

\ W
返回字符串不包含任何单词字符的匹配项
“\ W”

\ Z
如果指定的字符位于字符串的末尾,则返回匹配项
“Spain\Z”

在这里插入图片描述

22.Regular Expressions (3)

A set是一对方括号[]中的一组字符,具有特殊的含义:
[arn]
返回具有指定字符(a、r或n)之一的匹配

[a-n]
返回任意小写字符的匹配项,按字母顺序在a和n之间

返回除a、r和n之外的任何字符的匹配

[0123]
返回具有指定数字(0、1、2或3)的匹配

[0 - 9]
返回0到9之间任意数字的匹配

[0 - 5][0 - 9(中括号结束)
返回从00到59的任意两位数的匹配

(a-zA-Z)
返回按字母顺序在a和z之间、小写或大写的任何字符的匹配

(+)
在集,+,*,|,()美元,{}没有特殊的意义,所以[+]意味着返回字符串中任意+字符的匹配

在这里插入图片描述

23. ғɪʟᴇ ʜᴀɴᴅʟɪɴɢ

在这里插入图片描述

24.RegEx

在这里插入图片描述

25.ʙᴜɪʟᴛ-ɪɴ ғᴜɴᴄᴛɪᴏɴ - ɪɴᴘᴜᴛ()

在这里插入图片描述

26.

在这里插入图片描述

27

在这里插入图片描述
在这里插入图片描述

28.ᴍᴀᴛᴘʟᴏᴛʟɪʙ

Python中很常用的一个library-matplotlib的简单用法。想知道怎么用Python绘制数据分析图吗?

在这里插入图片描述
在这里插入图片描述

29

在这里插入图片描述

30

今天的题目虽然不难,但是有涉及到非常重要的ᴍᴀᴘ和ʟᴀᴍʙᴅᴀ两个概念,同时是很多程序员刷题一开始遇到的ғɪʙᴏɴᴀᴄᴄɪ序列题。挑了很久选了这道,因为实在太有代表性啦!做起来会很有意思哦!
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值