Basic Knowledge of Python-One

一.常数、变量和数据类型

1.字符串的两侧可以用单引号,也可以用双引号,使用时成对出现。“\”反斜杆表示转义;"\n"表示换行;如果是一个段落文章,可以用‘ """  ’或者 ' ''' ';注释用‘#’。

a="she's a good girl"
print(a)
>>>she's a good girl

a="she\'s a good girl"
print(a)
>>>she's a good girl

s="this is line1\nAnd this is line2\nline3 is hear"  
print(s)
>>>this is line1
   And this is line2
   line3 is hear

>>> s='''
... this is line1
... And this is line2
... line3 is here
... '''
>>> print(s)

this is line1
And this is line2
line3 is here

2.命名可以使用英文字母,数字,下划线;命名第一个字母前需要用英文字母;可以用下划线隔开一个命名里的不同单词,如answer_number。(建议上网搜寻完整的程序编写规范)。

3.命名时关键字(keyword)或保留字(reservedword)不适宜用来做变量名称。

4.数据类型可以强制转换,下列列出需要注意的几个程序。

a=36
b=5
print (int(a/b))
>>>7

sum=1+2+3+4
pre_msg="the sum is "
print(pre_msg+str(sum))#sum整型换成字符型
>>>the sum is 10

quote="how to keep calm when beng trouble"
quote.upper() #改成大写
>>>'HOW TO KEEP CALM WHEN BENG TROUBLE'

quote.split()
>>>['how', 'to', 'keep', 'calm', 'when', 'beng', 'trouble']#列表

二.表达式

1.算数表达式(+,-,*,/,//,%,**)

>>>a=3**3 #表次方
>>>print(a)
27

>>> a,b,c=3,2,1
>>> print(a,b,c)
3 2 1
>>> a,b=7,8
>>> print(a,b,c)
7 8 1
>>> a,b=b,a
>>> print(a,b,c)
8 7 1

>>> a//b #整除
0
>>> a%b #求余
1

2.关系表达式(<,>,<=,>=,!=,==)

>>> a,b=1,2
>>> a==b
False
>>> a!=2
True
>>> a>=b
False
>>> a,b=1,2 #if/elif
>>> if a==b:
...   print("a==b")
... elif a>b:
...   print("a>b")
... else:
...   print("a<b")
...
a<b

3.逻辑表达式(and--是,not--否,or--或)

age=input("请输入你的年龄")
with_parent=input("和父母一起来吗?(Y/N)") #读取控制台输入,与用户交互
if age >= str(18): #int与str不能相加
    print("可以看限制级电影")
elif age >str(12):
    print("可以看辅导型电影")
elif (age >=str(6) and age<str(12)) and (with_parent=="Y" or with_parent=="y"):
    print("可以看保护级电影")
else:
    print("只能看普通级电影")


三.列表list、元组tuple、字典dict与集合set类型

1. list列表与tuple元组

>>> str_list=['p','y','t','h','o','n']
>>> str_list
['p', 'y', 't', 'h', 'o', 'n']
>>> str_list[0]
'p'

>>> str_msg="I love python"
>>> b_list=str_msg.split()
>>> b_list
['I', 'love', 'python']
>>> c_list=list(str_msg)
>>> c_list
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'y', 't', 'h', 'o', 'n']

>>> k1=['book',10]
>>> k2=['campus',15]
>>> k3=['cook',9]
>>> k4=['Python',26]
>>> keywords=[k1,k2,k3,k4]
>>> keywords
[['book', 10], ['campus', 15], ['cook', 9], ['Python', 26]]
>>> keywords[1]
['campus', 15]
>>> keywords[2][0]
'cook'
>>> 'python' in k1
False
>>> 'Python' in keywords
False
>>> ["Python",26] in keywords
True
>>> keywords+k1+k2
[['book', 10], ['campus', 15], ['cook', 9], ['Python', 26], 'book', 10, 'campus', 15]

2.list的操作应用

        

 列表表达式

操作结果说明

list *n

把list列表重复n次

list[n1:n2]

把索引组n1到n2的列表内容取出,组成另一个列表

list[n1:n2:k]

同上,但取出列表的间隔为k

del lst[n1:n2]

删除索引值n1到n2之间的元素

list[n1:n2]=n

把索引值n1到n2之间的元素设置为n

list[n1:n2:k]

同上,但间隔为k

del lst[n1:n2:k]

删除n1到n2之间的元素,间隔为k

len(lst)

返回列表的个数

min(lst)

返回列表中的最小值

max(lst)

返回最大数

list.index()

返回列表中第一次出现的索引值

list.count()

计算出n在列表中出现的次数

>>> x=list(range(10))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y=x[1:7]
>>> y
[1, 2, 3, 4, 5, 6]
>>> y=x[1:7:2]
>>> y
[1, 3, 5]
>>> msg="here is the test string"
>>> list=list(msg)
>>> list
['h', 'e', 'r', 'e', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'e', 's', 't', ' ', 's', 't', 'r', 'i', 'n', 'g']
>>> list.index('i')
5
>>> list.count("i")
2
方法使用 运算结果说明
list.append(x) 将x视为一个元素,附加到列表的后面
list.extend(x) 将x中所有的元素(如果有的话)附加到列表的后面
list.insert(n,x) 将x插入到索引值为n的地方
list.pop() 弹出列表中的最后一个元素,也可以指定索引
list.reverse() 反转列表的顺序
list.sort() 将列表里所有的元素进行排序
list.remove(x) 从列表中删除第一个出现的x
>>> lsta=[1,2,3,4,5]
>>> extb=[5,5,5]
>>> lsta.append(extb)
>>> lsta
[1, 2, 3, 4, 5, [5, 5, 5]]
>>> lsta.extend(extb)
>>> lsta
[1, 2, 3, 4, 5, [5, 5, 5], 5, 5, 5]
>>> lsta.append(9)
>>> lsta.append('x')
>>> lsta
[1, 2, 3, 4, 5, [5, 5, 5], 5, 5, 5, 9, 'x']
>>> lsta.pop()
'x'
>>> lsta.pop(2)
3
>>> lsta
[1, 2, 4, 5, [5, 5, 5], 5, 5, 5, 9]

tuple元组和其一样,但内容无法修改

>>> tpl=tuple(range(10))
>>> tpl
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> tpl[2]
2
>>> tpl[5]=4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

3.dict字典

>>> time={}  #使用“{}”大括号或者设置为dict()函数,即将变量设置为字典类型
>>> time['Monday']=''
>>> time={}
>>> time['Monday']='星期一'
>>> time['Tuesday']='星期二'
>>> time['Wednesday']='星期三'
>>> print(time)
{'Monday': '星期一', 'Tuesday': '星期二', 'Wednesday': '星期三'}
>>> time.keys() #字典中的键
dict_keys(['Monday', 'Tuesday', 'Wednesday'])
>>> time.values()  #字典中的值
dict_values(['星期一', '星期二', '星期三'])
方法使用 运算结果说明
d.clear() 清除 字典d中的所有值
dl=d.copy() 把d的内容复制一份给dl
d.get(key) 通过key取出相对应的value
d.items()

返回dict.item里的所有内容,并输出(key,value)

d.keys() 输出键
d.update(d2) 使用d2的内容去更新d相同的键值
d.values() 输出值

4.set集合

>>> b={1,2,3,4,5,6}
>>> type(b)
<class 'set'>
>>> d={'a':1,'b':2}
>>> type(d)
<class 'dict'>

5.且(AND—&)、或(OR—|)、 异或(XOR—^)

>>> a={1,2,3,4,5}
>>> b={1,3,5,7,9}
>>> a&b
{1, 3, 5}
>>> a|b
{1, 2, 3, 4, 5, 7, 9}
>>> a^b
{2, 4, 7, 9}

6.查看两个变量是否为同一个地址内存

>>> a={1,2,3} #注意大括号
>>> b=a
>>> a
{1, 2, 3}
>>> b
{1, 2, 3}
>>> b.add(4)
>>> a
{1, 2, 3, 4}
>>> b
{1, 2, 3, 4}
>>> a is b
True



>>> a={1,2,3}
>>> b=a.copy()
>>> b.add(4)
>>> a
{1, 2, 3}
>>> b
{1, 2, 3, 4}
>>> a is b
False

>>> a=[1,2,3] #注意方括号
>>> b=a
>>> b.append(4)
>>> b
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]
>>> a is b #判断其是不是一个对象
True
>>> a='string i'
>>> b=a
>>> a==b
True
>>> a is b
True
>>> b=b.upper() #换成大写
>>> a
'string i'
>>> b
'STRING I'

四.内建函数和自定义函数

1.内键建函数

函数名称 使用说明
abs(x) 返回绝对值x
all(i)

i中所有元素都是True才会返回True

any(i) 只要有一个True就会返回True
bin(n) 将数值n转化为二进制数字
bool(x) x如果是False或None或空值就会返回False
chr(n) 取出n个ASCIl码的字符
dir(x) 用来检查x对象可以使用的办法
divmod(a,b) 返回a/b的商和余数,以tuple的方式返回
enumerate(x) 用枚举的方式,经变量x中的索引值和值取出来,组合成tuple,而x必须像list,dict这一类具有迭代性质的变量
eval(e) 求字符串类型的表达式e的值
format() 字符串格式化符号输出映像
frozenset() 用来创建出不能被修改的集合变量
hex(n) 转化为十六进制数字
id(x) 取得变量地址
input(msg) 显示出信息msg,并要求用户输入数据
len(a) 计算a的长度,要求a是可以计算长度的类型
oct(x) 转化为八进制数字
open() 打开文件
pow(x,y)

计算x的y次方

range(a,b,c) 返回a开始到b-1,间隔为c的序列数字
round(n) 数值n四舍五入,取整数
sorted(a) 把a的元素排序
str(n) 把变量n转换为字符串类型
>>> a=list(range(1,10))
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print("1+2+3...+9={}".format(sum(a)))
1+2+3...+9=45

2.自定义部分

>>> def add2number(a,b):
...   global d
...   c=a+b
...   d=a+b
...   print("c={},d={}".format(c,d))
...
>>> c=10
>>> d=99
>>> print("c={},d={}".format(c,d))
c=10,d=99
>>> print("{}+{}={}".format(2,2,2+2))
2+2=4
>>> print("c={},d={}".format(c,d))
c=10,d=4 #d是全局变量,而c是局部变量

>>> def draw_bar(n,symbol="*"):
...   for i in range(1,n+1):
...     print(symbol,end="")
...   print()
...
>>> draw_bar(5)
*****
>>> draw_bar(10,'$')
$$$$$$$$$$


>>> def proc(*args):
...   for arg in args:
...     print("arg:",arg)
...
>>> proc(1,2,3)
arg: 1
arg: 2
arg: 3
>>> proc("a","b")
arg: a
arg: b


>>> x=range(1,10)
>>> y=map(lambda i:i**3,x)
#map(function,iterable,...),function是函数,iterable是一个或多个序列,即map(执行的函数,容器变量)
#https://blog.csdn.net/lemon_tree12138/article/details/50774827(lamdba用法)
>>> for i,value in enumerate(y): 
#http://www.runoob.com/python/python-for-loop.html(for语句的用法)
#https://blog.csdn.net/sinat_31824577/article/details/55536336(enumerate内置函数的用法)
...   print("{}^3={}".format(i,value))
...
0^3=1
1^3=8
2^3=27
3^3=64
4^3=125
5^3=216
6^3=343
7^3=512
8^3=729

>>>def square(x) :      # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
# 提供了两个列表,对相同位置的列表数据进行相加
[3, 7, 11, 15, 19]

3.import与自定义模块

def draw_bar(n,symbol="*"):
for i in range(1,n+1):
print(symbol,end="")
print()
#存入draw_bar.py

from my_module import draw_bar
draw_bar.draw(10,"$")
#存另外一个文件,用from...import读取,自己操作没有成功

五.单词出现频率的统计程序

>>> import re
>>> fp=open("test.txt","r")
>>> article=fp.read()
>>> new_article=re.sub("[^a-zA-Z\s]","",article)
>>> words=new_article.split()
>>> word_counts={}
>>> for word in words:
...   if word.upper() in word_counts:
...     word_counts[word.upper()]=word_counts[word.upper()]+1
...   else:
...     word_counts[word.upper()]=1
...
>>> key_list=list(word_counts.keys())
>>> key_list.sort()
>>> for key in key_list:
...   if word_counts[key]>1:
...     print("{}:{}".format(key,word_counts[key]))
...
A:3
AS:2
OF:2
THE:4
#过后看看具体实现情况

import re
fp=open("test.txt","r")
article=fp.read()
new_article=re.sub("[^a-zA-Z\s]","",article)
words=new_article.split()
word_counts={}
for word in words:
    if word.lower() in word_counts:
        word_counts[word.lower()] = word_counts[word.lower()] + 1
    else:
        word_counts[word.lower()] = 1
key_list=list(word_counts.keys())
key_list.sort()
for key in key_list:
        print("{}:{}".format(key, word_counts[key]))

a:3
almost:1
analysis:1
as:2
average:1
best:1
businesses:1
companies:1
feted:1
gap:1
gender:1
guardian:1
half:1
has:1
have:1
higher:1
in:1
included:1
list:1
national:1
of:2
on:1
pay:1
places:1
revealed:1
than:1
the:4
to:1
uk:1
woman:1
work:1
#可以分析一套英语试卷
发布了16 篇原创文章 · 获赞 4 · 访问量 2296

猜你喜欢

转载自blog.csdn.net/qq_40078031/article/details/83301834
今日推荐