List Builder
Definition: The amount can be abbreviated loop code. For example 1:
result = [ i+1 for i in range(1,20)] print(result)
=== "is split into the following
result = [] for i in range(1,20): result2.append(i+1) print(result)
Execution order
Example 2: the first loop, and then determine the execution condition (condition can be added later in the cycle), and finally perform operations, and finally returns to the list
* Str (i) .zfill (2) zero-padding operation digit string
result = [ str(i).zfill(2) for i in range(1,20) if i<8 ] print(result) ------- result2 = [] for i in range(1,10): if i<8: j = str(i).zfill(2) result2.append(j) print(result2)
A triplet of expressions
Sex = ' M ' IF int (id_card [-2])% 2 == 0 the else ' M ' # ternary expressions with Print (Sex)
=== "if conditions are met for the preceding value, otherwise the value of the latter, can be converted to the following:
id_card = '410881199211111141' if int(id_card[-2]) % 2 == 0: sex = '女' else: sex = '男' print(sex)
set
Definition: a data type, can be set to a natural weight sets are unordered
= L [1,1,2,3,4,3 ] Print (SET (L)) # sets are unordered
Set of operations
1,2,3,4 = {S2 } S = SET () # empty set s.add (. 1) # additive elements s.remove (. 1) # remove elements Print (S2)
Set intersection and union, difference, symmetric difference (multiple sets can be intersected)
Xn = [ ' jiajinju ' , ' yangliangliang ' , ' zhaowenjing ' , ' shenxianlu ' ] ZDH = [ ' jiajinju ' , ' yangliangliang ' , ' zhaowenjing ' , ' Hanmin ' , ' liuzhao ' ] xn_set = SET (Xn) zdh_set = the SET (ZDH) Print (xn_set.intersection (zdh_set)) # intersected Print (xn_set & zdh_set) # intersected Print (xn_set.union (zdh_set)) # and set # add together the two set of repeating removal Print (xn_set | zdh_set) # and Set Print (xn_set.difference (zdh_set)) # difference sets, a set in which there is no set inside the b Print (xn_set - zdh_set) # difference set Print (xn_set.symmetric_difference (zdh_set)) # symmetric difference, the two sets are removed inside Print (xn_set zdh_set ^) # symmetric difference
function
Defined functions:
DEF Smile (): Print ( ' ha ha ha ' ) Smile () # call the function, the function must be called before execution
# A function to achieve only one function, do not write too long in a function inside
Parameter, arguments
DEF of is_float (S): # formal parameters s, variable Pass of is_float ( 1) # actual parameter 1
Example: determining whether the data input is a decimal
Resolution:
# 1.54
# 1, only a decimal point
# 2, the left and right of the decimal point is an integer
-------------------------
# -1.34
# 1, only a decimal point
# 2, to the right of the decimal point is an integer, a negative sign to the left of the decimal point only
behind # negative number is an integer
= INPUT. price ( ' Enter Price: ' ) DEF of is_float (S): # formal parameter S = STR (S) IF s.count ( ' . ' ) ==. 1 : left, right = s.split ( ' . ' ) # 1.74 [ '1', '74'], a string is divided into left and right string. IF left.isdigit () and right.isdigit (): # left and right are digital return True elif left.startswith ( ' - ' ) and left [. 1:] isdigit (). andright.isdigit (): # left by the - start, and left and right are digital '' return True return False
Function return value
DEF Calc (A, B): Result = A + B Print (Result) return Result # function returns the value SUM Calc = (1,1 ) Print ( ' SUM ' , SUM)
How to determine whether the return value - see the demand, it is determined whether the return value of the function need to increase (e.g., reading a file), as follows:
def write_file(file_name,content):#写文件 with open(file_name,'w',encoding='utf-8') as fw: fw.write(content)
# Variables defined inside a function are local variables
# function in the long encounter ended immediately return function
DEF the read_file (file_name): # Read File with Open (file_name, encoding = ' UTF-. 8 ' ) AS FW: Result = fw.read () return Result username = INPUT ( ' username: ' ) RES = the read_file ( ' Users ' ) IF username in RES: Print ( ' ! user name ' ) the else : Print ( ' user name does not exist! ' )
Return Value Returns tuple
DEF More (): name = ' xiaohei ' Age = 18 is Score = 37.5 return name, Age, Score # needs to correspond to the function and the number of content items
The default value of the parameter
DEF Register (name, Sex = ' F ' ): Print ( ' [% S% S] into the database ' % (name, Sex)) Register ( ' Gujin Ju ' , ' M ' ) # traditional values M, M is written the Register ( ' Gu Jinju ' ) # no traditional values, default write for women
Examples function read the file / Dictionary
import json def op_file(file_name,content=None): if content:#有content with open(file_name,'w',encoding='utf-8') as fw: fw.write(content) else:#只传文件名,没有content with open(file_name,encoding='utf-8') as fr: return fr.read() def op_file_json(file_name,dic=None):#字典格式 if dic: with open(file_name,'w',encoding='utf-8') as fw: json.dump(dic,fw) else: with open(file_name,encoding='utf-8') as fr: result = json.load(fr) return result result = op_file('users') print(result) op_file('user2.txt',xiaoming)
Random module
import random
6 is a randomly generated number #
import random def sms_code(): result = random.randint(1, 999999) verify_code = str(result).zfill(6) return verify_code print(sms_code())
random.sample
Import Random Print (random.sample ( ' 0123456789 ' ,. 6)) # randomly 6, returns a list
The output list random.sample translated into strings
random_list = random.sample('0123456789',6) print(random_list) print(''.join(random_list))
Use random constants
Import String Print (string.digits) # all integers Print (string.ascii_lowercase) # lowercase letters Print (string.ascii_uppercase) # capital letters Print (string.ascii_letters) # uppercase letters lowercase letters + Print (string.punctuation) # All special symbols Print (random.uniform (1,999999)) # random decimal
random operation
Import String Print (The random.choice (string.digits)) # randomly a value Print (random.uniform (1,999999)) # random decimal
= L [1,2,3,4,5,6 ] random.shuffle (L) # shuffling Print (L) # List change, no return value
For example: a group generating a user name, a length of between 6-12, which is generated can not be repeated a number of user names, user names need to start with a letter, it must contain letters and numbers
Analysis
# 1, cycle, the incoming number is, how many generated
# 2, a randomly generated number between 6-12 length as
# 3, not repeated use, use a set of
user # 4, the judgments of name of the first element is not an integer
import string def op_file(file_name,content=None): if content: with open(file_name,'w',encoding='utf-8') as fw: fw.write(content) else: with open(file_name,encoding='utf-8') as fr: return fr.read() def gen_username(num):#产生用户名- 100 all_username = set()#定义空集合 while len(all_username)!= num: length = random.randint(6,12) temp = random.sample(string.digits+string.ascii_letters,length)#产生用户名 if set(temp) & set(string.digits) and set(temp) & set(string.ascii_letters) and \ not temp[0].isdigit(): username = ''.join(temp) all_username.add(username+'@163.com'+'\n') return all_username usernames = gen_username(100) username_str = ''.join(usernames) op_file('usernames.txt',username_str)