day 2 notes and work

What is a module

sys module

import sys 
print(sys.path) 
# 打印环境变量  标准库(或安装的第三方库)就存在打印出的目录中 第三方库存在site-package中
>>>['D:\\BaiduNetdiskDownload\\新建文件夹\\源码', 'D:\\BaiduNetdiskDownload\\新建文件夹\\源码', 'D:\\software_programming\\PyCharm 2019.2.1\\helpers\\pycharm_display', 'C:\\Users\\15534\\python3.7\\python37.zip', 'C:\\Users\\15534\\python3.7\\DLLs', 'C:\\Users\\15534\\python3.7\\lib', 'C:\\Users\\15534\\python3.7', 'C:\\Users\\15534\\python3.7\\lib\\site-packages', 'D:\\software_programming\\PyCharm 2019.2.1\\helpers\\pycharm_matplotlib_backend']
# 系统有环境变量
# Python也有全局环境变量
print(sys.argv)
pritn(sys.argv[2])
#打印该文件的相对路径(pycharm)中打印绝对路径
#用命令行运行可以传参

os module (system interaction)

import os
os.system("dir") # 查看当前目录文件
cmd_res = os.system("dir") # 执行命令,不保存结果
cmd_res2 = os.popen("dir").read() #内存地址 read取出
print("---->",cmd_res)
print("---->",cmd_res2)

os.mkdir("new_dir")# 在当前地方创建目录
  • Default looking to find a module in the current directory, then the global variables could not find where to find
  • Solution
    • 1. The module is added to the path environment variable (after addition)
    • 2. Copy the module to the site-package

What is pyc

  • pyc file
    • Byte code files precompiled
  • Why fast second run py file
在说这个问题之前,我们先来说两个概念,PyCodeObject和pyc文件。
我们在硬盘上看到的pyc自然不必多说,而其实PyCodeObject则是Python编译器真正编译成的结果。我们先简单知道就可以了,继续向下看。
当python程序运行时,编译的结果则是保存在位于内存中的PyCodeObject中,当Python程序运行结束时,Python解释器则将PyCodeObject写回到pyc文件中。
当python程序第二次运行时,首先程序会在硬盘中寻找pyc文件,如果找到,则直接载入,否则就重复上面的过程。
所以我们应该这样来定位PyCodeObject和pyc文件,我们说pyc文件其实是PyCodeObject的一种持久化保存方式。

Python data types

1. Digital

  • Integer
    • 2
  • Long integer
    • But a large number of integer.
  • Float
    • 3.23 and 52.3E-4. E denotes a power of 10 marks. Here, 52.3E-4 represents a 52.3 * 10-4.
  • plural
    • (-5 + 4j) and (2.3-4.6j), where 5,4 is a real number, j is an imaginary number.
  • int (integer)

On 32-bit machines, the number of bits for 32-bit integer in the range of -2 31 to 2 31 - 1 ~ -2147483648 2147483647 i.e.

In the 64-bit system, 64 bits for an integer in the range of -2 63 to 2 63-1 ~ 9223372036854775807 i.e. -9223372036854775808

  • long (Long)

  C with different languages, Python long integer bit width is not specified, namely: Python does not limit the size of a long integer value, but in fact because of the limited memory machines, long integer value that we use can not be infinite.

  Note that since Python2.2 on, if integer overflow occurs, Python will automatically convert into a long integer integer data, so now without the letter L in the back of a long integer data does not lead to serious consequences of.

  • float (float)

First literacy http://www.cnblogs.com/alex3714/articles/5895848.html

For processing floating point real numbers, i.e. with decimals. Similar to the C language type double, 8 bytes (64 bits), wherein a bottom 52, 11 represents an exponent, and the remaining one represents a symbol.

2. Boolean value

  • Real or fake

  • 1 or 0

3. String

bytes of data types

bytes--decode--> string

sring--encode--> bytes

python3 all types of file transfer types are bytes

msg = "我爱北京天安门"
print(msg)
msg_byte = msg.encode("utf-8")
print(msg_byte)
pritn(msg_byte.decode("utf-8"))
# Python3中,encode/decode默认utf-8

Use the list

names = ["zhangyang", "Guyun", "Xiangpeng", "Xuliangchen"]

  • increase
names.append("LeiHaidong") #添加到末尾
names.insert(1,"chengronghua")#随意插入 如不写位置默认插在最前端
  • change
names[2] = "XieDi"#改
  • delete
names.remove("Chengronghua") # del names[1]
names.pop()# 默认删掉最后一个值,也可输入下标
  • check
print(names.index("XieDi"))
print(names[names.index("XieDi")])
  • slice
print(names)
print(names[0],names[2])
print(names[1:2]) # 切片 [1,2) 顾头不顾尾
print(names[-1]) #取最后一位
print(names[-2:]) #取最后两位
print(names[:3]) 
print(names[:3:1)
pritn(names[::2])   

print(names.count("Chengronghua"))
  • other
names.clear()#清空列表

names.reverse()

names.sort()#按特殊符号 数字 大写 小写(ASCII)排序

names.extend(names2)#合并
del names2
  • zip
>>> x = zip([1,2,3],[2,3,4])
>>> list(x)
[(1, 2), (2, 3), (3, 4)]
>>> for i,j in zip([1,2,3],[2,3,4]):
...     print(i,j)
...
1 2
2 3
3 4
  • copy of the list
names = ["zhangyang", "Guyun", "Xiangpeng", ["alex","jacl"], "Xuliangchen"]
names[2] = "向鹏"
names[3][0] = "ALEX"
names3 = names.copy() 
#浅copy 只copy第一层;第二层复制了内存地址,如此即使改names3的第二层names也会变
print(names)
print(names3)
>>>['zhangyang', 'Guyun', '向鹏', ['ALEX', 'jacl'], 'Xuliangchen']
['zhangyang', 'Guyun', 'Xiangpeng', ['ALEX', 'jacl'], 'Xuliangchen']
names = ["zhangyang", "Guyun", "Xiangpeng", ["alex","jacl"], "Xuliangchen"]
names3 = names
names[2] = "向鹏"
names[3][0] = "ALEX"
print(names)
print(names3)
>>>['zhangyang', 'Guyun', '向鹏', ['ALEX', 'jacl'], 'Xuliangchen']
['zhangyang', 'Guyun', '向鹏', ['ALEX', 'jacl'], 'Xuliangchen']
import copy
names = ["zhangyang", "Guyun", "Xiangpeng", ["alex","jacl"], "Xuliangchen"]
names3 = copy.copy(names) #深copy
names[2] = "向鹏"
names[3][0] = "ALEX"
print(names)
print(names3)
>>>['zhangyang', 'Guyun', '向鹏', ['ALEX', 'jacl'], 'Xuliangchen']
['zhangyang', 'Guyun', 'Xiangpeng', ['ALEX', 'jacl'], 'Xuliangchen']

循环:
for i in names:
    print(i)


import copy
person = ["name", ['a',100]]
# 浅copy
p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)
person = ["name", ['saving',100]]
# 浅copy的例子
p1 = person[:]
p2 = person[:]
p1[0] = 'alex'
p2[0] = 'fengjie'
p1[1][1] = 50
print(p1)
print(p2)

Tuple

  • Read-only list tuple
    • names = ('alex','jack')

      Shopping Cart Program

    product_list = [
      ('Iphone',5800),
      ('Mac Pro',9800),
      ('Bike',800),
      ('Watch',10600),
      ('Coffee',31),
      ('Alex Python',120),
    ]
    shopping_list = []
    salary = input("Input your salary:")
    if salary.isdigit():
      salary = int(salary)
      while True:
          for index,item in enumerate(product_list):
                                                      #enumerate使用方法:
                                                      # >>> a = [1,2,3]
                                                      # >>> for i in enumerate(a):print(i)
                                                      # ...
                                                      # (0, 1)
                                                      # (1, 2)
                                                      # (2, 3)
              #print(product_list.index(item),item)
              print(index,item)
          user_choice = input("选择要买嘛?>>>:")
          if user_choice.isdigit():
              user_choice = int(user_choice)
              if user_choice < len(product_list) and user_choice >=0:
                  p_item = product_list[user_choice]
                  if p_item[1] <= salary: #买的起
                      shopping_list.append(p_item)
                      salary -= p_item[1]
                      print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m" %(p_item,salary) )
                  else:
                      print("\033[41;1m你的余额只剩[%s]啦,还买个毛线\033[0m" % salary)
              else:
                  print("product code [%s] is not exist!"% user_choice)
          elif user_choice == 'q':
              print("--------shopping list------")
              for p in shopping_list:
                  print(p)
              print("Your current balance:",salary)
              exit()
          else:
              print("invalid option")

    String common operations

name = "my \tname is {name} and i am {year} old"

print(name.capitalize())
print(name.count("a"))
print(name.center(50,"-"))# 用-两边填补
print(name.ljust(50,'*')  )# 用*右边填补
print(name.rjust(50,'-')  )# 用-左边填补
print(name.endswith("ex"))# 判断
print(name.expandtabs(tabsize=30))
print(name[name.find("name"):]) #切片
print(name.format(name='alex',year=23)) 
print(name.format_map(  {'name':'alex','year':12}  ))#传字典进去
print('ab23'.isalnum()) #英文字符+阿拉伯数字
print('abA'.isalpha())  #纯英文字符
print('1A'.isdecimal()) #十进制
print('1A'.isdigit())   #整数
print('a 1A'.isidentifier()) #判读是不是一个合法的标识符
print('a 1A'.islower()) #小写
print('My Name Is  '.istitle()) #首字母大写
print('My Name Is  '.isprintable()) #tty file ,drive file
print('My Name Is  '.isupper()) #大写
print('+'.join( ['1','2','3'])  )
print( 'Alex'.lower()  )
print( 'Alex'.upper()  )
print( '\nAlex'.lstrip()  )#去空格和回车
print( 'Alex\n'.rstrip()  )
print( '    Alex\n'.strip()  )
p = str.maketrans("abcdefli",'123$@456') #对应置换
print("alex li".translate(p) )
print('alex li'.replace('l','L',1))
print('alex lil'.rfind('l')) #从左往右找到最远的值的下标
print('1+2+3+4'.split('+'))
print('1+2\n+3+4'.splitlines())
print('Alex Li'.swapcase()) #大小写互换
print('lex li'.title())
print('lex li'.zfill(50)) #用0从左边填充

Use a dictionary

info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
}
  • Increase / change
info["stu1101"] ="武藤兰"
info["stu1104"] ="CangJingkong"
# 判断是否有这个key
print('stu1103' in info)
info.has_key("1103")# Python2.x使用 
  • delete
del
del info["stu1101"]
info.pop("stu1101")
info.popitem()
print(info)
  • check
print(info["stu1101"])
print(info.get('stu1103')) #若无该key也不会报错

print(info.items() )
>>>dict_items([('stu1101', 'TengLan Wu'), ('stu1102', 'LongZe Luola'), ('stu1103', 'XiaoZe Maliya')])
  • Multi-level dictionary
av_catalog = {
    "欧美":{
        "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
        "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
        "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
        "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
    },
    "日韩":{
        "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    },
    "大陆":{
        "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    }
}

av_catalog["大陆"]["1024"][1] = "可以在国内做镜像" #改

av_catalog.setdefault("台湾",{"www.baidu.com":[1,2]}) #若无该key则添加
av_catalog.setdefault("大陆",{"www.baidu.com":[1,2]}) #若找到该key则不变
print(av_catalog)
  • Dictionary update
b ={
    'stu1101': "Alex",
    1:3,
    2:5
}

info.update(b)
print(info)
  • Dictionary initialization
c = dict.fromkeys([6,7,8],[1,{"name":"alex"},444]) #初始化一个字典
print(c)
c[7][1]['name'] = "Jack Chen"
print(c)
>>>{6: [1, {'name': 'alex'}, 444], 7: [1, {'name': 'alex'}, 444], 8: [1, {'name': 'alex'}, 444]}
{6: [1, {'name': 'Jack Chen'}, 444], 7: [1, {'name': 'Jack Chen'}, 444], 8: [1, {'name': 'Jack Chen'}, 444]}
  • for loop print dictionary
for i in info:
    print(i,info[i])

for k,v in info.items(): # info.items()速度慢 不建议使用
    print(k,v)

>>>
stu1101 TengLan Wu
stu1102 LongZe Luola
stu1103 XiaoZe Maliya

Three-level menu

This section Jobs - Shopping Cart Optimization

  • User entry
    • Exist commodity information file
    • Items purchased, the balance recorded
  • Business entry
    • You can add items, edit commodity prices

Guess you like

Origin www.cnblogs.com/randomdoor-2019/p/11668888.html