目录
第二章 基本数据类型
2.1 变量和标识符
2.1.1 变量是什么?
变量:在程序的运行过程中,可以发生变化的量,就叫做变量
具有名称的内存空间,这种说法也是正确的
2.1.2如何定义变量
python是一门弱数据类型语言
Java 、C、C++都是强数据类型语言
数据类型 变量名称 = 变量;
在Java中:
int age = 18; double price = 3.14;
每个数据类型占用的内存大小是不一样
1字节 ------- byte boolean
2字节 ------ short、char
4字节 ----- int 、float
8字节 ----- long 、double
在python这种弱数据类型语言中,一般声明变量的格式:
var 变量名称 = 变量
什么是强数据类型语言?什么是弱数据类型语言?
强:当定义变量的时候,需要声明数据类型
弱:当定义变量的时候,不需要声明数据类型,系统可以根据变量的值自动判别数据类型
>>> a = 10 >>> a 10 >>> type(a) #判断变量的类型全局函数 <class 'int'> >>> b = 3.14 >>> type(b) <class 'float'>
所以,在python中,将var也省略,直接通过变量名称=变量这种方式去声明即可
全局函数:
print() ------ 标准的输出函数,可以在控制台上进行输出某个字符串
type() ------- 返回的是变量的数据类型
2.1.3 变量的命名规范
1、变量名称只能由有效字符组成(大小写字母、数字、下划线)(name+ 会报错 语法错误)
2、不能以数字开头
3、不能是关键字或者保留字
4、变量命名尽量要有意义(name age gender)
小驼峰法(userName)
2.1.4 标识符的命名规范
标识符:对变量、常量、函数、类等对象起的名字
注意:python是一门弱数据类型语言,也是严格区分大小写的语言
命名规范:
第一个字符必须是字母表中的字母或者下划线,也是支持中文的
其他部分是有有效字符组成
对大小写敏感的
2.1.5 python 中的常量
不会变化的量就叫做常量
常量的名称最好全部是大写字母
>>> nationality = "中国" >>> max_num = 10000000000 --------- 这种写法不推荐 MAX_NUM = 100000 NATIONLITY = "中国"
2.2 python中的关键字
关键字:具有特殊含义的单词或者词组
保留字:目前的版本中还未使用的,但是未来可能会被使用,暂时保留,所以不建议使用
查看python中的关键字:
import keyword
>>> import keyword >>> dir(keyword) ['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'iskeyword', 'issoftkeyword', 'kwlist', 'softkwlist'] >>> keyword.kwlist ['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', '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'] >>> if = 1 File "<stdin>", line 1 if = 1 ^ SyntaxError: invalid syntax >>> or = 5 File "<stdin>", line 1 or = 5 ^ SyntaxError: invalid syntax
2.3 数据类型
python是一门弱数据类型语言,所以没有数据类型,这种说法是错误的
只是说不用去声明数据类型,但是是有数据类型的
分类:基本数据类型和复合数据类型(引用数据类型)
2.3.1 基本数据类型
数值型:
整数 int
浮点数 float
复数(虚数) ----- 一般用不到
布尔类型(bool)
判断条件成不成立?一般只有两种情况True和Flase
>>> true Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'true' is not defined >>> True True
字符串 (在Java这种强数据类型语言中字符串是一个对象,但是在python中字符串是一种数据类型)str
定义字符串: 单引号 双引号 三单引号 三双引号
字符串中可以包含任何语言
>>> s = 'hhhhh' >>> type(s) <class 'str'> >>> ss = "hhhhhh" >>> type(ss) <class 'str'> >>> sss = "我是中国人" >>> type(sss) <class 'str'>
ord() -------获取字符整数表示 ASCII值
chr() ------ 将编码转换为字符
>>> ord("A") 65 >>> ord("a") 97 >>> chr(65) 'A' >>> chr(25991) '文' >>> ord("中") 20013 >>> ord("文") 25991
如果字符串中包含 ' 怎么办
>>> print('I'm ok') File "<stdin>", line 1 print('I'm ok') ^ SyntaxError: invalid syntax >>> print("I'm ok") I'm ok >>> print('I\'m ok') I'm ok >>> print("\\") \
如果字符串有多行内容,第一种可以使用\n,第二种方式可以使用三引号
>>> print("""line1 ... line2 ... line3 ... line4""") line1 line2 line3 line4
2.3.2 复合数据类型(引用数据类型)
字典、列表、元组、集合
例子:写一段代码,输入一个数,判断这个数的数据类型
type() ---- 返回的是这个数的数据类型
input() ------ 标准的输入语句,默认的返回值是str类型
#写一段代码,输入一个数,判断这个数的数据类型 num = input("请输入一个数:") print(type(num))
2.4 数据类型的转换
字符串类型转换为整数类型 ------- int()
#写一段代码,输入一个数,判断这个数的数据类型 num = int(input("请输入一个数:")) print(type(num)) # temp = int(num) # print(type(temp))
字符串类型转换为浮点数类型 ---- float()
num = float(input("请输入一个数:")) print(type(num))
将其他类型转换为字符串类型 ------ str()
#写一段代码,输入一个数,判断这个数的数据类型 num = float(input("请输入一个数:")) print(type(num)) # temp = int(num) # print(type(temp)) print("num的值是:"+str(num))
字符串的拼接方式:
1、+ str(其他类型)进行拼接
2、可以使用逗号
3、%s占位符
# print("num的值是:"+num) # print("num的值是:",num) # print("num的值是%s"%(num)) num1 = int(input("请输入第一个数:")) num2 = int(input("请输入第二个数:")) sum = num1 + num2 print("%s和%s的和是%s"%(num1,num2,sum))
2.5 常见运算符
2.5.1 算术运算符
+ 加法运算 - 减法运算 * 乘法运算 / 除法运算 // 整除运算 % 取余运算 ** 幂次方运算
>>> a = 10 >>> b = 3 >>> a + b 13 >>> a - b 7 >>> a / b 3.3333333333333335 >>> a * b 30 >>> a // b 3 >>> a % b 1 >>> a ** b 1000 >>> 2 ** 3 8
2.5.2 关系运算符
两个数之间的关系 ,返回结果是boolean
> 大于 < 小于 >= 大于等于 <= 小于等于 == 等于 != 不等于
== 等于 比较的是两个变量的值是否相等
is ----- 比较的两个变量的地址是否相同
>>> a = 10 >>> b = 2 >>> a > b True >>> a < b False >>> a >= b True >>> a == b False >>> a != b True
2.5.3 逻辑运算符
多个表达式之间的关联关系,结果也是一个boolean
and 且 多个条件同时成立的时候结果为True
or 或 多个条件,至少有一个为真,结果就为True
not 非 取反,一般会和in关键字进行连用,表示判断元素是不是在某个容器里面
>>> a = 3 >>> b = 4 >>> c = 3 >>> a > b and b > c False >>> a > b or b > c True >>> list = [1,2,3,4] >>> 1 in list True >>> 5 in list False >>> 5 not in list True >>> 1 not in list False
2.5.4 赋值运算符
python中没有自加自减的运算
= 等于
+= 加等 a = a + 1 a += 1
-= 减等
*= 乘等
/= 除等
**= 乘方等
//= 整除等
2.5.5 身份运算符
is 判断两个标识符是不是引用同一个对象(内存地址)
is not
>>> a = [1,2,3] >>> b = a >>> b == a True >>> b [1, 2, 3] >>> b is a True >>> id(a) 2440474027200 >>> id(b) 2440474027200 >>> c = a[:] >>> c [1, 2, 3] >>> a [1, 2, 3] >>> b [1, 2, 3] >>> a == c True >>> b == c True >>> a == b True >>> a is c False >>> b is c False >>> a is b True >>> id(a) 2440474027200 >>> id(b) 2440474027200 >>> id(c) 2440474404096
2.5.6 成员运算符
in
not in
2.5.7 位运算符
把数字看作二进制数据进行的运算
a = 60
b = 13
a = 0011 1100
b = 0000 1101
& -------- 按位与运算,参与运算的两个数,如果两个对应的位置都为1则为1,否则为0 a & b = 0000 1100 | ------- 按位或运算,只要对应的位置有1则为1 a | b = 0011 1101 ^ ----- 按位异或运算,不同为1,相同为0 a ^ b = 0011 0001 ~ ----- 按位取反 << ------- 按位左移运算 a << 2 = 1111 0000 >> ------- 按位右移运算 a >> 2 = 0000 1111
>>> a = 60 >>> b = 13 >>> a & b 12 >>> a | b 61 >>> a ^ b 49 >>> a << 2 240 >>> a >> 2 15
2.5.8 三目运算符
判断条件?为真的时候的结果:为假的结果
result = 5 > 3 ? 1:0
在python中:为真的结果 if 判定条件 else 为假的结果
True if 5 > 3 else False
num1 = int(input("请输入第一个数:")) num2 = int(input("请输入第二个数:")) max = num1 if num1 > num2 else num2 print(max)
2.6 图形化设计
turtle模块
import turtle
>>> import turtle >>> dir(turtle) ['Canvas', 'Pen', 'RawPen', 'RawTurtle', 'Screen', 'ScrolledCanvas', 'Shape', 'TK', 'TNavigator', 'TPen', 'Tbuffer', 'Terminator', 'Turtle', 'TurtleGraphicsError', 'TurtleScreen', 'TurtleScreenBase', 'Vec2D', '_CFG', '_LANGUAGE', '_Root', '_Screen', '_TurtleImage', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__forwardmethods', '__func_body', '__loader__', '__methodDict', '__methods', '__name__', '__package__', '__spec__', '__stringBody', '_alias_list', '_make_global_funcs', '_screen_docrevise', '_tg_classes', '_tg_screen_functions', '_tg_turtle_functions', '_tg_utilities', '_turtle_docrevise', '_ver', 'addshape', 'back', 'backward', 'begin_fill', 'begin_poly', 'bgcolor', 'bgpic', 'bk', 'bye', 'circle', 'clear', 'clearscreen', 'clearstamp', 'clearstamps', 'clone', 'color', 'colormode', 'config_dict', 'deepcopy', 'degrees', 'delay', 'distance', 'done', 'dot', 'down', 'end_fill', 'end_poly', 'exitonclick', 'fd', 'fillcolor', 'filling', 'forward', 'get_poly', 'get_shapepoly', 'getcanvas', 'getmethparlist', 'getpen', 'getscreen', 'getshapes', 'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'inspect', 'isdown', 'isfile', 'isvisible', 'join', 'left', 'listen', 'lt', 'mainloop', 'math', 'mode', 'numinput', 'onclick', 'ondrag', 'onkey', 'onkeypress', 'onkeyrelease', 'onrelease', 'onscreenclick', 'ontimer', 'pd', 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position', 'pu', 'radians', 'read_docstrings', 'readconfig', 'register_shape', 'reset', 'resetscreen', 'resizemode', 'right', 'rt', 'screensize', 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle', 'setundobuffer', 'setup', 'setworldcoordinates', 'setx', 'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle', 'simpledialog', 'speed', 'split', 'st', 'stamp', 'sys', 'textinput', 'tilt', 'tiltangle', 'time', 'title', 'towards', 'tracer', 'turtles', 'turtlesize', 'types', 'undo', 'undobufferentries', 'up', 'update', 'width', 'window_height', 'window_width', 'write', 'write_docstringdict', 'xcor', 'ycor']
Turtle是Python内嵌的绘制线、圆以及其他形状(包括)文本的图形模块
常用的方法:
imoprt turtle #导入库文件
showturtle() #显示当前的位置和方向
write(string) #绘制一个文本字符串
forward(int) #向箭头方向移动int个像素并绘制直线
right(int) #转向int度数
color(string) #设置颜色
goto(int,int) #移到某个位置
penup() #抬起笔
pendown() #放下笔
circle(int) #绘制半径为int的圆
done() #绘制完毕
示例:
绘制三角形
import turtle as t t.pensize(10) t.right(60) t.forward(100) t.right(120) t.forward(100) t.right(120) t.forward(100) t.done()
绘制五角星
import turtle as t t.pensize(10) t.color("red") t.right(72) t.forward(100) t.right(144) t.forward(100) t.right(144) t.forward(100) t.right(144) t.forward(100) t.right(144) t.forward(100) t.done()
绘制五环
import turtle # 画布中心坐标为(0,0) turtle.pensize(10) # 画笔宽度 turtle.color("blue") turtle.penup() turtle.goto(-110, -25) turtle.pendown() turtle.circle(45) turtle.color("black") turtle.penup() turtle.goto(0, -25) turtle.pendown() turtle.circle(45) turtle.color("red") turtle.penup() turtle.goto(110, -25) turtle.pendown() turtle.circle(45) turtle.color("yellow") turtle.penup() turtle.goto(-55, -75) turtle.pendown() turtle.circle(45) turtle.color("green") turtle.penup() turtle.goto(55, -75) turtle.pendown() turtle.circle(45) turtle.done()