一.数据类型概述
数据类型比较
• 按存储模型分类
– 标量类型:数值、字符串
– 容器类型:列表、元组、字典
• 按更新模型分类:
– 可变类型:列表、字典
– 不可变类型:数字、字符串、元组
• 按访问模型分类
– 直接访问:数字
– 顺序访问:字符串、列表、元组
– 映射访问:字典
1.数字
1.1 基本数字类型
• int:有符号整数
• bool:布尔值
– True:1
– False:0
• float:浮点数
• complex:复数
1.2 数字表示方式
• python默认以十进制数显示
• 数字以0o或0O开头表示为8进制数
• 数字以0x或0X开头表示16进制数
• 数字以0b或0B开头表示2进制数
2. 字符串
2.1 定义字符串
• python中字符串被定义为引号之间的字符集合
• python支持使用成对的单引号或双引号
• 无论单引号,还是双引号,表示的意义相同
• python还支持三引号(三个连续的单引号或者双引号),可以用来包含特殊字符
• python不区分字符和字符串
2.2 字符串切片
• 使用索引运算符[ ]和切片运算符[ : ]可得到子字符串
• 第一个字符的索引是0,最后一个字符的索引是-1
• 子字符串包含切片中的起始下标,但不包含结束下标
>>> py_str = 'python'
>>> py_str[0]
'P'
>>> py_str[-2]
'o'
>>> py_str[2:4]
'th'
>>> py_str[2:]
'thon'
>>> py_str[:4]
'Pyth'
2.3 字符串连接操作
• 使用+号可以将多个字符串拼接在一起
• 使用*号可以将一个字符串重复多次
>>> py_str='python'
>>> is_cool='is Cool‘
>>> print py_str + ' ' + is_cool
python is Cool
>>> py_str * 2
'pythonpython'
- 列表
3.1 定义列表
• 可以将列表当成普通的“数组”,它能保存任意数量任意类型的python对象
• 像字符串一样,列表也支持下标和切片操作
• 列表中的项目可以改变
>>> alist = [1, "tom", 2, "alice"]
>>> alist[1] = 'bob‘
>>> alist[2:]
3.2 列表操作
• 使用in或not in判断成员关系
• 使用append方法向列表中追加元素
>>> alist = [1, "tom", 2, "alice"]
>>> 'tom' in alist
True
>>> 'alice' not in alist
False
>>> alist.append(3)
>>> alist[5]='bob'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
4.元组
4.1元组的定义及操作
• 可以认为元组是“静态”的列表
• 元组一旦定义,不能改变
>>> atuple = (1, "tom", 2, "alice")
>>> 'tom' in atuple
True
>>> atuple[0] = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError:'tuple' object does not support item assignment
5.字典
5.1字典的定义及操作
• 字典是由键-值(key-value)对构成的映射数据类型
• 通过键取值,不支持下标操作
>>> user_dict = {'name':'bob', 'age':23}
>>> use_dict['gender'] = 'male'
>>> 'bob' in user_dict
False
>>> 'name' in user_dict
True
>>> user_dict[0]
Traceback (most recent call last):
File "<stdin>", line 1,in <module> KeyError:0
二. 判断语句
1.if语句
1.1if语句语法结构
• 标准if条件语句的语法
if expression:
if_suite
else:
else_suite
• 如果表达式的值非0或者为布尔值True, 则代码if_suite被执行;否则就去执行else_suite
• 代码组是一个python术语,它由一条或多条语句组成,表示一个子代码块
1.2 if语句示例解析
• 只要表达式数字为非零值即为True
>>> if 10:
... print('Yes')
Yes
• 空字符串、空列表、空元组,空字典的值均为False
>>> if "":
... print('Yes')
... else:
... print('No')
No
- 扩展if语句
2.1 扩展if语句结构
if expression1:
if_suite
elif expression2:
elif_suite
else:
else_suite
2.2条件表达式
• Python 在很长的一段时间里没有条件表达式(C ? X :Y),或称三元运算符,因为范·罗萨姆一直拒绝加入这样的功能
• 从Python 2.5集成的语法确定为: X if C else Y
>>> x, y = 3, 4
>>> smaller = x if x < y else y
>>> print smaller
3
2.3.1案例:编写判断成绩的程序
• 创建grade.py脚本,根据用户输入的成绩分档,要求
如下:
1. 如果成绩大于60分,输出“及格”
2. 如果成绩大于70分,输出“良”
3. 如果成绩大于80分,输出“好”
4. 如果成绩大于90分,输出“优秀”
5. 否则输出“你要努力了”
[root@miss ~]# cat grade.py
score = int(input('成绩:'))
if score >= 90:
print('优秀')
elif score >= 80:
print('好')
elif score >= 70:
print('良')
elif score >= 60:
print('及格')
else:
print('你要每天努力了')
或
[root@miss ~]# cat grade2.py
score = int(input('成绩:'))
if score >= 60 and score < 70:
print('及格')
elif 70 <= score < 80:
print('良')
elif 80 <= score < 90:
print('好')
elif score >= 90:
print('优秀')
else:
print('你要努力了!')
2.3.2案例:编写石头剪刀布小游戏
编写game.py,要求如下:
1. 计算机随机出拳
2. 玩家自己决定如何出拳
3. 代码尽量简化
[root@miss ~]# cat game.py
import random
computer = random.choice(['石头', '剪刀', '布'])
player = input('请出拳(石头/剪刀/布):')
# print('您出了:', player, '计算机出的是:', computer)
print('您出了: %s, 计算机出的是: %s' % (player, computer))
if player == '石头':
if computer == '石头':
print('平局')
elif computer == '剪刀':
print('You WIN!!!')
else:
print('You LOSE!!!')
elif player == '剪刀':
if computer == '石头':
print('You LOSE!!!')
elif computer == '剪刀':
print('平局')
else:
print('You WIN!!!')
else:
if computer == '石头':
print('You WIN!!!')
elif computer == '剪刀':
print('You LOSE!!!')
else:
print('平局')
或
[root@miss ~]# cat game2.py
import random
all_choices = ['石头', '剪刀', '布']
win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]
prompt = '''(0) 石头
(1) 剪刀
(2) 布
请选择(0/1/2):'''
computer = random.choice(all_choices)
ind = int(input(prompt))
player = all_choices[ind]
print('您出了: %s, 计算机出的是: %s' % (player, computer))
if player == computer:
print('\033[32;1m平局\033[0m')
elif [player, computer] in win_list:
print('\033[31;1mYou WIN!!!\033[0m')
else:
print('\033[31;1mYou LOSE!!!\033[0m')
3.while循环
3.1循环概述
• 一组被重复执行的语句称之为循环体,能否继续重复,决定循环的终止条件
• Python中的循环有while循环和for循环
• 循环次数未知的情况下,建议采用while循环
• 循环次数可以预知的情况下,建议采用for循环
3.2while循环语法结构
• 当需要语句不断的重复执行时,可以使用while循环
while expression:
while_suite
• 语句while_suite会被连续不断的循环执行,直到表达式的值变成0或False
sum100 = 0
counter = 1
while counter <= 100:
sum100 += counter
counter += 1
print ("result is %d" % sum100)
3.3 break语句
• break语句可以结束当前循环然后跳转到下条语句
• 写程序的时候,应尽量避免重复的代码,在这种情况下可以使用while-break结构
name=input('username: ')
while name != 'tom':
name = input('username: ')
#可以替换为
while True:
name = input('username: ')
if name == 'tom':
break
3.4 continue语句
• 当遇到continue语句时,程序会终止当前循环,并忽略剩余的语句,然后回到循环的顶端
• 如果仍然满足循环条件,循环体内语句继续执行,否则退出循环
sum100=0
counter=0
while counter <= 100:
counter += 1
if counter % 2:
continue
sum100 += counter
print("result is %d" % sum100)
3.5 else语句
• python中的while语句也支持else子句
• else子句只在循环完成后执行
• break语句也会跳过else块
sum10 = 0
i = 1
while i <= 10:
sum10 += i
i += 1
else:
print (sum10)
3.6案例:完善石头剪刀布小游戏
编写game2.py,要求如下:
1. 基于上节game.py程序
2. 实现循环结构,要求游戏三局两胜
[root@miss ~]# cat game3.py
import random
all_choices = ['石头', '剪刀', '布']
win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]
prompt = '''(0) 石头
(1) 剪刀
(2) 布
请选择(0/1/2):'''
pwin = 0
cwin = 0
while pwin < 2 and cwin < 2:
computer = random.choice(all_choices)
ind = int(input(prompt))
player = all_choices[ind]
print('您出了: %s, 计算机出的是: %s' % (player, computer))
if player == computer:
print('\033[32;1m平局\033[0m')
elif [player, computer] in win_list:
pwin += 1
print('\033[31;1mYou WIN!!!\033[0m')
else:
cwin += 1
print('\033[31;1mYou LOSE!!!\033[0m')