314598340 发表于 2018-8-14 06:00:05

python3 day7

  三层目录:
  功能要求:
  1. 输入即可进入下一层
  2. 按q退出
  3. 按b可以回退到上一层
  代码:
  #!/usr/bin/env python
  # -*- coding:utf-8 -*-
  menu={
  '山东':{
  '青岛': ['四方','市南','市北',],
  '济南':['历下','市中',],
  },
  '河南':{
  '郑州':['郑东新区','管城区'],
  '开封':['龙庭区','金明区'],
  }
  }
  Back_Flag=False#回退标志位
  Exit_Flag=False#退出标志位
  while not Back_Flag and not Exit_Flag:
  for key1 in menu:#打印第一级清单
  print(key1)
  choice1=input('Pls input the province: ').strip()
  if choice1 in menu: #如果输入正确,使用while循环打印第二级清单
  while not Back_Flag and not Exit_Flag:
  for key2 in menu:
  print(key2)
  choice2=input('Pls input the city: ').strip()
  if choice2 in menu:
  while not Back_Flag and not Exit_Flag:
  for key3 in menu:
  print(key3)
  choice3=input('Pls input the district: ').strip()
  if choice3 in menu:
  print(choice3)
  print('This is the Last level')
  else:
  print('Invalid input,pls input again')
  if choice3=='b':
  Back_Flag=True
  if choice3=='q':
  Exit_Flag=True
  else:
  Back_Flag=False
  else:
  print('Invalid input,pls input again')
  if choice2=='b':
  Back_Flag=True
  if choice2=='q':
  Exit_Flag=True
  else:
  Back_Flag=False
  else:
  print('Invalid input,pls input again')
  if choice1=='q':
  Exit_Flag=True
  优化后的代码:
  #!/usr/bin/env python
  # -*- coding:utf-8 -*-
  menu={
  '山东':{
  '青岛': {'四方':{},'市南':{},'市北':{},},
  '济南':{'历下':{},'市中':{},},
  },
  '河南':{
  '郑州':{'郑东新区':{},'管城区':{}},
  '开封':{'龙庭区':{},'金明区':{}},
  }
  }
  Current_Layer=menu
  Parent_Layer=[] #存放父层,便于b回退
  while True:
  for key in Current_Layer:
  print(key)
  choice=input('Pls input your choice: ').strip()
  if len(choice)==0:
  continue
  if choice in Current_Layer:
  Parent_Layer.append(Current_Layer)
  Current_Layer=Current_Layer
  elif choice=='b':
  if Parent_Layer:#回退时,如果父层不为空,就将父层最后一个元素赋值给当前层
  Current_Layer=Parent_Layer.pop()
  elif choice=='q':
  break
  else:
  print('无此项')
  python2默认ASCII,不支持中文
  python3默认unicode,支持中文
  utf-8,utf-16等也支持中文
  汉语字符集:
  gb2312:支持6700个汉字
  gbk:支持20000个汉字
  gb18030:支持27000个汉字,要求在中国发行的软件都支持gb18030
  python2中
  前提:CMD的属性中,当前代码页为“简体中文(GBK)”
  代码1:
  # -*- coding:utf-8 -*-
  s='中文'
  print s
  CMD执行结果:
  C:\Users\Carrick>C:\Python27\python.exe E:\py_code\py2_code\test1.py
  涓枃
  python2中,默认字符集为ASCII,开头指定utf-8,CMD终端字符集为gbk,gbk不认识utf-8,造成乱码
  解决办法一: # -*- coding:gbk -*-
  解决办法二:
  # -*- coding:utf-8 -*-
  s='中文'
  print s.decode('utf-8')-->指定从utf-8解码为unicode
  print s.decode('utf-8').encode('gbk')
  CMD执行结果:
  C:\Users\Carrick>C:\Python27\python.exe E:\py_code\py2_code\test1.py
  中文
  中文
  在python2中,默认字符集为ASCII,但是开头指定了utf-8,utf-8解码为unicode,unicode支持中文,因此可以显示中文
  从utf-8解码为unicode,然后从unicode编码为gbk,也能支持中文
  另外,如果开头不使用# -*- coding:utf-8 -*-,定义了中文字符串,总是会报错一个非ASCII的代码
  www.cnblogs.com/alex3714/articles/5717620.html
  缺一张图,
  python3
  代码:
  #!/usr/bin/env python
  import sys
  print(sys.getdefaultencoding())
  s='中文'
  print(s)
  执行结果:
  utf-8-->但是python官网说python3中的默认编码是unicode
  中文
  05看到12分钟
页: [1]
查看完整版本: python3 day7