Python basics day 3, python Day 3
Ternary Computation
A triplicate operation is also called a triplicate operation. It is short for a simple conditional statement, for example, if
# Standard if judgment syntax if 1 = 1: name = "yes" else: name = "no" # if 1 = 1, name = "yes ", otherwise, name = "no" # name = "yes" if 1 = 1 else "no" # if the condition is true, assign yes to the name variable, otherwise, no is assigned to the name variable.View Code set
Set is an unordered and non-repeating element set.
# Create a set s1 = {11,22} s2 = set () s3 = set ([11,22, 33,4]) # operation set s = set () s. add (123) # add the elements to be passed into the collection as a whole. update (123) # split the elements to be passed in into the s. clear () # delete all elements in the Set s1 ={11,22, 33} s2 ={, 44} s3 = s1.difference (s2) # s1 exists, s2 does not exist s3 = s2.difference (s1) # s2 does not exist, s2 does not exist s3 = s1.20.ric _ difference (s2) # s1.difference _ update (s2) does not exist simultaneously in s1 s2) # update s1 exists and s2 does not contain s1.20.ric _ difference_update (s2) # update s1.discard (1111) # If 1111 is the deletion of elements in the Set s1, no error is reported for s1.remove (11111) # If 1111 is the deletion of elements in the Set s1, no error is reported for ret = s1.pop () # delete any object in the set and return it s3 = s1.union (s2) # Return a new set. The set element is the Union set s3 = s1.intersection (s2) of S1) # Return a new set. The set element is the intersection of s1 s2 s1.intersection _ update (s2) # The members in s1 belong to s1 and s2 # li = [11, 22, 33] # list _ init __# li () # list _ call __# li [0] # list _ getitem __# li [0] = 123 # list _ setitem __# def li [1] # list __ delitem _ old_dict = {"#1 ": 8, "#2": 4, "#4": 2,} new_dict = {"#1": 4, "#2": 4, "#3 ": 2 ,}# old_kyes = old_dict.keys () # old_set = set (old_kyes) new_set = set (new_dict.keys () old_set = set (old_dict.keys () remove_set = begin (new_set) add_set = new_set.difference (old_set) update_set = old_set.intersection (new_set) import rere. match ()View Code Function Description
Before learning functions, we always follow the following principle: process-oriented programming, namely, implementing functions from top to bottom based on business logic. It often uses a long code segment to implement specific functions, the most common operation in the development process is to paste and copy the previously implemented code block to the desired function. The most important thing in functional programming is to enhance the reusability and readability of the Code.
Def sendmail (): try: import smtplib from email. mime. text import MIMEText from email. utils import formataddr msg = MIMEText ('mail content', 'plain ', 'utf-8') msg ['from'] = formataddr (["Wu peiqi ", 'ptawy @ 126.com ']) msg ['to'] = formataddr (["leave", '2017 @ qq.com']) msg ['subobject'] = "topic" server = smtplib. SMTP ("smtp.126.com", 25) server. login ("wptawy@126.com", "WW.3945.5") server. sendmail ('ptawy @ 126.com ', ['2017 @ qq.com',], msg. as_string () server. quit () failed T: # failed to send return "failed" else: # Success return "cc" ret = sendmail () print (ret) if ret = "cc ": print ('sent successfully') else: print ("failed to send ")Email function definition and use def function name (parameter):... function body... return valueFormat
Functions are defined as follows:
- Def: indicates the function keyword.
- Function Name: name of the function. The function will be called Based on the function name in the future.
- Function body: perform a series of logical calculations in the function, such as sending emails and calculating the maximum number in [11, 22, 38,888, 2...
- Parameter: provides data for the function body.
- Return Value: After the function is executed, the caller can return data.
Return Value
# In a function, once return is executed, the function execution process immediately terminates def f1 (): print (123) return "111" print (456) r = f1 () print (r) def f2 (): print (123) r = f2 () print (r)Return Value
Parameters
The function has invalid parameters.
- Common parameters (assign the actual parameters to formal parameters in strict order)
Def sendmail (xxoo, content): # xxoo = alex try: import smtplib from email. mime. text import MIMEText from email. utils import formataddr msg = MIMEText (content, 'plain ', 'utf-8') msg ['from'] = formataddr (["Wu peiqi ", 'ptawy @ 126.com ']) msg ['to'] = formataddr (["leave", '2017 @ qq.com']) msg ['subobject'] = "topic" server = smtplib. SMTP ("smtp.126.com", 25) server. login ("wptawy@126.com", "WW.3945.59") server. sendmail ('ptawy @ 126.com ', [xxoo,], msg. as_string () server. quit () failed T: # failed to send return "failed" else: # Success return "cc" while True: em = input ("enter email address :") result = sendmail (em, "SB") if result = "cc": print ("sent successfully") else: print ("failed to send ")Format parameters
- Default parameter (must be placed at the end of the parameter list)
Def send (xxoo, content, xx = "OK"): print (xxoo, content, xx) print ("sent successfully:", xxoo, content) return Truewhile True: em = input ("Enter the email address:") result = send (em, "SB", "OK") if result = True: print ("sent successfully ") else: print ("failed to send ")Default parameters
- Specify parameters (assign the actual parameters to the formal parameters)
Def send (xxoo, content): print (xxoo, content) # print ("email sent successfully:", xxoo, content) return Truesend (content = "alex ", xxoo = "sb ")Parameter
* All input parameters are placed in tuples by default, f1 (* [1 '1, 44])
** By default, all input parameters are placed in the dictionary f1 (** {"kl": "v1", "k2": "v2 "})
F1 (n1 = "alex", n2 = 18) dic = {'k1 ': "v1", "k2": "v2"} f1 (kk = dic) dic = {'k1 ': "v1", "k2": "v2"} f1 (** dic) f1 (11) li = [11, 22, "alex ", "hhhh"] f1 (li, '12') li = [11,22, "alex", "hhhh"] f1 (li) f1 (* li) li = "alex" f1 (* li)Dynamic Parameters
- Omnipotent parameter, * args, ** kwargs
Def f1 (* args, ** kwargs): print (args) print (kwargs) f1 (k1 = "v1") def f1 (* args ): # args = (11,) # args = ([, 22, "alex", "hhhh"], "12") print (args, type (args) f1 (, 22,) li = [,] f1 (* li) def f1 (** args): # args = (11,) # args = ([, 22, "alex ", "hhhh"], "12") print (args, type (args ))Universal Parameters
Global Variables
- Global variables, all scopes can be read
- Assign a value to the global variable. global is required.
- Special: List dictionary, which can be modified and cannot be assigned again
Def f1 (): age = 18 global NAME # indicates that name is a global variable # NAME = "123" print (age, NAME) def f2 (): age = 19 print (age, NAME) f1 () f2 ()Global variable File Processing f = open ('db', 'R') # Read-Only f = open ('db', 'w') # write only, first clear the original file f = open ('db', 'x') # The file exists, and an error is returned. If it does not exist, create and write only f = open ('db', 'A ') # append f = open ('db', 'R', encoding = "UTF-8") data = f. read () print (data, type (data) f. close () f = open ('db', 'R') data = f. read () print (data, type (data) f = open ('db', 'rb') data = f. read () print (data, type (data) f = open ("db", 'A') f. write ("Li Jie") f. close () f = open ("db", 'AB') f. write (bytes ("Li Jie", encoding = "UTF-8") f. close () f = open ("db", 'r + ', encoding = "UTF-8") # f. fileno () # If the open mode does not have B, read data = f. read (1) # The position (in bytes) of the current tell pointer print (f. tell () # adjust the current point to your location (byte) f. seek (f. tell () # The current pointer position begins to overwrite f. write ("888") f. close ()Open the File read () # No parameter, read all; there are parameters, B, byte without B, by character tell () Get the current pointer position (bytes) seek (1) pointer jump to the specified position (byte) write () write data, B, byte; no B, character closefilenoflush strong brush readline read only one row truncate truncation, the clear for loop object after the pointer is f = open (xxx) for line in f: print (line) f = open ("db", 'r + ', encoding = "UTF-8") f. seek (3) f. truncate () f. close () f = open ("db", 'r + ', encoding = "UTF-8") for line in f: print (line)Operation file f. close () with open ('xb ') as f: passwith open ('db1', 'R', encoding = "UTF-8 ") as f1, open ("db2", 'w', encoding = "UTF-8") as f2: for line in f1: if line = "xx": f2.write () f2.write () # new_str = line. replace ("alex", 'st') # f2.write (new_str)Close file