python programming learning 1

Life is short, I use python

不打ACM了可能是最遗憾的事了

但是终究是自己选的…

fighting!!!

x

String function:

.title():

1
2
3
4
name="wyh"
print(name.title())
#out:Wyh
#Capitalize the first letter of a string

.upper() and .lower();

1
2
3
4
5
6
name="Wyh"
print(name.upper())
print(name.lower())
#out:WYH
wyh
#Convert all strings to upper or lower case

.rstrip() and .lstrip() and .strip():

1
2
3
4
5
6
name=" i love python "
print(name)
print(name.rstrip())
print(name.lstrip())
print(name.strip())
#Remove header or trailing spaces in a string


Digit:

整数:

1
2
3
4
5
6
7
8
9
10
>>>2+3
5
>>>3-2
1
>>>2*3
6
>>>3/2
1.5
>>>3**3
27

浮点数:

1
2
3
4
5
6
7
>>>0.1+0.1
0.2
>>>0.2+0.1
0.3000000000004
>>>0.1*3
0.3000000000004
#Ignore the extra decimal places

Type conversion:

digit->string:

1
2
3
age=19
print("happy "+str(age)+" rd birthday!")
#out: happy 19rd birthday!

Conversion between numeric types:

1
2
3
4
>>>3/2
1.5
>>>int(3/2)
1

Introduction to the list:

Create and access the list:

1
2
3
4
5
6
7
8
9
10
11
list_=["C++","python","C"]
print(list_)
#out:['C++','python','C']
list__=['C++','C','python']
print(list__)
#out:['C++','C','python']
print(list_[1])
#out:python
print(list_[1].title())
#out:Python
#upper()、lower()均可使用

“xxx”可以替换’xxx’,但是,不能换成;

索引从0开始

Modify, add, and delete list elements:

.append()

.insert()

.pop()

.remove()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
_=['huawei','apple','mi']
_[2]='xiaomi'
print(_)
#['huawei','apple','xiaomi'] --modify list elements
_.append('meizu')
print(_)
#['huawei','apple','xiaomi','meizu'] --Add a list element at the end
_.insert(0,'samsung')
print(_)
#['samsung',huawei','apple','xiaomi','meizu'] --Add a list element anywhere
del _[0]
print(_)
#['huawei', 'apple', 'xiaomi', 'meizu'] --delete a list element anywhere
mi=_.pop()
print(mi)
#meizu -- pop up the lastest element
print(_)
#['huawei', 'apple', 'xiaomi']
huawei=_.pop(0)
print(huawei)
#huawei --Pop up elements anywhere
print(_)
#['apple', 'xiaomi']
_.remove('apple')
print(_)
#['xiaomi'] --Remove elements based on element values

Organization list:

Sorting of lists:

1
2
3
4
_=['huawei','apple','mi']
_.sort()
print(_)
#out: ['apple', 'huawei', 'mi']

Temporary sorting of lists:

1
2
3
4
5
6
7
8
_=['huawei','apple','mi']
print("the list:"+str(_))
print("the sorted list:"+str(sorted(_)))
print("the list:"+str(_))
###out:
the list:['huawei', 'apple', 'mi']
the sorted list:['apple', 'huawei', 'mi']
the list:['huawei', 'apple', 'mi']

Reverse print list:

reverse()是反转列表元素的排列顺序

1
2
3
4
5
_=['huawei','apple','mi']
_.reverse()
print(_)

###out:['mi', 'apple', 'huawei']

Confirm the length of the list:

1
2
3
_=['huawei','apple','mi']
print(len(_))
##out: 3

List index:

python的索引也是从0开始,不过py的索引可以有-1->代表列表的最后一个值(列表为空时会返回索引错误)

1
2
3
4
5
6
7
8
_=['huawei','apple','mi']
print(_[0])
print(_[-1])
print(_[-2])
###out:
huawei
mi
apple

List operation:

List traversal:

for循环:

example:

1
2
3
4
5
6
7
_=['huawei','apple','mi']
for i in _:
print(i)
###out:
huawei
apple
mi

列表元素与字符串一起打印:

1
2
3
4
5
6
7
_=['huawei','apple','mi']
for i in _:
print(i.title()+", i love it!")
###out:
Huawei, i love it!
Apple, i love it!
Mi, i love it!

注意for循环的缩进和末尾的冒号!(Note the indentation of the for loop and the colon at the end!)

Create a list of values:

使用函数range():

range(1,5):–>1 2 3 4 5 ×

​ –>1 2 3 4 √

range(a,b)—>[a,b)

range(a,b,c)—>a,a+c,a+2c,a+3c…a+nc(a+nc<=b)

example:使用range()创建1-10的平方的数字集:

1
2
3
4
5
6
_=[];
for i in range(1,11):
_.append(i**2)
print(_)
###out:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Simple statistical calculation of a list of numbers:

1
2
3
4
5
6
7
8
9
10
11
12
_=[];
for i in range(1,11):
_.append(i*i)
print(_)
print(min(_))
print(max(_))
print(sum(_))
###out:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1
100
385

List resolution:

列表解析

example:创建1-10平方数字集:

1
2
3
4
_=[i**2 for i in range(1,11)]
print(_)
###out:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

list_name=[i_function for i in range(a,b)]

Use part of the list:

列表切片:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
_=[1,2,3,4,5]
print(_[0:3])
print(_[:3])
print(_[2:5])
print(_[2:])
print(_[-3:])
print(_[:])
###out:
[1, 2, 3]
[1, 2, 3]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[1, 2, 3, 4, 5]

可见:列表切片与range()类似:[a,b]==>[a,b),从a开始,到b-1结束

_[a:b]:没有参数a时:即代表索引从0开始切到b

​ 没有参数b时:即为索引从a开始切片到最后一个元素为止(包括最后一个元素)

​ 既没有参数a也没有参数b时:相当于复制列表

对于_[a:b]的a与b均可为负数,代表倒数第多少个元素。

复制列表:

1
2
3
4
5
_=[1,2,3,4,5]
cxk=_[:]
print(cxk)
###out:
[1, 2, 3, 4, 5]

那么这样呢?–>cxk=_

当然是可以的,但是:

1
2
3
4
5
6
7
8
9
10
_=[1,2,3,4,5]
cxk=_
print(cxk)
_.append(6)
print(_)
print(cxk)
###out:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

最后一行为列表cxk,它的列表值随着的改变也改变了,这是我们不希望达到的效果,而cxk=[:]就可以避免这种情况

1
2
3
4
5
6
7
8
9
10
_=[1,2,3,4,5]
cxk=_[:]
print(cxk)
_.append(6)
print(_)
print(cxk)
###out:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]

Tuple:

即元组,元组与列表很像,但是列表的值可以修改可以添加(即列表被修改),而元组不可以被修改。

元组:例如ddd=(1,2,3,4,5)索引之类类似列表写法

虽然元组不能被修改,但是可以被赋值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
wyh=(7,2,4)
print(wyh)
for i in wyh:
print(i)
wyh=(6,2,3)
print(wyh)
for i in wyh:
print(i)
###out:
(7, 2, 4)
7
2
4
(6, 2, 3)
6
2
3

Dictionary:

字典是各个键值对的集合:

example: addr_book={‘wyh’:’hefei’, ‘dyx’:’taiyuan’, ‘ysq’:’hefei’, ‘mhj’:’ganzhou’}

关于字典的增删改查:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
addr_book={'wyh':'hefei', 'dyx':'taiyuan', 'ysq':'hefei', 'mhj':'ganzhou'}
print(addr_book)
print(addr_book['dyx'])
print("wyh is from "+addr_book['wyh'])
## Add a set of key-value pairs
addr_book['coswindy']=' is wyh actually'
print("coswindy"+addr_book['coswindy'])
## Modify the value of a key-value pair
addr_book['wyh']=' wants to study well!'
print("wyh"+addr_book['wyh'])
## Delete a pair of key-value pairs
del addr_book['ysq']
print(addr_book)
###out:
{'wyh': 'hefei', 'dyx': 'taiyuan', 'ysq': 'hefei', 'mhj': 'ganzhou'}
taiyuan
wyh is from hefei
coswindy is wyh actually
wyh wants to study well!
{'wyh': ' wants to study well!', 'dyx': 'taiyuan', 'mhj': 'ganzhou', 'coswindy': ' is wyh actually'}

针对有多组键值对的字典,可以写成多行:

1
2
3
4
5
6
7
8
addr_book={
'wyh':'hefei',
'dyx':'taiyuan',
'mhj':'ganzhou',## The last comma is unnecessary
}
print(addr_book)
###out:
{'wyh': 'hefei', 'dyx': 'taiyuan', 'mhj': 'ganzhou'}

Dictionary traversal:

字典键值对的遍历:

for i,j in dic.items()

对于 addr_book={‘wyh’:’hefei’, ‘dyx’:’taiyuan’, ‘ysq’:’hefei’, ‘mhj’:’ganzhou’} 的遍历:

1
2
3
4
5
6
7
8
9
10
11
12
13
addr_book={'wyh':'hefei', 'dyx':'taiyuan', 'ysq':'hefei', 'mhj':'ganzhou'}
for key,value in addr_book.items():
print(key+" is from "+value)
###out:
wyh is from hefei
dyx is from taiyuan
ysq is from hefei
mhj is from ganzhou
#key与value是不必须的,只是写法,下面的代码同样可以达到效果(只是命名不同:
addr_book={'wyh':'hefei', 'dyx':'taiyuan', 'ysq':'hefei', 'mhj':'ganzhou'}
for i,j in addr_book.items():
print(i+" is from "+j)
#运行结果与上一致

字典所有键的遍历:

for i in dic.keys()

1
2
3
4
5
6
7
8
addr_book={'wyh':'hefei', 'dyx':'taiyuan', 'ysq':'hefei', 'mhj':'ganzhou'}
for i in addr_book.keys():
print(i)
###out:
wyh
dyx
ysq
mhj

由键推值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
addr_book={'wyh':'hefei', 'dyx':'taiyuan', 'ysq':'hefei', 'mhj':'ganzhou'}
my_friends=['wyh','mhj']
for i in addr_book.keys():
print(i.title())
if i in my_friends:
print("Hi "+i.title()+
",I Know that you are from "+
addr_book[i]+"!")
###out:
Wyh
Hi Wyh,I Know that you are from hefei!
Dyx
Ysq
Mhj
Hi Mhj,I Know that you are from ganzhou!

keys()并非只能用于遍历;实际上他返回了一个列表,包含了字典中所有的键:

1
2
3
4
5
addr_book={'wyh':'hefei', 'dyx':'taiyuan', 'ysq':'hefei', 'mhj':'ganzhou'}
if 'mhj' in addr_book.keys():
print("Oh!my dear friend")
###out:
Oh!my dear friend

字典所有值的遍历:

返回一个值列表,而不包含任何键:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
addr_book={'wyh':'hefei', 'dyx':'taiyuan', 'ysq':'hefei', 'mhj':'ganzhou'}
for i in addr_book.values():
print(i.title())
### Eliminate duplicates 剔除重复项
print("After eliminating duplicates")
for i in set(addr_book.values()):
print(i)
###out:
Hefei
Taiyuan
Hefei
Ganzhou
After eliminating duplicates
ganzhou
taiyuan
hefei

使用set(集合)剔除重复项

顺序遍历字典中的所有键或值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
### 键的顺序遍历
addr_book={'wyh':'hefei', 'dyx':'taiyuan', 'ysq':'hefei', 'mhj':'ganzhou'}
for i in sorted(addr_book.keys()):
print(i.title()+" is from "+addr_book[i]+'!')
###out:
Dyx is from taiyuan!
Mhj is from ganzhou!
Wyh is from hefei!
Ysq is from hefei!
##(D->M->W->Y)

### 值的顺序遍历:
addr_book={'wyh':'hefei', 'dyx':'taiyuan', 'ysq':'hefei', 'mhj':'ganzhou'}
for i in sorted(addr_book.values()):
print(i.title())
###Out:
Ganzhou
Hefei
Hefei
Taiyuan

也可将reverse()加入后转为逆序

Nesting of dictionaries and lists:

字典与列表的嵌套:

在列表中存储字典:

(字典列表)

拿之前的addr_book举例来说,一个人的信息如果不止地址这一项呢?加上电话、年龄…这些呢?该怎样把这些具有多个信息的人们装进一个集合里呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
friend_0={
'name':'wyh',
'addr':'hefei',
'age':19
}
friend_1={
'name':'dyx',
'addr':'taiyuan',
'age':21
}
friend_2={
'name':'mhj',
'addr':'ganzhou',
'age':21
}
friends=[friend_0,friend_1,friend_2]
for i in friends:
print(i)
print("*********")
### add friends:
for i in range(10):
new_friend={
'name':'xxx',
'addr':'China',
'age':18
}
friends.append(new_friend)
for ii in friends[:5]:
print(ii)
print("*********")
print("Now I have "+str(len(friends))+"friends!")
###out:
{'name': 'wyh', 'addr': 'hefei', 'age': 19}
{'name': 'dyx', 'addr': 'taiyuan', 'age': 21}
{'name': 'mhj', 'addr': 'ganzhou', 'age': 21}
********
{'name': 'wyh', 'addr': 'hefei', 'age': 19}
{'name': 'dyx', 'addr': 'taiyuan', 'age': 21}
{'name': 'mhj', 'addr': 'ganzhou', 'age': 21}
{'name': 'xxx', 'addr': 'China', 'age': 18}
{'name': 'xxx', 'addr': 'China', 'age': 18}
*********
Now I have 13 friends!

在字典中存储列表:

即字典中的value值为列表时,比如对于上述的人,穿的衣服的颜色可能不为单一,所以字典中clothes_colors键对应的值就可能会是一个列表比如:[‘blue’,’red’,’green’]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
friend_0={'name':'wyh','clothes':['white','black']}
friend_1={'name':'coswindy','clothes':['red','green']}
print("Today "+friend_0['name']+" is wearing: ")
for i in friend_0['clothes']:
print("\t"+i)
print("*************")
##如果我的朋友很多并且我要把他们的信息都打印出来呢?

friends={
'wyh':['white','black'],
'coswindy':['red','green'],
'晚风':['while','red','black']
}
for name,clothes in friends.items():
print("Today "+name.title()+" is wearing: ")
for cloth in clothes:
print(" "+cloth.title())
###out:
Today wyh is wearing:
white
black
*************
Today Wyh is wearing:
White
Black
Today Coswindy is wearing:
Red
Green
Today 晚风 is wearing:
While
Red
Black

在字典中存储字典:

想象在上述的朋友集合中,对每一个给定的信息为姓,名,居住地

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
friends={
'01':{
'first_name':'wang',
'last_name':'sicong',
'location':'beijing'
},
'02':{
'first_name':'ma',
'last_name':'yun',
'location':'hangzhou'
},
'03':{
'first_name':'ma',
'last_name':'huateng',
'location':'shenzhen'
}
}
for name,place in friends.items():
print("ID:"+name)
print("This is my friend:"+place['first_name'].title()+" "+place['last_name'].title())
print(place['first_name'].title()+" "+place['last_name'].title()+" lives in "+place['location'].title())
print("*************")
###out:
ID:01
This is my friend:Wang Sicong
Wang Sicong lives in Beijing
*************
ID:02
This is my friend:Ma Yun
Ma Yun lives in Hangzhou
*************
ID:03
This is my friend:Ma Huateng
Ma Huateng lives in Shenzhen
*************

if Statement:

检查相等与不相等:

== 相等

!=不相等

检查多个条件时:

and ==>与:

多个条件同时成立时,值为True,否则为False

or ==>或:

多个条件其中之一成立,值即为True,只有在多个条件同时不成立是才为False

检查特定元素是否在列表中:

1
2
3
4
5
>>>_=['wyh','mhj','cxk']
>>>'wyh' in _
>>>True
>>>'xxx' in _
>>>False

对于元组同样适用:

1
2
3
4
5
6
_=(1,2,3)
print(1 in _)
print(4 in _)
###out:
True
False

if 语句的写法:

最简单的if语句:

1
2
3
4
5
6
7
8
if conditional_test:
do something
#for example:
age=19
if age>=18:
print("You are old enough to go to the internet cafe")
###out:
You are old enough to go to the internet cafe

if-else 语句:

同C/C++理解起来一样:

1
2
3
4
5
6
7
age = 17
if age>=18:
print("You are old enough to go to the internet cafe")
else:
print("Your age is too small !")
###out:
Your age is too small !

if-elif-else 语句:

1
2
3
4
5
6
7
8
9
age = 18;
if age < 18:
print("Your age is too small !")
elif age == 18:
print("It’s so good, the age of flowers !")
else :
print("You are old enough to go to the internet cafe !")
###out:
It’s so good, the age of flowers !

elif 语句可以有很多,写法形式相同

if 语句处理列表:

for循环遍历处理:

if语句用来处理列表自然时需要用到for循环遍历的,举个栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
_=[1,2,3,4,5,6,7,8,9]
for i in _:
if i == 4:
print("this is 4!")
elif i== 5:
print("this is 5!")
else :
print("nothing")
###out:
nothing
nothing
nothing
this is 4!
this is 5!
nothing
nothing
nothing
nothing

将列表换成元组也一样是可行的

对于空列表的判断(处理):

用法如下:

1
2
3
4
5
6
7
_=[]
if _:
print("This list has elements")
else:
print("This is an empty list !")
###out:
This is an empty list !

User input and while loop:

User input :

Use input() to get a string input:

使用input()获取字符串输入:

x=input(Prompt message)—-提示信息

1
2
3
4
5
6
7
name=input("Please enter your name:")
print("Hello,"+name+"!")
###in:
wyh
###out:
Please enter your name:wyh
Hello,wyh!

Use int() to get the numeric input:

使用int()来获取数值输入:

1
2
3
4
5
6
7
8
9
10
age=int(input("How old are u ?"))
if(age > 18):
print("You are already an adult.")
else:
print("You are still too small.")
###in:
19
###out:
How old are u ?19
You are already an adult.

留坑:

以前写题目遇上那种以空格为分隔读入两个以上的数时所用的input写法我给忘了,后面想起再补……

———2019/8/6———-

while loop:

How to use the while loop:

与C/C++的思路逻辑也是类似:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
_=1
while _ <= 5:
print("white nb!")
_+=1
print("Please enter your name:")
name=""
while name!='quit':
name=input()
if name=='quit':
break
print(name+" nb!")
###in:
55 kai
white
wyh
quit
###out:
white nb!
white nb!
white nb!
white nb!
white nb!
Please enter your name:
55 kai
55 kai nb!
white
white nb!
wyh
wyh nb!
quit

Use and difference between break and continue:

break:

如上面的while循环实例代码所示,和C/C++一样,跳出循环

continue:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#continue:
_=0
while _<10:
_+=1
if _%2==0:
continue

print(_)
###out:
1
3
5
7
9
#break:
_=0
while _<10:
_+=1
if _%2==0:
break

print(_)
###out:
1

参上代码,不难看出,此程序当满足 _%2==0时,没有走到print()这一步

而换成break语句,在遇到第一次满足_%2==0时就直接结束while循环,只打印出了1

而continue明显只是结束了本次循环,而while()循环任然在继续

Use a while loop to handle lists and dictionaries:

使用while循环来处理列表与字典:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
un_=['wyh','cxk','55kai']
_=[]
while un_:
x=un_.pop()
print("待确认:"+x.title())
_.append(x)
print("已确认:")
for i in _:
print(i.title())
while 'cxk' in _:
_.remove('cxk')
print(_)
while _:
print(_.pop().title())
###out:
待确认:55Kai
待确认:Cxk
待确认:Wyh
已确认:
55Kai
Cxk
Wyh
['55kai', 'wyh']
Wyh
55Kai

使用用户输入填充字典:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
friends=[]
flag=True
i=0
while flag:
friend={}
name=input("what's your name?")
if name=='quit':
break
age=input("how old are you?")
blood_type=input("What's your blood type?")
friend['name']=name
friend['age']=age
friend['blood_type']=blood_type
friends.append(friend)
i+=1
print(friends)
for i in friends:
print(i['name'].title()+" is "+i['age']+" years old this year, his blood type is "+i['blood_type'].title()+" type.")


###in:
wyh
19
o
55 kai
29
a
cxk
250
sb
quit
###out:
what's your name?wyh
how old are you?19
What's your blood type?o
what's your name?55 kai
how old are you?29
What's your blood type?a
what's your name?cxk
how old are you?250
What's your blood type?sb
what's your name?quit
[{'name': 'wyh', 'age': '19', 'blood_type': 'o'}, {'name': '55 kai ', 'age': '29', 'blood_type': 'a'}, {'name': 'cxk', 'age': '250', 'blood_type': 'sb'}]
Wyh is 19 years old this year, his blood type is O type.
55 Kai is 29 years old this year, his blood type is A type.
Cxk is 250 years old this year, his blood type is Sb type.

以上代码纯属恶搞,(有点害怕律师函警告


End:

第一部分就写到这,毕竟写的太长看起来也麻烦…

python之前就学过,只是很久没有用生疏了很多,以上很多都是老生常谈,但还是写下来,算是一个系统的学习语法的过程。明天再开写后面的函数、类、文件部分……再往后写一写项目实战,说实话学编程这么久没接触过什么开发的过程,现在从ACM退出了,这个暑假一定好好把python掌握好,可以的话以后再学习一门新的开发语言,这样对考研也是有一点好处的,现在考研是我最后的稻草了,我一定要抓紧!

奥利给!

-------------本文结束感谢您的阅读-------------
undefined