python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

一 大纲

2 运算符

3 基本数据类型

  整型:int

  字符串:str

  列表:list

  元组:tuple

  字典:dic

4 for enumrate xrange range

 上节内容回顾
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
  1、编程语言
  2、python、C#、java
  3、python:pypy,cpython,jpython..
  4、执行方式
解释器
文件
  5、指定解释器
  python xxx.py
  ./xxx.py   #!/usr/bin/env python
  6、ascii   unicode   utf-8
  7、
    2.7    # -*- coding:utf-8 -*-
    3.x    默认utf-8
  8、变量,代指
    变量名 = 值
    变量名要求:
    a.数字字母下划线
    b.数字不能开头
    c.不能和py关键字重复
    a = "alex"
    b = a
  9、条件
    if 条件,elif 条件,else
  10、while
    while 条件,
    从上到下执行一次
    (判断条件是否真)从上到下执行一次
    (判断条件是否真)从上到下执行一次
    (判断条件是否真)从上到下执行一次
    (判断条件是否真)从上到下执行一次

  

 二  前天作业讲解:

 知识点:

  判断奇偶:除以2取模

1 %
2 3%2=1
3 2%2=0
4 4%2=0

  详细见 url http://www.cnblogs.com/liujianzuo888/articles/5440915.html 

 三 编码转换

 

unicode 可以编译成 UTF-U GBK

 

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'Administrator'

a='刘建佐'        #默认是utf-8
a_unicod=a.decode('utf-8')  # decode是解码成unicode 括号是脚本内容的默认编码  即:将脚本内容的utf-8解码成unicode
a_gbk=a_unicod.encode('gbk') #encode是编码,将unicode的编码内容编码成指定的,这里是gbk
print(a_gbk)  #用于终端打印
#print(u"刘建佐")  #3里面是字符串  2里面是unicode 


# 3版本直接将utf-8编码成GBK 不需要先转成unicode了,因为3没有了

E:\py_test\s2_py>python3 test.py
Traceback (most recent call last):
File "test.py", line 6, in <module>
a_unicod=a.decode('utf-8') # decode是解码成unicode 括号是脚本内容的默认编码 即:将脚本内容的utf-8解码成unicode 
AttributeError: 'str' object has no attribute 'decode'


python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

 

四 pycharm 安装 配置

   file-setings-editor- file && file encode template  输入 

  

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'

 

五 pycharm 快捷键

   ctrl+/ 批量注释

  shift+方向键 选中 

  shift+tab 向左tab

六 运算符

算数运算:

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

比较运算:

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

赋值运算:

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

逻辑运算:

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

成员运算:

 python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

身份运算: 面向对象讲解

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

运算符

名称

说明

例子

+

两个对象相加

3 + 5得到8。'a' + 'b'得到'ab'。

-

得到负数或是一个数减去另一个数

-5.2得到一个负数。50 - 24得到26。

*

两个数相乘或是返回一个被重复若干次的字符串

2 * 3得到6。'la' * 3得到'lalala'。

**

返回x的y次幂

3 ** 4得到81(即3 * 3 * 3 * 3)

/

x除以y

4/3得到1(整数的除法得到整数结果)。4.0/3或4/3.0得到1.3333333333333333

//

取整除

返回商的整数部分

4 // 3.0得到1.0

%

取模

返回除法的余数

8%3得到2。-25.5%2.25得到1.5

<<

左移

把一个数的比特向左移一定数目(每个数在内存中都表示为比特或二进制数字,即0和1)

2 << 2得到8。——2按比特表示为10

>>

右移

把一个数的比特向右移一定数目

11 >> 1得到5。——11按比特表示为1011,向右移动1比特后得到101,即十进制的5。

&

按位与

数的按位与

5 & 3得到1。

|

按位或

数的按位或

5 | 3得到7。

^

按位异或

数的按位异或

5 ^ 3得到6

~

按位翻转

x的按位翻转是-(x+1)

~5得到-6。

<

小于

返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。

5 < 3返回0(即False)而3 < 5返回1(即True)。比较可以被任意连接:3 < 5 < 7返回True。

>

大于

返回x是否大于y

5 > 3返回True。如果两个操作数都是数字,它们首先被转换为一个共同的类型。否则,它总是返回False。

<=

小于等于

返回x是否小于等于y

x = 3; y = 6; x <= y返回True。

>=

大于等于

返回x是否大于等于y

x = 4; y = 3; x >= y返回True。

==

等于

比较对象是否相等

x = 2; y = 2; x == y返回True。x = 'str'; y = 'stR'; x == y返回False。x = 'str'; y = 'str'; x == y返回True。

!=

不等于

比较两个对象是否不相等

x = 2; y = 3; x != y返回True。

not

布尔“非”

如果x为True,返回False。如果x为False,它返回True。

x = True; not x返回False。

and

布尔“与”

如果x为False,x and y返回False,否则它返回y的计算值。

x = False; y = True; x and y,由于x是False,返回False。在这里,Python不会计算y,因为它知道这个表达式的值肯定是False(因为x是False)。这个现象称为短路计算。

or

布尔“或”

如果x是True,它返回True,否则它返回y的计算值。

x = True; y = False; x or y返回True。短路计算在这里也适用。

练习

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange View Code

 

大于 小于 左移右移 按位与 按位或

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
>>> 3>2
True
>>> 3<2
False
>>> 3>=2
True
>>> 3!=2
True
>>> print "数字变成2进制"
数字变成2进制
>>> 5<<2
20
>>> 5>>2
1
>>> 5 | 3
7
>>> 5 & 3
1
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
1 2 3 4  5  6  7  8
1 2 4 8 16 32 64 128
数组5转二进制 5=1+4
1 0 1   所以是5就是00000101
左移两位 5<<2
0 0 1 0 1 所以5<<2结果是20 即4+16=20
右移两位 5>>2
1          所以结果是1
按位与 5&3
5的二进制 101  3的二进制是110
1 0 1
1 1 0
得出结果 1 0 0 竖向看:1和1与是1,0和1与是0,1和0与是0,所以得出的结果是1
按位或 5|3
5的二进制 101  3的二进制是110
1 0 1
1 1 0
得出结果 1 1 1 竖向看:1和1或是1,0和1或是1,1和0或是1,所以得出的结果是1+2+4=7
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

 

七 基本数据类型

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

比如数字来说:

  数字的方法都放在int类中,而数字是类的实例化。 如上图所示

 

1 整型

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
n1=4
n2=4
print(n1.__add__(n2))

a=18
print("the num 18 's bit is:",a.bit_length())
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange View Code

 

2、布尔值
  真或假
  1 或 0
3、字符串
"hello world"
万恶的字符串拼接:
  python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。
字符串格式化
name = "alex"
print "i am %s " % name
  
#输出: i am alex

PS: 字符串是 %s;整数 %d;浮点数%f

字符串常用功能:  后面有练习
  • 移除空白
  • 分割
  • 长度
  • 索引
  • 切片
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange View Code

 

 示例
 
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'


a1 = "Alex"
print(a1.capitalize())

b="alex alex alex"
print(b.center(20,"*"))

print(b.count("le",1,9))
print(b.find("xxlex"))
print(b.istitle())
print(b.partition("le"))
print(b.replace("ale","ALE",2))
print(b.split("le",2))
print(a1.swapcase())
print(a1.upper())
print(a1.zfill(20))
print(a1.__add__("dfsf"))
s = " hell {0} ,age {1}"
print(s.format('alex',19))
print("字符串的分片",a1[0],a1[0:2],a1[0:])


注意: strip()
  1 可以去除两端空格
2 可以去除末尾\n
3 可以去除 空行
4 可以传如参数,比如
    n = “hello”
s = n.strip(“o”)
    print s 结果是 = ‘hell’
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

4、列表
创建列表:

 

name_list = ['alex', 'seven', 'eric']
或
name_list = list(['alex', 'seven', 'eric'])

基本操作:

  • 索引
  • 切片
  • 追加
  • 删除
  • 长度
  • 切片
  • 循环
  • 包含

 

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange View Code

示例:

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
###### 列表 ##########

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'


lis=[1,2,3,'alex']
cc=[5,5]
print(lis.count("alex"))
lis.extend(cc)
print(lis)

name_list = ["eirc", "alex", 'tony']
"""
# 索引
print(name_list[0])
# 切片
print(name_list[0:2])
# len
print(name_list[2:len(name_list)])
# for
for i in name_list:
    print(i)


#join 方法,拼接字符串
li = ["alex","eric"]
name = "li jie"
ss = "_".join(li)
s = "_".join(name)
print(s,ss)


"""
# 列表内部提供的其他功能
# append后追加
name_list.append('seven')
name_list.append('seven')
name_list.append('seven')
print(name_list)
# 元素出现的次数
print(name_list.count('seven'))
# iterable,可迭代的
temp = [111,22,33,44]
# 扩展,批量添加
name_list.extend(temp)
print(name_list)
# 获取指定元素的索引位置
print(name_list.index('alex'))
# 向指定索引位置插入数据
name_list.insert(1, 'SB')
print(name_list)
# 在原列表中移除掉最后一个元素,并将其赋值给 a1
a1 = name_list.pop()
print(name_list)
print(a1)
# 移除某个元素
name_list.remove('seven')
print(name_list)
# 翻转
name_list.reverse()
print(name_list)

# 删除指定索引位置
print(name_list)
del name_list[1:3]
print(name_list)
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

列表练习

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange View Code

 

  

 

5、元组
创建元祖: 元组一旦创建 不等增加也不能减少

 ages = (11, 22, 33, 44, 55) 或 ages = tuple((11, 22, 33, 44, 55)) 

基本操作:
索引
切片
循环
长度
包含

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange View Code

 

示例:

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
############### 元组 #################
name_tuple = ('alex', 'eric')
# 索引
print(name_tuple[0])
# len
print(name_tuple[len(name_tuple)-1])
# 切片
print(name_tuple[0:1])
# for
for i in name_tuple:
    print(i)
# 删除
# del name_tuple[0] 不支持
# count,计算元素出现的个数
print(name_tuple.count('alex'))
# index 获取指定元素的索引位置
print(name_tuple.index('alex'))
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
元组练习
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
不想别人改  默认变量 等。 别人调用你的程序元组。别人该你的不想改 用元组
只有两个方法
 c.count(
  c.index(

tuple(列表)列表变元组
>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d=tuple(a)
>>> d
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
list(元组)元组变列表
>>> d
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> e = list(a)
>>> e
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

 
6、字典(无序)
创建字典:
person = {"name": "mr.wu", 'age': 18}
或
person = dict({"name": "mr.wu", 'age': 18})

常用操作:

  • 索引
  • 新增
  • 删除
  • 键、值、键值对
  • 循环
  • 长度
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange View Code

 

 

示例: 

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'


dic={1:2,"alex":4,4:9}
print(dic.get("alex"))
print(dic.items())
print(dic.keys())
print(dic.values())
print(dic.pop(2,None))
print(dic.setdefault("name","rain"))

#
##################### 字典 ################### # 字典的每一个元素,键值对 user_info = { 0: "alex", "age": 73, 2: 'M' } # 0 “alex" # 1 73 # 索引 # print(user_info[0]) # print(user_info["age"]) # 循环,默认值输出key # for i in user_info: # print(i) # # 获取所有键 # print(user_info.keys()) # # 获取所有值 # print(user_info.values()) # # 获取所有键值对 # print(user_info.items()) # for i in user_info.keys(): # print(i) # # for i in user_info.values(): # print(i) # user_info = { # 0: "alex", # "age": 73, # 2: 'M' # } # for k,v in user_info.items(): # print(k) # print(v) # clear,清除所有内容 # user_info.clear() # print(user_info) # get 根据key获取值,如果key不存在,可以指定一个默认值 # val = user_info.get('age') # print(val) # val = user_info.get('age', '123') # print(val) # 索引取值时,key不存在,报错 # print(user_info['age']) # print(user_info['age1111']) # has_key 检查字典中指定key是否存在 3版本python没有了 可以用in 判断 # ret = 'agfffe' in user_info.keys() # print(ret) # pop # popitem # update # print(user_info) # test = { # "a1": 123, # 'a2': 456 # } # user_info.update(test) # print(user_info) # 删除指定索引的键值对 test = { "a1": 123, 'a2': 456 } del test['a1'] print(test)
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

PS:循环,range,continue 和 break

字典练习


python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange View Code

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange View Code

 

 

 

八 for 循环

1、for循环
用户按照顺序循环可迭代对象中的内容,
PS:break、continue
li = [11,22,33]
for i in li:
    print(li.index(i),i)

九 enumrate 

创建 *** 

li = [11,22,33]
for k,v in enumerate(li, 1):
    print(k,v)

十 range 和xrange

  迭代循环
  不会先在内存中创建,而是每次循环就创建一次。节约内存。
  3版本python只有range了,等同于xrange
 
指定范围,生成指定的数字
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
print range(1, 10)
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
 
print range(1, 10, 2)
# 结果:[1, 3, 5, 7, 9]
 
print range(30, 0, -2)
# 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]


例如 :
print(range(1,10))
  输出 range(1, 10) 而不是1 2 3.。。10
 
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
range用法:  stop不匹配

 range(start,stop,sep)

  比如 range(1,10,2)

    打印1 3 5 7 9 

  range(10,1,-1

      10 9 8 7 ... 2 
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

 

练习题

1、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

 

2、查找
查找列表中元素,移动空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
 
3、输出商品列表,用户输入序号,显示用户选中的商品  利用 enumrate
    商品 li = ["手机", "电脑", '鼠标垫', '游艇']
 
4、购物车

功能要求:

  • 要求用户输入总资产,例如:2000
  • 显示商品列表,让用户根据序号选择商品,加入购物车
  • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
  • 附加:可充值、某商品移除购物车
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 


 

5、用户交互,显示省市县三级联动的选择
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
dic = {
    "河北": {
        "石家庄": ["鹿泉", "藁城", "元氏"],
        "邯郸": ["永年", "涉县", "磁县"],
    }
    "河南": {
        ...
    }
    "山西": {
        ...
    }
 
}
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

答案:

 1 

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'
list_a=[11,22,33,44,55,66,77,88,99,111]
dic = { "k1":[],"k2":[]}
for i in list_a:
    if i <= 66:
        dic["k1"].append(i)
    else:
        dic["k2"].append(i)

print("\033[33;1m小于66的值:\033[0m%s \n\033[35;1m大于66的值:\033[0m%s " % (dic["k1"],dic["k2"]))
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 #易错点:

    if  a条件 or b条件 and c条件   

    如果分级的话用括号包起来

      if  (a条件 or b条件) and  c条件 

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

#!/usr/bin/env python # _*_ coding:utf-8 _*_ __author__ = 'liujianzuo' li = ["alec", " aric", "Alec", "Tony", "rain"] tu = ("adnc", " arlc", "Amx", "Tony", "rain") dic = {'k1': "arm", 'k2': ' apec', "k3": "Alc", "k4": "Tony"} a=[] b=[] c=[] for i in li: key_a=i.strip() if (key_a.startswith("a") or key_a.startswith("A")) and key_a.endswith("c"): a.append(key_a) for tup in tu: key_b = tup.strip() if (key_b.startswith("a") or key_b.startswith("A")) and key_b.endswith("c"): b.append(key_b) for key in dic.keys(): key_c = dic[key].strip() if (key_c.startswith("a") or key_c.startswith("A")) and key_c.endswith("c"): c.append(key_c) print("列表内的符合元素为:",a) print("元组内的符合元素为:",b) print("字典内内的符合元素为:",c)
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

3

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'
li = ["手机", "电脑", '鼠标垫', '游艇']
print("商品列表")
for i in enumerate(li,1):
    print(i[0],i[1])


while True:
    chose=input("请选择商品:").strip()
    if len(chose) == 0:
        print("\033[31;1m输入为空,清重新输入!!\033[0m")
        continue
    elif chose.isdigit() == True:
        break
    else:
        print("\033[31;1m你的输入为非数字,请重新输入\033[0m")
        continue
print("\033[31;1m选中的商品是:\033[0m",li[int(chose)-1])
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'
while True:
    salary = input("\033[33;1m请输入你的工资:\033[0m").strip()
    if len(salary) == 0:
        print("\033[31;1m工资不能为空重新输入~~\033[0m")
        continue
    elif salary.isdigit() != True:
        print("\033[31;1m输入必须是数字~~~\033[0m")
        continue
    else:
        break
salary = int(salary)
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]
def list_goods():
    print("\033[32;1m欢迎来到商城 ,商品列表:\033[0m")
    n = 1
    for i in goods:
        print(n, i["name"], i["price"])
        n += 1
list_goods()
shop_list = []
while True:
    chose = input("\033[33;1m输入选中的商品 输入 quit 离开:\033[0m").strip()
    if len(chose) == 0:
        print("\033[31;1m选择不能为空重新输入~~\033[0m")
        continue
    elif chose == 'quit':
        while True:
            print("\033[34;1m购物车列表,如果要移除请选择***\033[0m")
            for x in enumerate(shop_list, 1):
                print(x[0], x[1])
            del_list = input("\033[33;1m你可以移除商品,输入你的购物车商品编号, 输入 quit 离开:\033[0m")
            if len(del_list) == 0:
                print("\033[31;1m不能为空~~\033[0m")
                continue
            elif del_list == 'quit':
                break
            elif del_list.isdigit() != True:
                print("\033[31;1m必须是个数字\033[0m")
                continue
            elif int(del_list) > len(shop_list):
                print("\033[31;1m物品不存在\033[0m")
                continue
            del_list = int(del_list)
            for i in goods:
                if shop_list[del_list - 1] == i["name"]:
                    salary += i["price"]
                    print(
                        "\033[35;1m移除了商品:%s 返回现金:%s 元,目前余额:%s 元\033[0m" % (shop_list[del_list - 1], i["price"], salary))
            del shop_list[del_list - 1]
        break
    elif chose.isdigit() != True:
        print("\033[31;1m输入必须是数字~~~\033[0m")
        continue

    chose = int(chose)
    if chose > len(goods):
        print("\033[31;1m你选择的商品不存在!!\033[0m")
        continue
    if goods[chose - 1]["price"] <= salary:
        salary -= goods[chose - 1]["price"]
        shop_list.append(goods[chose - 1]["name"])
        print("\033[35;1m你选择了:%s 还剩下工资:%s 你的购物车内有:%s\033[0m" % (goods[chose - 1]["name"], salary, shop_list))
        continue
    else:
        print("\033[31;1m余额不够\033[0m")
        ans = input("你是否想充值?yes=充值 no=返回商城列表:")
        if ans == 'yes':
            while True:
                add_salary = input("输入你的充值额数:").strip()
                if len(add_salary) == 0:
                    add_salary = 0
                    break
                elif add_salary.isdigit() != True:
                    print("\033[31;1m输入必须是数字~~~\033[0m")
                    continue
                else:
                    break
            add_salary = int(add_salary)
            
            salary += add_salary
            print("\033[35;1m充值金额:%s 现在工资:%s 元 \033[0m" % (add_salary, salary))
        elif ans == 'no':
            list_goods()
            continue
balance = salary
if len(shop_list) < 1:
    shop_list = "0件"
print("\033[35;1m购买的商品: %s 余额是:%s\033[0m" % (shop_list, balance))
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

输出示例:

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

 

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
 1 #!/usr/bin/env python
 2 # _*_ coding:utf-8 _*_
 3 __author__ = 'liujianzuo'
 4 chinamap = {
 5     "山东省":{
 6         "济南":["市中区","历下区","天桥区","槐荫区","历城区","长清区","章丘市","平阴县","济阳县","商河县","其他"],
 7         "青岛":["市南区","市北区","城阳区","四方区","李沧区","黄岛区","崂山区","胶南市","胶州市","平度市","莱西市","即墨市","其他"]
 8     },
 9     "北京市":{
10         "北京":["东城区","西城区","崇文区","宣武区","朝阳区","海淀区","丰台区","石景山区","房山区","通州区","顺义区","昌平区","大兴区","怀柔区","平谷区","门头沟区","密云县","延庆县","其他"],
11     },
12     "广东省":{
13         "广州":["越秀区","荔湾区","海珠区","天河区","白云区","黄埔区","番禺区","花都区","南沙区","萝岗区","增城市","从化市","其他"],
14         "深圳":["福田区","罗湖区","南山区","宝安区","龙岗区","盐田区","其他"]
15     },
16     "河北省":{
17         "邯郸":[
18             "成安县","磁县","大名县","肥乡县","馆陶县","广平县","邯郸市","邯郸县","鸡泽县","临漳县","邱县","曲周县","涉县","魏县","武安市","永年县"
19         ],
20         "衡水":[
21             "安平县","阜城县","故城县","衡水市","冀州市","景县","饶阳县","深州市","武强县","武邑县","枣强县"
22         ],
23         "石家庄":[
24             "高邑县","晋州市","井陉县","灵寿县","鹿泉市","平山县","深泽县","石家庄市","无极县","辛集市","新乐市","行唐县","元氏县","赞皇县","赵县","正定县","藁城市","栾城县"
25         ]
26     }
27 }
28 chose=[]
29 def zero():
30     print("\033[31;1m选择不能为空,清重新输入~~\033[0m")
31 def crre():
32     print("\033[31;1m你的选择不正确,清重新输入~~\033[0m")
33 
34 print("\033[32;1m省列表如下:\033[0m\033[0m")
35 for key in chinamap.keys():
36     print(key)
37 while True:
38     sheng=input("\033[33;1m请输入省,quit for leave:\033[0m").strip()
39     if len(sheng) == 0:
40         zero()
41         continue
42     elif sheng == 'quit':
43         break
44     elif sheng not in chinamap.keys():
45         crre()
46         continue
47 
48     else:
49         chose.append(sheng)
50         print("\033[32;1m市列表如下:\033[0m")
51         for key_shi in chinamap[sheng].keys():
52             print(key_shi)
53         while True:
54             shi=input("\033[33;1m请输入市:quit for leave:\033[0m").strip()
55             if len(shi) == 0:
56                 zero()
57             elif shi == 'quit':
58                 print("\033[35;1m你选择的省:%s \033[0m"%(chose[0]))
59                 exit()
60             elif shi not in chinamap[sheng].keys():
61                 crre()
62             else:
63                 chose.append(shi)
64                 print("\033[32;1m县区列表如下:\033[0m")
65                 for key_xian in enumerate(chinamap[sheng][shi],1):
66                     print(key_xian[0],key_xian[1])
67                 while True:
68                     xian=input("\033[33;1m请输入县序号,quti for leave:\033[0m").strip()
69                     if len(xian) == 0:
70                         zero()
71                     elif xian == 'quit':
72                         print("\033[35;1m你选择的省:%s 市是:%s \033[0m"%(chose[0],chose[1]))
73                         exit()
74                     elif xian.isdigit() != True:
75 
76                         print("\033[31;1m必须是 数字\033[0m")
77                         continue
78                     elif int(xian) > len(chinamap[sheng][shi]):
79                         print("\033[31;1m选择不存在\033[0m")
80                         continue
81                     else:
82                         xian=int(xian)
83                         chose.append(chinamap[sheng][shi][xian-1])
84                         break
85                 break
86         break
87 if len(chose) < 1:
88     print("\033[35;1m你什么也没选~~!!\033[0m")
89 else:
90     print("\033[35;1m你选择的省:%s 市是:%s 县是:%s\033[0m"%(chose[0],chose[1],chose[2]))
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

 第5题 以***的选择 来输出

  知识点

    字典keys 转换为 list

  

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'liujianzuo'
chinamap = {
"山东省":{
"济南":["市中区","历下区","天桥区","槐荫区","历城区","长清区","章丘市","平阴县","济阳县","商河县","其他"],
"青岛":["市南区","市北区","城阳区","四方区","李沧区","黄岛区","崂山区","胶南市","胶州市","平度市","莱西市","即墨市","其他"]
},
"北京市":{
"北京":["东城区","西城区","崇文区","宣武区","朝阳区","海淀区","丰台区","石景山区","房山区","通州区","顺义区","昌平区","大兴区","怀柔区","平谷区","门头沟区","密云县","延庆县","其他"],
},
"广东省":{
"广州":["越秀区","荔湾区","海珠区","天河区","白云区","黄埔区","番禺区","花都区","南沙区","萝岗区","增城市","从化市","其他"],
"深圳":["福田区","罗湖区","南山区","宝安区","龙岗区","盐田区","其他"]
},
"河北省":{
"邯郸":[
"成安县","磁县","大名县","肥乡县","馆陶县","广平县","邯郸市","邯郸县","鸡泽县","临漳县","邱县","曲周县","涉县","魏县","武安市","永年县"
],
"衡水":[
"安平县","阜城县","故城县","衡水市","冀州市","景县","饶阳县","深州市","武强县","武邑县","枣强县"
],
"石家庄":[
"高邑县","晋州市","井陉县","灵寿县","鹿泉市","平山县","深泽县","石家庄市","无极县","辛集市","新乐市","行唐县","元氏县","赞皇县","赵县","正定县","藁城市","栾城县"
]
}
}
# n = list(chinamap.keys())
#print(n)
# m = list(chinamap[n[0]].keys())
# print(m)
# print(n[0])
# print(m[0])
# print(chinamap[n[0]][m[0]])
# exit()
chose=[]
def zero():
print("\033[31;1m选择不能为空,清重新输入~~\033[0m")
def crre():
print("\033[31;1m你的选择不正确,清重新输入~~\033[0m")


print("\033[32;1m省列表如下:\033[0m\033[0m")
# for key in chinamap.keys():
# print(key)
n = list(chinamap.keys())
n1 = []
shi_list=[]
xian_list=[]
for k,i in enumerate(n,1):
print(k,i)
n1.append(i)

# print("=================",n1)
while True:
sheng=input("\033[33;1m请输入省,quit for leave:\033[0m").strip()
if len(sheng) == 0:
zero()
continue
elif sheng == 'quit':
break
elif sheng.isdigit() != True:
print("\033[31;1m请选择一个数字~~~\033[0m")
continue
elif int(sheng)-1 >= len(n):
print("\033[31;1m选择不存在 out of range\033[0m")
continue
else:
sheng=int(sheng)

chose.append(n1[sheng-1])
print("\033[35;1m你进入省:%s \033[0m"%(chose[0]))
#print(chose)
print("\033[32;1m市列表如下:\033[0m")
shi_dic_list = list(chinamap[n1[sheng-1]])
#print(shi_dic_list)
for k,v in enumerate(shi_dic_list,1):
print(k,v)
shi_list.append(v)
# print("=============",shi_list)
while True:
shi=input("\033[33;1m请输入市:quit for leave:\033[0m").strip()
if len(shi) == 0:
zero()
elif shi == 'quit':
print("\033[35;1m你选择的省:%s \033[0m" % (chose[0]))
exit()
# elif shi not in chinamap[sheng].keys():
# crre()
elif shi.isdigit() != True:
print("\033[31;1m请选择一个数字~~~\033[0m")
continue
elif int(shi) -1 >= len(shi_dic_list):
print("\033[31;1m选择不存在 out of range\033[0m")
continue
else:
shi=int(shi)
chose.append(shi_list[shi-1])

print("\033[35;1m你进入省:%s 市是:%s \033[0m"%(chose[0],chose[1]))

# print(chose)
# exit()
print("\033[32;1m县区列表如下:\033[0m")
for key_xian in enumerate(chinamap[n1[sheng-1]][shi_list[shi-1]],1):
print(key_xian[0],key_xian[1])
xian_list.append(key_xian[1])
while True:
xian=input("\033[33;1m请输入县序号,quti for leave:\033[0m").strip()
if len(xian) == 0:
zero()
elif xian == 'quit':
print("\033[35;1m你选择的省:%s 市是:%s \033[0m"%(chose[0],chose[1]))
exit()
elif xian.isdigit() != True:

print("\033[31;1m必须是 数字\033[0m")
continue
elif int(xian) > len(chinamap[n1[sheng-1]][shi_list[shi-1]]):
print("\033[31;1m选择不存在 out of range\033[0m")
continue
else:
xian=int(xian)
chose.append(xian_list[xian-1])
break
break
break
if len(chose) < 1:
print("\033[35;1m你什么也没选~~!!\033[0m")
else:
print("\033[35;1m你选择的省:%s 市是:%s 县是:%s\033[0m"%(chose[0],chose[1],chose[2]))
python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange

输出截图

python 基础2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange