Python section II

Source: Internet
Author: User

Module Initial Knowledge  
    • Python's strength is that he has a very rich and powerful standard library and third-party library, almost any function you want to implement has the corresponding Python library support, later in the course will be in depth to explain the various libraries commonly used, now, we first to symbolically learn 2 simple.
    • Standard library: No need to install direct import
    • Third party libraries: must install the download

Standard library Modules:

    • SYS module
# AUTHOR:XP
Import Sysprint (Sys.path) #打印环境变量print (SYS.ARGV) #打印相对路径
Print (sys.argv[2])
    • OS Module
# AUTHOR:XP
Import oscmd_res = Os.system ("dir") #执行命令不保存结果cmd_res = Os.popen ("dir"). Read () #执行命令保存结果print ("--", cmd_res) Os.mkdir ("New_dir") #创建目录哭
What is PYC?

Brief description of Python's running process

Before we say this question, let's start with two concepts, pycodeobject and PYC files.

The PYC we see on the hard drive naturally doesn't have to say much, and pycodeobject is actually the result of a Python compiler actually compiling it. Let's just get to the bottom of it and keep looking down.

When the Python program runs, the result of the compilation is saved in the Pycodeobject in memory, and when the Python program finishes running, the Python interpreter writes Pycodeobject back to the PYc file.

When the Python program runs for the second time, the program will first look for the PYc file on the hard disk, and if it is found, load it directly or repeat the process.

So we should be able to locate Pycodeobject and pyc files, we say that PYc file is actually a kind of persistent saving way of pycodeobject.

Data type:

int: (Shaping)
Long: (Python3) "--(NO)
float: (decimal and floating point) floating-point numbers are used to process real numbers, that is, digits with decimals. Similar to the double type in C, accounting for 8 bytes (64 bits), where 52 bits represent the bottom, 11 bits represent the exponent, and the remaining one represents the symbol.

Boolean value: "True: True (1)" or "false: False (0)"

list: To Create a list: names  = [ ‘ZhangYang‘ ‘GuYun‘ ‘xp‘,‘liangcheng‘ ]Print (names[1],names[2]) #切片: (check) print (Names[1:3]) Guyun XP #反向取值切片: Print (names[-2:]) XP Liangcheng hint: value before and after (plus or minus) Subscript 0 can omit this 0 such as: [2:], [-2:] #不长切片 print (Names[::2]) #插入 (Increase) Names.insert (1, "Nihao") Names.insert (3, "Keyi") #改 NA MES[2] = "Xiedi" #删 del names[1] Names.remove (XP) #查找一个用户的位置点 print (Names.index ("XP")) Print (Names[names.index ( "XP")]) #查找统计列表中的重复字符串的数量 print (Names.count ("XP")) #清空列表 names.clear () #反转列表: Names.reverse () #按字母顺序排序 "Special symbols-- --Capital letter---lowercase "names.sort () #列表合并: Names2 = [1,2,3,4] Names.extend (names2) ##copy模块:       Import Copy names =  [‘ZhangYang‘‘GuYun‘‘xp‘,‘liangcheng‘ ]#三种浅拷贝: n1=copy.copy (names) n2=name[:]        n3=list (names)#深拷贝: name2 = copy.deepcopy (names) Meta-group

(Immutable list)

To create a tuple: ages  = ( 11 22 33 44 55 )Program Exercises

Please close your eyes and write the following procedure.

Program: Shopping Cart Program

Demand:

    1. After you start the program, let the user enter the payroll, and then print the list of items
    2. Allow users to purchase items based on their product number
    3. After the user selects the product, checks whether the balance is enough, enough on the direct debit, enough to remind
    4. You can exit at any time to print the purchased goods and balances when exiting
#Author: xpproduct_list = [(' Iphone ', 5800), (' Mac Pro ', 9800), (' Watch ', 10600), (' Bike ', "31"), (' Alex Python ',]shopping_list=[]salary = input ("Enter Payroll:") if Salary.isdigit (): salary = Int (salary) while True        : For Index,item in Enumerate (product_list): Print (index,item) User_choice = input ("SELECT Product:")  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 s Hopping Cart,your current balance is \033[31;1m%s\033[0m "% (p_item,salary)) Else:print (" \033[41;1m your balance remains [%s], and buy a sweater \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 (1) else:print ("Invalid option") 
string Common operations:
#首字母大写 #查看有几个相同的字符串Print (Name.center, "-")#打印50个字符不够的话用 '-' full #以什么结尾print (name.expandtabs (tabsize=30)) #转成多少个 "Here is 30" Space print (Name.find (name))#找字符串的索引 #大写转换成小写print (' Xp '. Upper ())# Lowercase converted to uppercase print (Name.format (name= ' Xp ', year=123)) #print (Name.format_map ({' Name '; Xp ', ' year ';)) print ('  ab23 '. Isalnum ()) print (' AbA '. Isalpha ()) print (' 1.23 '. Is_integer ()) print (' A 1 a '. Isidentifier ())#判断是不是一个合法的标识符
Dictionary operation:

A key-value data type, used as a dictionary of our school, to check the details of the corresponding page by strokes and letters.

Grammar:

info = {    ' stu1101 ': ' Tenglan Wu ',    ' stu1102 ': ' Longze luola ',    ' stu1103 ': ' Xiaoze Maliya ',}
# info["stu1101"] = "Enrique" #改
# info["stu1104"] = "Cangjinkong" #该字符串存在就修改不存在就添加
#print (info["stu1101"]) #查
#del info["stu1101") #删除
#info. Pop ("stu1101") #判断字典里是否有数据
#info. Popitem ("stu1101") #随机删除也可指定
#print (Info.get (' stu1104 ')) #在字典里精确查找
#print (' stu1104 ' in info) #判断字典里是否有此字符串
#info Has_key (' 1103) #py2.7 to determine if there is a string in the dictionary

Features of the dictionary:

    • Dict is disordered.
    • Key must be unique and so is inherently heavy

Cycle:

info = {    ' stu1101 ': ' Tenglan Wu ',    ' stu1102 ': ' Longze luola ',    ' stu1103 ': ' Xiaoze Maliya ',}
For I in (info):    print (I,info[i])

  

Python section II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.