# author:source#-*-coding:utf-8-*-#使用第三方库, import library name ' Import getpasspassword=getpass.getpass (' please input your Password: ') print (password) "#自己建一个库 to make it work in the same directory, or on Site-packages (third party libraries). If you are in a different directory, you need to add a new path. "' Account=input (' Input account! '). Capitalize ()) Password=input (' Import something '. Capitalize ()) ' #模块初识 (OS module) OS module is to operate the operating system import osos.system (' dir ') #打印当前目录名称信息, the result is output directly to the screen and cannot be saved. Cmd_res=os.popen (' dir ') #内存的对象地址 #os.mkdir (' attempt ') #创建文件夹 #print (Cmd_res.read ()) #模块初识 (SYS module) import sysprint ( Sys.path) #打印环境变量, the address of the module, print (SYS.ARGV) #脚本相对路径, takes the parameter # compiled language is before the program executes, first through the compiler to the high-level language into the machine can read machine language. No translation is required at the time of execution, and direct execution is possible. #典型的例子是C语言. An interpreted language is an interpreter that interprets a program on a line-by-row basis and then runs directly. Python is also a language that is compiled and interpreted first. #Python运行过程: When the Python program runs, it saves the compilation results to the Pycodeobject in memory, and the Python interpreter writes the results to the PYc file at the end of the run. #下次运行程序时, the Python program will first check the PYc file on the hard disk, otherwise repeat the above action. When the program is updated, the update time of the PYc file and the source program is checked. #数据类型. Integers, long integers are relatively large numbers. 3.24 is a floating-point number, and 5.24E-4 refers to 5.24*10^-4. #int类型. In 32-bit -2**32--2**32-1, 64 is -2**63--2**63-1. #long (Long Integer), python2.2. #三元运算 ' number=input (' please input a number: ') if Number.isdigit (): number=int (number) result = ' adult '. Capitalize () If number>=18 else ' nonage '. Capitalize () print (Result) ' #进制转换 # # Binary conversion to 16, take four-in-one method, that is, from the binary decimal point is the dividing point, left (or right) every four bits. When you get the highest bit (lowest bit) If # cannot make up four bits, you can fill 0 on the leftmost (or rightmost) of the decimal point and convert it. #十六进制用字母H表示 can also be represented by a 0X prefix, such as 0X. #十六进制转二进制. method is a copy of four, that is, a hexadecimal number is divided into four binary numbers. "' Number_decimalism=input (' please input a decimalism numeral: ') if Number_decimalism.isdigit (): number_decimalism= int (number_decimalism) print (' Decimal number: ', number_decimalism) print (' Convert to binary: ', Bin (number_decimalism)) print (' Convert to octal number: ', Oct (number_decimalism)) print (' Convert to 16 binary: ', Hex (number_decimalism)) else:print (' \033[31;1mplease input legal numeral !\033[0m ') ' #字符串str与二进制bytes转换 #string through encode into bytesconding= ' S12 '. Encode (' Utf-8 ') print (conding) # Bytes by decode programming Stringprint (Conding.decode ()) #列表元组操作 # Create a list of contents separated by commas list=[' Datou ', ' Erbai ', ' Sanmao ', ' Lisi ', ' Wangwu '] #切片操作, Gu Tou regardless of tail print (list) print (list[2]) #切片第三个print (List[0:2]) #切片前两个print (List[:2]) #切片前两个print (List[1:4]) # Slice Middle three print (List[2:5]) #切片最后三个print (list[2:]) #切片最后三个print (list[-1]) #切片最右边一个print (list[-3:]) #切片最右边三个 # Add Operation list.append (' Liuliu ') #直接添加list. Insert (1, ' ErB ') #指定位置添加print (list) # Modify List value list[1]= ' zhenerb ' Print (list) #删除list. Remove ("Lisi") print (list) del list[1]print (list) list.pop (0) print (list) # Look for print (List.index ("Wangwu")) #显示查询数据在列表位置, use the subscript of the list to indicate print (List[list.index ("Wangwu")) #统计print (List.count (' Liuliu ') #清空print (List.clear ()) #添加list. Append ("Jiaren") print (list) list.insert (0, ' jialing ') print (list) #反转list. Reverse () print (list) #排序, the collation may be the type of the first character, some special characters > numbers > Another special character > English > Chinese list.append (' 12a ') list.append (' A2 ') List.append (' >a1 ') list.append (' B2 ') list.append (' &a2 ') list.append (' 2b ') list.append (' <s2 ') list.append ( ' Chinese ') list.append (' Translate ') List.sort () print (list) #反转fake_list =[' Wanglaoban ', [' Lidatou ', ' Find Me '], ' xiaxiage ']print ( List) print (fake_list) print (fake_list[1][1]) list.extend (fake_list) print (list) #浅COPYimport copynew_list=[' Dageda ' , [' Xiaobudian ', ' Dabudian '], ' sanmaoge ', ' zaodiansi ', ' Wanglaowu ']shallow1=copy.copy (new_list) #方法一copy_new_list = New_list.copy () #方法二shallow2=new_list[:] #方法三print (copy_new_list) print (new_list) copy_new_list[1][1]= ' changed one piece to ' print ' (copy_new_list) print (new_ List) print (SHALLOW1) print (shallow2) #深copyimport copydeep_copy_new_list=copy.deepcopy (new_list) print (deep_copy_ new_list) print (new_list) deep_copy_new_list[1][1]= ' This time can be changed ' print (deep_copy_new_list) print (new_list) # String manipulation attempt= ' gJy121 ' Print (Attempt.capitalize ()) #将首字母变为大写print (Attempt.casefold ()) #将大写字母全部变为小写字母print ( Attempt.center (50, '. ')) #设置一个范围, and then fill the remaining space with a symbol print (Attempt.count (' G ')) #统计字符出现的次数, you can choose to start with the end as position print (Attempt.encode (' GB18030 ')) # Specifies the encoding to compile print (' gjy121\t gg '. Expandtabs ()) #指定空格的长度print (Attempt.endswith (' 1 ')) #结束的标志是否是该字符. Yes true, wrong falseprint (' My Name is {name} and my occupation is {occupation}. '. Format (name= ' GJY ', occupation= ' habitual loafer ')) #Methods 1print (' My Name is {0} and my occupation is {1}. '. Format (' GJY ', ' habitual loafer ')) #Methods 2,{} starts from 0 print (Attempt.find (' 2 ', 0,5)) #Python the Find () method detects if the string contains substrings of STR, If you specify the Beg (start) and end (end) ranges, # checks to see if it is contained within the specified range, or returns 1 if the containing substring returns the starting index value. prInt (' My Name is {name} and my occupation is {occupation}. '. Format_map ({' Name ': ' GJY ', ' occupation ': ' Habitual loafer ')) print (Attempt.index (' G ')) #查询目标的第一个下标, there is no error print ( Attempt.isdigit ()) #查询是否是数字print (Attempt.isalnum ()) #检测字符串是否由字母和数字组成. Print (Attempt.isalpha ()) #所有字符都是字母则Trueprint (Attempt.isdecimal ()) #Python the Isdecimal () method to check whether the string contains only the decimal character print ( Attempt.isidentifier ()) #检测字符串是否是字母开头print (Attempt.islower ()) #Python the Islower () method to detect whether a string consists of lowercase letters. Print (Attempt.isnumeric ()) #Python the IsNumeric () method to detect whether a string consists of only numbers. This method is only for Unicode objects. Print (Attempt.isprintable ()) #判断是否为可打印字符print (Attempt.isspace ()) #Python the Isspace () method detects whether a string consists of only spaces. Print (Attempt.istitle ()) #Python the Istitle () method detects that all words in a string are spelled in uppercase, and that the other letters are lowercase. Print (Attempt.isupper ()) # #Python The Isupper () method detects whether all letters in a string are uppercase. Print (' + ', ' 6 ', ' 98 ')) #Python the Isupper () method to detect whether all the letters in the string are uppercase. Print (' + '. Join (' 246810 ')) print (Attempt.ljust ($)) #Python the Ljust () method returns the left alignment of the original string and fills the new string with a space to the specified length. Returns the original string if the specified length is less than the length of the original # string. Print (attempt.rjust, '% ')) #Python the Rjust () method returns an original characterString to the right, and fills the new string with a space to the specified length. Returns the original string if the specified length is less than the length of the original # string. Print (Attempt.lower ()) #Python the lower () method converts all uppercase characters in a string to lowercase. The print (Attempt.swapcase ()) #swapcase () method is used to convert the uppercase and lowercase letters of a string. Print (' \nstrip '. Lstrip ()) #Python the Lstrip () method to truncate the left space of the string or specify the character. Print (' strip\n '. Rstrip ()) #Python the Rstrip () method to truncate the space to the right of the string or specify the character. Print (' \nstrip \ n '. Strip ()) #截断字符串左右两边的空格或指定字符. The #Python Maketrans () method is used to create a conversion table of character mappings, for the simplest way to invoke # Two parameters, the first parameter is a string that represents the character that needs to be converted, and the second argument is the target of the string representation transformation. plaintext= ' 123456 ' encrypt= ' abcdef ' A=str.maketrans (plaintext,encrypt) example= ' 852643 ' Print (Example.translate (a) Print (' source123 '. partition (' 1 ')) #partition () method is used to split the string according to the specified delimiter. The #Python replace () method replaces the old string in the string with the new one, and if you specify the third parameter max, the replacement does not exceed Max times. Print (' source123 '. Replace (' so ', ' re ')) print (' Heafafaeh '. RFind (' h ')) #Python RFind () returns the position of the last occurrence of the string, or 1 if there is no match. Print (' finally '. Rindex (' lly ')) #Python Rindex () returns the substring of STR in the last occurrence of the string, # If there is no matching string to report the exception, you can specify an optional parameter [Beg:end] to set the search interval. Print (' FADF12SA1 '. Rpartition (' 1 ')) #partition () method is used to split the string according to the specified delimiter. From right to left. #与pArtition difference print (' FADF12SA1 '. partition (' 1 ')) #Python the Rsplit () method splits the string by specifying a delimiter and returns a list with the default delimiter of all null characters, #包括空格, line break (\ n), tab (\ t) and so on. Similar to the split () method, except that the split begins at the end of the string. Print (' faf\tafd\n123. Rsplit ()) #Python Splitlines () separated by line (' \ r ', ' \ r \ n ', \ n '), # Returns a list containing the rows as elements, if the argument keepends to False , does not contain a newline character, and if true, the newline character is preserved. Print (' Faf\rafd\n123\r\n44 '. Splitlines (True)) print (' FADF12SA1 '. Split (' 1 ')) #Python split () slices the string by specifying a delimiter, if the parameter NUM has a specified value, it separates only num substring # from partition: Split does not contain the delimiter #python StartsWith () method is used to check whether the string starts with the specified substring, or returns False if it is true,# otherwise. If the parameter beg and end specify a value, the check is within the specified range. Print (Attempt.startswith (' gJy ')) print (' Hello world! '). Title ()) #Python the title () method returns a "caption" string, meaning that the first letter of all words is converted to uppercase and the remaining letters are lowercase print (attempt.upper ()) #Python Upper () method to convert lowercase letters in a string to uppercase. Print (Attempt.zfill) #Python the Zfill () method returns a string of the specified length, the original string is right-aligned, and the front padding 0# dictionary operation dictionary={' casual1 ': ' Number1 ', ' Casual2 ' : ' Number2 ', ' casual3 ': ' Number3 ', ' casual4 ': ' Number4 '}print (dictionary) #查字典print (dictionary[' Casual3 ']) # To go to the key value correct print (Dictionary.get (' Casual2 ')) print (' CAsuall ' in dictionary) #改字典dictionary [' Casual1 ']= ' yanghuizhen ' dictionary[' cannot ' to help but ']= ' Yang Hui Zhen '. Title () # Does not exist add print (dictionary) #删除dictionary. Pop (' cannot help but ') del dictionary[' Casual4 ']print (dictionary) Dictionary.popitem () #重新运行会重新随机删除print (dictionary) #多级字典嵌套操作 ' message={' Source ': {' age ': ['] ', ' educatio N Background ': {' Yango University ': [' Graduate '}}, ' Yang ': {' age ': [' + '], ' interset ': [' to ' I know Nothing on. '] }} #查字典print (Message.get (' source ')) print (message[' Yang ' [' Age ']) print (' source ' in message) #改字典message [' Source '] [' Age '. Lower ()]= ' Message.setdefault (' Hero ', {' age ': ['], ' significance ': [' I don ' know. ') '. Capitalize ()]}) #添加print (message) "Print (dictionary) print (dictionary.values ()) print (Dictionary.keys ()) reserve= {' Pengfei ': ' Zui Shuai '. Capitalize ()}dictionary.update (reserve) print (dictionary, ' \ n ', reserve) #items将字典转化为列表print (dictionary) The print (Dictionary.items ()) #fromkeys () function is used to create a new dictionary that is the key to the dictionary of elements in the sequence SEQ, value is the initial value corresponding to all keys in the dictionary. Dictionary2=dict.fromkeys ([1,2,3],[' A ', ' B ', ' C ']) print (dictionary2) dictionary2[1][1]= ' x ' Print (DICTIONARY2) # Loop Dictdictionary.items () for items in Dictionary:print (Items,dictionary[items]) for items,i in Dictionary.items (): PR Int (items,i) #New shopping:# author:sourcefile_money=open (' money.txt ', mode= ' R ') Read_file_moeny=file_money.read () Print (' Your balance has: ', read_file_moeny) if read_file_moeny== ': While True:salary=input ("Please input y Our salary: ") if Salary.isdigit (): Salary=int (Salary) Break Else:print (' Te XT is not a legal character. Capitalize ()) Continueelse:if read_file_moeny.isdigit (): Read_file_moeny=int (Read_file_moeny) Salary=read_file_moeny Else:print ("text is not a legal character."). Capitalize ()) commodity=[("Iphonex". Title (), 8388), ("ipad mini4". Title (), 2400), ("Dragon Fruit". Title (), 6), (" Alkaline Mineral Water ". Title (), 2), (" toothpaste ". Title (), 12),]shopping_cart=[] #print (commodity) while True:for item in Commodity:print (Commodity.index (item), item) #for I , item in Enumerate (commodity): #python for in # Print (I,item) number=input ("Fancy a Commodity:") if number.is Digit (): number=int (number) print (LEN (commodity)) if Number<len (commodity) and number>=0: List_price=commodity[number] If list_price[1] <= salary:shopping_cart.append (list_pric e) salary-=list_price[1] Print ("You aleady buy%s and your balance has \033[31;1m%s\033[0m. "% (shopping_cart,salary)) else:print (" \033[31;1myour balance is not enough.\033[0m ") If Commodity[3][1]>salary:while true:print (' \033[31;1myou don\ ' not ha ve much Monty. Do your want to increase your savings?\033[0m '. Capitalize ()) Increase=input (' Y or N ') IF increase== ' Y ': While True:salary=input (' How to much money does you Want to deposit? '. Capitalize ()) if Salary.isdigit (): Salary=int (Salary) Break Else:print (" 33[31;1millegal character.\033[0m ". Capitalize ()) Continue elif I ncrease== ' N ': Break else:continue Els E:print ("\033[41;1mfollow option\033[0m") elif number== ' Q ': Print ("You aleady buy%s and your Balanc E has \033[31;1m%s\033[0m. "% ( shopping_cart,salary)) File_money=open (' Money.txt ', mode= ' W ') File_money.write (str (salary)) File_commo Dity=open (' Commodity.txt ', mode= ' a ') file_commodity.write (str (shopping_cart)) exit () Else:print ("\033[31;1minput error!\033[0m")
Python Learning Path Second week summary