Python学习

人生苦短,我用python

0

不知道从何学起,于是随随便便找个地方开始,开个blog怕自己忘记。
没有书籍,只有网站

来个hello world,以表敬意

1
print("hello world")

乘法口诀

1
2
3
4
5
# coding=gbk
for i in range(1,10):
for j in range(1, i+1):
print('{}×{}={}'.format(i, j, i*j),end="\t")
print('\n')

一开始没有这个

1
# coding=gbk

然后就一直报错…

转义字符

1
2
print('\\\t\\')
print(r'\\\t\\')

引号

单引号双引号
三引号’‘‘多行字符串’’’

多行内容

如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用’‘’…‘’'的格式表示多行内容

1
2
3
print('''line1
line2
line3''')

常量

所谓常量就是不能变的变量,比如常用的数学常数π就是一个常量。在Python中,通常用全部大写的变量名表示常量:

PI = 3.14159265359
但事实上PI仍然是一个变量,Python根本没有任何机制保证PI不会被改变,所以,用全部大写的变量名表示常量只是一个习惯上的用法,如果你一定要改变变量PI的值,也没人能拦住你。

浮点数

/除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数
还有一种除法是//,称为地板除,两个整数的除法仍然是整数

格式化输出

1
2
3
4
print('Hello, %s' % 'world')
print('%2d-%02d' % (3, 1))
print('%.2f' % 3.1415926)
print('Age: %s. Gender: %s' % (25, True))

format()
另一种格式化字符串的方法是使用字符串的format()方法,它会用传入的参数依次替换字符串内的占位符{0}、{1}……,不过这种方式写起来比%要麻烦得多:

1
'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)

容器

列表 元组 集合 字典
英文 list tuple set dict
可否读写 读写 只读 读写 读写
可否重复
存储方式 键(不能重复) 键值对(键不能重复)
是否有序 有序 有序 无序 无序,自动正序
初始化 [1,‘a’] (‘a’, 1) set([1,2]) 或 {1,2} {‘a’:1,‘b’:2}
添加 append 只读 add d[‘key’] = ‘value’
读元素 l[2:] t[0] d[‘a’]

列表

列表、元组、字典、集合的区别是python面试中最常见的一个问题。这个问题虽然很基础,但确实能反映出面试者的基础水平。

list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项目。列表中的项目。列表中的项目应该包括在方括号中,这样python就知道你是在指明一个列表。一旦你创建了一个列表,你就可以添加,删除,或者是搜索列表中的项目。由于你可以增加或删除项目,我们说列表是可变的数据类型,即这种类型是可以被改变的,并且列表是可以嵌套的。python里的列表用“[]”表示:

lst = [‘arwen’,123]
print lst[0]
print lst[1]

lst[0] = ‘weiwen’

向list中添加项有两种方法:append和extend。

append():列表后追加元素

1
word.append('1')

extend()或者+=:列表合并,将一个列表加入到另一个中,成为一个列表。

字典

  1. 字典中的元素顺序无关紧要,通过不同的键(key)进行访问,字典是可以改变的,和现实的字典类似。
  2. 字典在其它的语言中被称为关系型数组,哈希表,哈希图等。
    使用大括号{key:value}创建
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
#键值对的字典
one_dict = {"day1":study
"day2":paly
"day3":sleep
}
#储存一个元素
d = {
'one':123,
'two':2,
'three':3,
'test':2
}
d2 = d['three']
d2
['three':3]
#访问一个元素,如果不存在会报错
d = {
'one':123,
'two':2,
'three':3,
'test':2
}
d['one']
123
#添加一个元素,然后修改这个元素
d = {
'one':123,
'two':2,
'three':3,
'test':2
}
#添加元素'try':55
d['try'] = '55'
d
d = {
'one':123,
'two':2,
'three':3,
'test':2
'try':55
}
修改元素555
d['try'] = '5'

[key]储存,访问,添加或者修改元素

1
2
3
4
5
6
7
8
#将包含双值的子序列的序列转换成字典,第一值为键,第二个值为值
one_list = [[1,'a'],[2,'b']]
dict(one_list)
{1:'a',2:'b'}
#可以将双值的,双字符,元组,列表化成字典。
tos = ('ab','cd','ef')
dict(tos)
{'c':'d','a':'b','e':'f'}

元组

元组与序列类似,也是由任意元素组成的序列,但是元组一旦创建如同字符串,不可改变。

集合

集合和只剩下的键的字典类似,键与键之间不允许重复,类似数学中的集合,主要包括并、交等运算,且集合是无序的。

1
2
#偶数集合
even_numbers = {0,2,4,6,8}

union() 或者 | 函数获取并集
different() 或者 - 获得集合的并集
symmetric_difference() 或者 ^ 获得异或集(只在两个集合中出现一次)
issubset() 或者 <= 判断一个集合是否是另一个集合的子集
< 判断真子集
issupset() 或者 >= 判断超集(超集的概念与子集相反)

实验1

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
import random
word = ('answer', 'python','password', 'learn')
print(' 欢迎参加猜单词游戏\n', ' 请把下列各字母组合成一个正确的单词.\n')

while True: #随机取词
get_word = ''
temp = random.randint(0, len(word) - 1)
temp_word = word[temp]

while (len(temp_word)): #打乱字母
position = random.randint(0, len(temp_word) - 1)
get_word += temp_word[position]
temp_word = temp_word[:position] + temp_word[(position + 1):]#切片操作

print('乱序后单词:',get_word)
if(input('请你猜:') != word[temp]):
print('对不起不正确.')
while(input('继续猜:') != word[temp]):print('对不起不正确.')
print('真棒,你猜对了!\n')

while True: #是否继续
judge_w = input('是否继续(Y/N):')
if (judge_w == 'Y' or judge_w == 'y'):break
elif (judge_w == 'N' or judge_w == 'n'):exit()

实验2

1

1
2
3
4
5
6
7
8
9
10
11
12
import sqlite3

#单词列表
regions = [(1, 'anwser'), (2, 'password'), (3, 'python'), (4, 'learn'), (5, 'star'), (6, 'warn'), (7, 'error')]

#创建数据库,单词写入数据库
con = sqlite3.connect(r"F:\work\二上\py\SQL数据库\test.db")
con.execute("create table region(id primary key, name)")
con.executemany("insert into region(id, name) values(?, ?)", regions)

con.commit()
con.close()

2

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
import sqlite3
import random

con = sqlite3.connect(r"F:\work\二上\py\SQL数据库\test.db") #单词从数据库中取出
cur = con.execute("select id, name from region")
word = []
for row in cur: word.append(row[1])
cur.close()
con.close()

print(' 欢迎参加猜单词游戏\n', ' 请把下列各字母组合成一个正确的单词.\n')
while True: #随机取词
get_word = ''
temp = random.randint(0, len(word) - 1)
temp_word = word[temp]

while (len(temp_word)): #打乱字母
position = random.randint(0, len(temp_word) - 1)
get_word += temp_word[position]
temp_word = temp_word[:position] + temp_word[(position + 1):]#切片操作

print('乱序后单词:',get_word)
if(input('请你猜:') != word[temp]):
print('对不起不正确.')
while(input('继续猜:') != word[temp]):print('对不起不正确.')
print('真棒,你猜对了!\n')

while True: #是否继续
judge_w = input('是否继续(Y/N):')
if (judge_w == 'Y' or judge_w == 'y'):break
elif (judge_w == 'N' or judge_w == 'n'):exit()