python
是一种解释行,面向对象的动态数据类型的高级程序设计语言,在1989
年发明;shell
;python
提示符,互动执行程序;python
的特点:Python
代码阅读清晰;GUI
变成以及系统调用;Python
代码嵌入到C/C++
程序中;C
程序相比非常慢,Python
属于解释性语言,代码在执行时会一行一行翻译成CPU
机器代码,翻译过程十分耗时;C
语言发布成二进制的可执行文件;#
进行注释;'''注释多行 '''
,写代码时,不应该存在中文字符;'''注释多行'''
;print
:打印双引号之间的内容;print('hello world')
,
进行分割print('hi python','hello python')
print(19)print(10 + 8)print('10 + 8 ', 18)
input
:用于从标准输入获取变量的值age=input('please input your age ')print('age = ', age)
输出的结果为
Python的数据类型
number
:
整数:Python
可以处理任意大小的整数,同时也包括负整数,在程序中的写法和数学表达是一致的;
连续定义多个变量
num1 = 10num3 = num2 = num1 //这样变量的地址是一样的num6,num7 = 6,6这两个变量的地址也是一样的;print(id(num2),id(num3));93941385645920 93941385645920
float1 = 1.1float2 = 2.30000print(type(float1))print(float1+float2)
结果为
复数:表示的实数部分和虚数部分组成;
数值类型转换:
print(int(1.9))print(int('123'))print(int('+123'))print(int('-112'))
abs()
:用于返回某个数的绝对值;print((num2>num3)-(num2<num3))
:用于表示比较这两个数的大小,返回值为1 0 -1
;max(arg1,arg2,arg3..)
:用于返回给定参数的最大值;min(arg1,arg2,arg3..)
:用于返回给定参数的最小值;pow(x,y)
:用于计算x^y
的结果;round(x,y)
:表示保留y
位,x
的值,省略表示的就是只保留整数位;math
库:数学运算相关的库;math.ceil(18.1)
:表示向上取整;math.flooe()
:表示向下取整;math.modf(22.3)
:用于将一个数拆分为整数[浮点型]部分和小数部分;math.sqrt()
:表示用于开平方;print(max(num2,num3))print(min(num2,num3))print(pow(num2,num3))print(round(3.456,1))
print(random.choice([1,3,5,7,9,'aa'])) //在这些数里面选出随机数print(random.choice(range(5)))print(random.choice('sunck'))print(random.choice(range(100))+1)print(random.randrange(1,100,2)) //1-->100生成随机数[包含1,但是不包含100],步长为2;print(random.randrange(100)) //start默认是0,步长默认为1print(random.random()) //随机生成[0,1)之间的浮点数;
list = [1,2,3,4,5]random.shuffle(list)print(list)
random.uniform(3,9) //范围是[3,9]
import randomnum = int(input('please input your number '))res = random.choice(range(100)) + 1if num == res: print('you are lucky')else: print('not you')
string
: 表示字符串,python
里面没有字符的概念;str1 = 'hello today'str2 = 'hello tomorrow'
+
:用于连接字符串str1 = 'hello today 'str2 = 'hello tomorrow'print(str1)str3 = str1 + str2
*
:表示字符串的多次输出,也就是拼接str3 = 'oo 'print(str3*3)
[]
用于获取某个单个字符str1 = 'hello today 'str2 = 'hello tomorrow'print(str1[1])str1[1]='a' //字符串不可变原则,所以一定会出错;
str2 = 'hello tomorrow,it's a new day'print(str2[2:14])print(str2[:13])print(str2[10:])
in
的使用str2 = 'hello tomorrow,it's a new day'print('hello' in str2)print('hi' in str2)
\n
:用于表示换行;print('num = %d \nstr = %s\nfnum =%f ' %(num,str1,fnum2))print('today is \\n a new day')print('today is a \'new\' day')print('today is a 'new' day')
print('''today is a goodday''')
\t
:表示制表符,默认是4
个空格print('today is a \t good day')
r
:如果字符串中,存在很多字符进行转义,为了简化,允许使用r
表示内部的字符串默认不转义print(r'\\\\t\\\\')
eval()
:用于将字符串当成有效的表达式来求值,并且返回计算结果,用于将字符串转换成整数不能够用于处理字母;num = eval('1234')print(num)print(type(num))num = eval('12+34')print(num)print(type(num)) //输出结果为46
len()
:用于返回字符个数,并不计算字节个数print(len('today is a new day'))
lower(str)
:转换字符串中的大写字母为小写字母str2 = 'Hello tomoRRow,it's a new day'print(str2.lower()) //并不改变原有字符串的;
upper()
:将小写字母转换为大写字母print(str2.upper())
swapcase()
:用于将大写转换为小写,用于将小写转换为大写print(str2.swapcase())
capitalize()
:只有将首字母大写,其他字母都是小写print(str2.capitalize())Hello tomorrow,it's a new day
title()
:每个单词的首字母大写print(str2.title())Hello Tomorrow,It'S A New Day
center(width,filechar)
:表示宽度和填充字符print(str1.center(40,'*'))**************hello today**************
ljust()
:表示进行左对齐,默认是空格填充print(str1.ljust(20,'%'))hello today%%%%%%%%%
rjust()
:表示返回一个指定长度的字符串,是右对齐,默认使用空格填充print(str1.rjust(20,'*'))*********hello today
zfill()
:返回指定字符串的长度,字符串右对齐,默认使用0
进行填充print(str1.zfill(20))000000000hello today
count(str[,start][,end])
:可以用于在指定字符串的位置中查找指定字符串出现的位置str2 = 'Hello tomotoRRow,it's a new day'print(str2.count('to',5,len(str2)))2
find(str[,start][,end[)
:用于查找指定字符串重做开始第一次出现的位置,如果不存在就返回-1
str2 = 'Hello tomotoRRow,it's a new day'print(str2.find('to',7,len(str2)))10
rfind()
:用法和上面一样,表示从由向左进行查找print(str2.rfind('to'))10
index(str,start=0,end-len=(str))
:用法和上面一样,如果指定字符串不存在,就会报错;str2 = 'Hello tomotoRRow,it's a new day'print(str2.index('too'))Traceback (most recent call last): File '/root/PycharmProjects/test/first.py', line 5, in <module> print(str2.index('too'))ValueError: substring not found
rindex()
:表示从右向左进行查找,如果找不到,就会出错
lstrip()
:用于去掉字符串左侧指定的字符,默认为空格
str2 = '*******Hello tomotoRRow,it's a new day'print(str2.lstrip('*'))Hello tomotoRRow,it's a new day
split(' ',num)
:表示按照某个关键字将字符串进行切割,如果指定num
表示截取指定的num
个字符串;string1 = 'today is a new day, but where are you'string2 = string1.split(' ')wordnum = 0for i in string2: if len(i) > 0: wordnum +=1print(wordnum)9
splitlines(true | false)
:表示按照\r, \r\n, \
分隔,true
表示返回换行符,false
表示不返回换行符;string1 = '''today is an new day, but where are youthe next day is an new day hello tomorrow'''print(string1.splitlines())print(string1.splitlines(True))['today is an new day, but where are you', 'the next day is an new day ', 'hello tomorrow']['today is an new day, but where are you\n', 'the next day is an new day \n', 'hello tomorrow\n']
join
:用于将列表组合成为字符串list1 = ['today is an new day, but where are you', 'the next day is an new day ', 'hello tomorrow']string1 = '\n'.join(list1)print(string1)today is an new day, but where are youthe next day is an new day hello tomorrow
max()
:表示用于返回字符串里面的最大值;min()
:表示用于返回字符串里面的最小值,按照ASCII
进行比较;replace(old,new,count)
:表示要替换的值,替换的值,替换的次数,默认进行全部替换,如果指定了count
,那么只进行前count
的替换;string1 = 'today is an new day'string2 = string1.replace('an','a',1)print(string2)
maketrans('映射前','映射后')
:表示创建字符串映射表,是一张表,每个字符对应进行替换,是按照字符为单位的,替换前后的字符数必须相等;translate()
:表示执行上面的映射string1 = str.maketrans('an', '6o')string2 = 'today is an an an an new day'string3 = string2.translate(string1)print(string3)tod6y is 6o 6o 6o 6o oew d6y
这种替换较少使用;
startwith('str', num1, num2)
:表示从num1
到num2
进行查找,是否是以str
开头的字符串,如果没有指定范围,默认是整个字符串;
string2 = 'today is an an an an new day'print(string2.startswith('an', 3, 10))False
endwith('str',
num1,
num2)
:使用同上,用于判断是否是str
结尾的encode('utf-8,'ignore')
string2 = 'today is an an an an new day'data = string2.encode('utf-8')print(data)print(type(data))解码string3 = data.decode('utf-8')print(string3)b'today is an an an an new day'today is an an an an new day
解码和编码必须使用同样的格式,否则会出错;
isalpha()
:表示如果字符串中至少有一个字符,并且所有的字符都是字母,但会True
,否则返回False
;
isalnum
:表示字符串中至少有一个字符,并且所有的字符都是字母或者数字返回True
,否则返回False
;
isupper()
:表示字符串中至少有一个英文字符,且所有的英文字符必须都是大写的英文字母,返回True
,否则返回False
,如果包含数字也会返回True
islower()
:表示字符串中至少一个英文字符,并且所有的英文字符必须都是小写的英文字符;
istitle()
:表示如果字符串是标题化的就返回True
,否则就是返回False
,标题化表示单词的第一个字母必须是大写;
isdigit()
:如果字符串只包含数字,返回True
,否则返回False
;
isnumeric()
:字符串中只包含数字字符,返回为True
;
isdecimal()
:字符串中只包含十进制字符;
isspace()
:如果字符串中只包含空格,返回True
,否则返回False
;
rstrip()
:作用和上面的一样
ord()
:用于将字母转换成为ACSII
chr()
:用于将某些ASCII
转换成为值;
字符串进行比较的规则:
ASCII
的大,那么就是比第二个;ASCII
;boolean
:用于表示true
以及false
,有且只有这两种值,
None
:是一个特殊值,但是不能够使用0
来进行表示;
list
列表用于存储更多的数据 ,列表表示一组有序的集合,并且允许时不同的类型
age = []print(age)[]age = [12, 23, 34, 45]print(age)[12, 23, 34, 45]list1 = [1, 2, 'sunck', True]print(list1)[1, 2, 'sunck', True]
0
开始,并且访问不能够越界;list1 = [1, 2, 'sunck', True]print(list1[1])list1[1] = 12print(list1)
3
层list2 = age + list1print(list2)
print(age * 3)[12, 23, 34, 45, 12, 23, 34, 45, 12, 23, 34, 45]
print(12 in age)
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]print(list2[2:6])print(list2[2:])print(list2[:6])[3, 4, 5, 6][3, 4, 5, 6, 7, 8, 9][1, 2, 3, 4, 5, 6]
list33 = [[1,2,3],[4,5,6],[7,8,9]]print(list33[1][1])
append
:表示在末尾一次性追加另一个列表中的多个值;list1 = [1, 2, 3, 4, 5]list1.append(6)print(list1)list1.append([7, 8, 9])print(list1)[1, 2, 3, 4, 5, 6][1, 2, 3, 4, 5, 6, [7, 8, 9]]
list1 = [1, 2, 3, 4, 5]list1.extend([6, 7, 8])print(list1)[1, 2, 3, 4, 5, 6, 7, 8]
insert
: 在下标处,添加一个元素,将列表当做一个元素来处理list1 = [1, 2, 3, 4, 5]list1.insert(3, 100)print(list1)[1, 2, 3, 100, 4, 5]
list1 = [1, 2, 3, 4, 5]list1.insert(3, [100, 200])print(list1)[1, 2, 3, [100, 200], 4, 5]
pop(x=list[-1])
:默认表示列表最后一个元素被弹走,可以指定下标移除指定元素,并且返回删除的数据list1 = [1, 2, 3, 4, 5]print(list1[-1])5list1.pop()print(list1)[1, 2, 3, 4]list1.pop(2)print(list1)[1, 2, 4]
remove()
:表示用于删除指定元素第一个匹配的结果,首先会查找指定元素的值list1 = [1, 2, 3, 4, 4, 4, 5]list1.remove(4)print(list1)[1, 2, 3, 4, 4, 5]
clear()
:用于删除列表中的所有元素list1 = [1, 2, 3, 4, 4, 4, 5]list1.clear()print(list1)[]
index()
:表示从列表中找出第一个匹配的索引list1 = [1, 2, 3, 4, 4, 4, 5]print(list1.index(3))print(list1.index(4, 2, 7))23
len()
:用于获取列表里面的元素个数list1 = [1, 2, 3, 4, 4, 4, 5]print(len(list1))
max()
:用于获取列表中的最大值;min()
:用于获取列表中的最小值;count()
:用于查询某个元素出现的次数;reverse()
:用于进行列表的倒序;sort()
:默认进行升序排序;list1 = [1, 2, 3, 4, 4, 4, 5]list2 = list1list2[3] = 300print(list2)print(list1)print(id(list1))print(id(list2))[1, 2, 3, 300, 4, 4, 5][1, 2, 3, 300, 4, 4, 5]140657342356296140657342356296
list27
和list28
里面保存的是堆区里面的同一段地址空间的首地址0x100
,其实访问的是同一片地址空间;list1 = [1, 2, 3, 4, 4, 4, 5]list2 = list1.copy()list2[3] = 300print(list2)print(list1)print(id(list1))print(id(list2))[1, 2, 3, 300, 4, 4, 5][1, 2, 3, 4, 4, 4, 5]140278067989320140278067987720
深拷贝表示的是内存拷贝,
元组转换为列表
list2 = list((1, 2, 3, 4, 5))print(list2)[1, 2, 3, 4, 5]
num = int(input())i = 2list1 = []if num == 1: print(1)while num != 1: if num % i == 0: list1.append(i) num //= i else: i += 1print(list1)
tuple2 = (1, 2, 3, 4, 'hello', True)
tuple1 = (1, )
0
开始,并且不允许越界;print(tuple2[3]) //下标为 0print(tuple2[-1]) //用于获取最后一个元素 [-2]表示倒数第二个元素
tuple2 = (1, 2, 3, 4, 5, [7, 8, 9])tuple2[-1][0] = 50print(tuple2)(1, 2, 3, 4, 5, [50, 8, 9])
del tuple2
+
:表示相加print(tuple2 + tuple1)(1, 2, 3, 4, 5, [50, 8, 9], 1, 2, 3, 4)
*
:表示乘法tuple3 = (1, 2, 3)print(tuple3 * 3)(1, 2, 3, 1, 2, 3, 1, 2, 3)
in
: 判断元素是否在元组里面tuple3 = (1, 2, 3)print( 1 in tuple3)
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9)print(tuple1[3:])print(tuple1[3:5])print(tuple1[:5])(4, 5, 6, 7, 8, 9)(4, 5)(1, 2, 3, 4, 5)
tuple2 = ((1, 2, 3, 4),(1, 2, 3, ),(1, 2, 3, ),(4, 5, 6, ))print(tuple2[1][1])
len()
:用于返回元组里面元素的个数tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
max()
:用于返回元组里面的最大值print(max(tuple1))
list1 = [1, 2, 3, 4, 5]tuple2 = tuple(list1)print(tuple2)(1, 2, 3, 4, 5)
for i in tuple2: print(i)
key-value
,对于key
key
必须是唯一的;key
:必须是不可变的对象;key
;list
是可变的,不能够作为key
dict1 = {'tom':60, 'xiaoxiao':90, 'houhou':100}
key
来访问value
,通过这种方式取值,如果值不存在,就会报错;print(dict1['jerry'])
print(dict1.get('houhouo'))
dict1['cat'] = 99 //如果字典里面内部存在就是添加dict1['jerry'] = 90 //字典里面存在就是修改
dict1.pop('houhou') //删除的前提是必须存在
dict1 = {'tom':60, 'jerry':90, 'houhou':100}print(dict1.get('houhouo'))dict1['cat'] = 99dict1['jerry'] = 90for key in dict1: print(key, dict1[key])for value in dict1.values(): print(value)for key, value in dict1.items(): print(key, value)for key, values in enumerate(dict1): print(key, values)0 tom1 jerry2 houhou3 cat
dictionary
:list
相比,查找和插入的速度是极快的,不会随着key-value
的增加而变慢;dict
在存储数据时,还需要存储序号,会导致内存浪费;list
:w = 'the'str = 'this is a good day, hello the new day, the the a and what the weather;'d = {}list = str.split(' ')print(list)for value in list: need = d.get(value) if need == None: d[value] = 1 else: d[value] += 1print(d[w])print(d)w = 'the'str = 'this is a good day, hello the new day, the the a and what the weather;'d = {}list = str.split(' ')print(list)for value in list: need = d.get(value) if need == None: d[value] = 1 else: d[value] += 1print(d[w])print(d)['this', 'is', 'a', 'good', 'day,', 'hello', 'the', 'new', 'day,', 'the', 'the', 'a', 'and', 'what', 'the', 'weather;']4{'what': 1, 'good': 1, 'and': 1, 'day,': 2, 'this': 1, 'is': 1, 'the': 4, 'new': 1, 'hello': 1, 'a': 2, 'weather;': 1}
set
:表示集合;
标识符
标识符是字符串,但是字符串未必是标识符;
标识符遵守的规则:
Python
的关键字和保留字;Python3
中,允许使用非ASCII
来定义标识符;表示符是用来给变量和函数进行命名的;
查看关键字
import keywordprint(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
name = 初始值
,初始值是为了确定变量的类型,变量的类型根据初始值确定的;变量名 = 数据值
,这个是用来存储数据值的;number1 = int(input('please input a number'))number2 = int(input('please input a number '))print('the sum is ',number1+number2)
显示结果为
删除变量
del name
,删除之后,变量无法引用,用于释放内存空间;
del number1del number2
print(type(number1))<class 'int'>
print(id(age))140043296231312 //变量的首地址
常量:程序运行期间不能够改变的数据,成为常量
运算符和表达式
表达式:由变量,常量和运算符组成的式子;
算术运算表达式不会改变变量的值,
运算符:
算术运算符:+ - * /
,%
取模,**
求幂,//
取整;
赋值运算符:=
,格式是变量 = 表达式
,计算了等号右侧的表达式的值并且赋值给等号左侧的变量;
复合运算符:+= -= /= %= **= //=
位运算符:将数值当做二进制数来进行运算;
&
:表示按位与运算符,如果按位进行运算,两个值都为1
,结果为1
,否则为0
;|
:表示二进制位有一个为1
时,结果为1
;^
:表示按位异或运算符,两个二进制位不同时,结果为1
;~
:表示按位取反运算符;<<
:表示二进制位向左移动几位,高位丢弃,低位补0
;0000 0000 0000 00100000 0000 0000 1000
* `>>`:表示各个二进制向右移动几位,低位丢弃;
关系运算符和关系运算表达式的结果是true
和false
==
!=
>
<
>=
<=
逻辑运算符:
表达式1 and 表达式2
:双真为真;
表达式1 or 表达式2
:一个为真,就是真;
not 表达式
:真为假,假为真;
成员运算符
in
:如果在指定的序列中,找到的指定的值,返回值为true
,否则为false
;
not in
:如果在指定的序列中,没有找到的指定的值,返回值为true
,否则为false
;
身份运算符
is
:判断两个标识符是不是引用同一个对象;
is not
:判断两个标识符是不是引用不同的对象;
运算符优先级
** --> ~ + - --> * / % // --> + - --> << >> --> & --> ^ | --> < > <= >= --> == != --> = --> is --> in --> not or and
判断语句
if 表达式: 语句else: 语句
当程序执行到if 语句
时,首先计算表达式的值,并且得到表达式的真假,表达式为真,执行if
语句 ,如果表达式为假,则跳过if
语句,向后执行;
假:0
以及 0.0
或者 ''
再或者 False
;
其余都为真;
判断三位的水仙花数
num1 = int(input('please input a number '))a = num1 % 10b = num1 //10 % 10c = num1 //100if num1 == a**3 + b**3 + c**3: print('yes')else: print('no')
max = num1if num2 > max: max = num2if num3 > max: max = num3
while
循环while 表达式: 语句
while i < 100: sum += i i += 1print('down')print(sum)while index < len(string1) - 1: print(string1[index]) index += 1
if-elif-else
语句if 表达式1: 语句elif 表达式2: 语句2 . . .else: 语句n
elif
都是对上面条件的否定;while 表达式: 语句1else: 语句2
false
,会执行else:
中的语句2
;for
循环语句:for 变量名 in 集合: 语句
range()
:列表生成器,用于生成数列,表示范围[0,n)
;for i in range(2,20,2): 开始位置默认为0,结束位置,步长默认为1 print(i)
for index, i in enumerate([1, 2, 3, 4, 5]): print(index, i)
break
:用于跳出for
和while
的循环,只能跳出距离最近的那一层循环;continue
:用于跳过当前循环的剩余语句,然后继续下一次循环,同样只能够跳过最近的一次循环;turtle
:是一个简单的绘图工具done()
:用于保持程序不结束;forward()
:表示向前移动,原点默认是从中间开始的;backward()
:表示向后移动;right()
:left()
goto(x,y)
:移动到坐标为x
,y
的位置speed()
:表示移动的速度;up
:表示在移动过程中,不画图down()
:表示开始划线setheading()
:改变朝向pencolor()
:用于表示颜色pensize()
:用于表示粗细reset()
:用于清空窗口,重置turtle
状态clear()
:表示清空窗口,但是不会重置turtle
circle()
:表示用于绘制圆形,或者是五边形turtle.begin_fill()
turtle.fillcolor('blue')
:表示填充什么颜色turtle.end_fill()
:表示结束填充undo()
:表示撤销生一次动作;hideturtle()
:表示隐藏海龟showtutle()
:表示用于显示海龟screensize()
:表示更改显示的屏幕大小联系客服