s21day09 python notes

1. Ternary operations (trinomial operations)

  1. Purpose: For simple if conditional statements
  2. Basic structure
v = before if condition else
 #If the condition is true, v = before, otherwise v = after

"""
Amount to
 if condition:
    v = front
else:
    v = back
"""
# Ask the user to enter a value that is converted to an integer if it is an integer, otherwise assign a value of None
data = input('>>>') value =  int(data) if data.isdecimal() else None 
  1. Note: Do not use ternary operations directly at this stage, make them first, and then think about how to simplify them.

2. Functions

The Essence and Scenario of 2.1 Function

Up to now: Process-oriented programming (poor readability/reusability)

For function programming:

  1. Essential: Take the N-line code elsewhere and give it a name so that it can be found and executed later by name
  2. Scenarios:
    • Code Repeat Execution
    • Code is particularly large than one screen, you can choose to split code by function
# Process-oriented programming 
user_input = input('Please enter a role:')

if user_input == 'Administrators':    
    import smtplib    
    from email.mime.text import MIMEText    
    from email.utils import formataddr
    msg = MIMEText('Administrator, I want to be male 1. You can do whatever you want.', 'plain', 'utf-8')    
    msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])    
    msg['To'] = formataddr(["Administrators", '344522251@qq.com'])    
    msg['Subject'] = "Dear Administrator"
    
    server = smtplib.SMTP("smtp.163.com", 25)           
    server.login("15776556369@163.com", "qq1105400511")          
    server.sendmail('15776556369@163.com', ['Administrators', ], msg.as_string())
    server.quit() 
    
elif user_input == 'Salesman':    
    import smtplib    
    from email.mime.text import MIMEText    
    from email.utils import formataddr
    msg = MIMEText('Operator, I want to be the first man. You can do whatever you want.', 'plain', 'utf-8')    
    msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])    
    msg['To'] = formataddr(["Salesman", 'Salesman'])    
    msg['Subject'] = "Dear salesperson"
    
    server = smtplib.SMTP("smtp.163.com", 25)    
    server.login("15776556369@163.com", "qq1105400511")   
    server.sendmail('15776556369@163.com', ['Salesman', ], msg.as_string())    
    server.quit() 
    
elif user_input == 'Boss':    
    import smtplib    
    from email.mime.text import MIMEText    
    from email.utils import formataddr
    
    msg = MIMEText('Boss, I want to be the first man. You can do whatever you want.', 'plain', 'utf-8')    
    msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])    
    msg['To'] = formataddr(["Boss", 'Boss Mailbox'])    
    msg['Subject'] = "Dear Boss"
    
    server = smtplib.SMTP("smtp.163.com", 25)    
    server.login("15776556369@163.com", "qq1105400511")    
    server.sendmail('15776556369@163.com', ['Boss Mailbox', ], msg.as_string())    
    server.quit()
#Functional programming
#To compare functional programming with process-oriented programming, regardless of whether it can be executed
def send_email():    
    import smtplib    
    from email.mime.text import MIMEText    
    from email.utils import formataddr
    
    msg = MIMEText('Boss, I want to be the first man. You can do whatever you want.', 'plain', 'utf-8')    
    msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])    
    msg['To'] = formataddr(["Boss", 'Boss Mailbox'])    
    msg['Subject'] = "Loving Boss"
    
    server = smtplib.SMTP("smtp.163.com", 25)    
    server.login("15776556369@163.com", "qq1105400511")    
    server.sendmail('15776556369@163.com', ['Boss Mailbox', ], msg.as_string())
    server.quit()

user_input = input('Please enter a role:')
if user_input == 'Administrators':    
    send_email() 
elif user_input == 'Salesman':    
    send_email() 
elif user_input == 'Boss':    
    send_email()

2.2 Function Definition

  1. Basic Definition Function
def function name (): #function definition
    Code#Function Content
    
Function Name ()#Execution of Function
"""
Note: 1. If the function is not called, the internal code will never be executed
     2. len is a function written inside python
"""
  1. Parameters (unlimited number)
def get_list_date(aaa):       #aaa: Formal parameter (formal parameter)
    v = [11,22,33,44]
    print(v[aaa])
    
get_list_date(1)             #1: Actual parameters (arguments)
  • Send Mail Question

    # Suppose: the administrator/salesperson/boss is using the same mailbox. 
    """
    def send_email(to):    
        import smtplib    
        from email.mime.text import MIMEText    
        from email.utils import formataddr
    
        msg = MIMEText('Director, I want to be male 1. You can do whatever you want.', 'plain', 'utf-8')    
        msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])    
        msg['To'] = formataddr(["director", to])    
        msg['Subject'] = "Director of Love"
    
        server = smtplib.SMTP("smtp.163.com", 25)    
        server.login("15776556369@163.com", "qq1105400511")  
        server.sendmail('15776556369@163.com', [to, ], msg.as_string())    
        server.quit() 
    """ 
    
    def send_email(to):    
        template = "To give%s Send Mail" %(to,)    
        print(template)
    
    user_input = input('Please enter a role:')
    if user_input == 'Administrators':    
        send_email('xxxx@qq.com') 
    elif user_input == 'Salesman':    
        send_email('xxxxo@qq.com') 
    elif user_input == 'Boss':    
        send_email('xoxox@qq.com')
  • Exercises

    # 1. Write a function that calculates the sum of all elements in the list info = [11,22,33,44,55].
    def get_sum():
        info = [11,22,33,44,55]
        data = 0
        for item in info:
            data += item
        print(data)
    
    get_sum()
    
    # 2. Write a function that calculates the sum of all the elements in the list.
    def get_list_sum(a1):
          data = 0
        for item in a1:
            data += item
          print(data)
    
    get_list_sum([11,22,33])
    get_list_sum([99,77,66])
    v1 = [8712,123,123]
    get_list_sum(v1)
    
    # 3. Write a function that splits two lists together.
    def join_list(a1,a2):
        result = []
        result.extend(a1)
        result.extend(a2)
        print(result)
    
    join_list([11,22,33],[55,66,77]
    
    # 4. Calculate the length of a list
    def my_len(arg):
      count = 0
      for item in arg:
              count += 1
      print(count)
    
    v = [11,22,33]
    my_len(v)
    len(v)
    
    # 5. Examples of mailing        
    def send_email(role,to):
        template = "To give%s%s Send Mail" %(role,to,)
        print(template)
    
    user_input = input('Please enter a role:')
    if user_input == 'Administrators':
        send_email('Administrators','xxxx@qq.com')
    elif user_input == 'Salesman':
        send_email('Salesman','xxxxo@qq.com')
    elif user_input == 'Boss':
        send_email('Boss','xoxox@qq.com')
  1. Return value
def func(arg):
    //Code#Function Content
return 9             #Return value is 9, default: return None

val = func('ads')    #Set a variable to receive a return value
  • Exercises

    # 1. Write a function to calculate how many numbers are in a list, print: there are%s numbers in the list.
    #    Hint: type('x') == int to determine if it is a number.
    # Mode 1:
    def get_list_counter1(data_list):
        count = 0
        for item in data_list:
            if type(item) == int:
                count += 1
      msg = "There are%s Numbers" %(count,)
        print(msg)
    
    get_list_counter1([1,22,3,'alex',8])
    
    # Mode 2:
    def get_list_counter2(data_list):
        count = 0
        for item in data_list:
            if type(item) == int:
                count += 1
      return count
    
    v = get_list_counter1([1,22,3,'alex',8])
    msg = "There are%s Numbers" %(v,)
    print(msg)
    
    # 2. Write a function that calculates the data of even index positions in one list to construct another list and return it.
    # Mode 1:
    def get_data_list1(arg):
        v = arg[::2]
        return v
    
    data = get_data_list1([11,22,33,44,55,66])
    
    # Mode 2:
    def get_data_list2(arg):
        v = []
        for i in range(0,len(arg)):
          if i % 2 == 0:
              v.append(arg[i])
          return v
    
    data = get_data_list2([11,22,33,44,55,66])
    
    # 3. Read the file, construct the contents of the file into data in the specified format, and return.
    """
    a.log file
        alex|123|18
        eric|uiuf|19
        ...
    //Target structure:
    a.  ["alex|123|18","eric|uiuf|19"] And return.
    b. [['alex','123','18'],['eric','uiuf','19']]
    c. [
      {'name':'alex','pwd':'123','age':'18'},
      {'name':'eric','pwd':'uiuf','age':'19'},
     ]
    """
    def a():
        info = []
        with open('a.log',mode='r',encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                info.append(line)
        return info
    
    def b():
        info = []
        with open('a.log',mode='r',encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                v = line.split('|')
                info.append(v)
        return info
    
    def c():
        info = []
        with open('a.log',mode='r',encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                list = line.split('|')
                v = {}
                v['name'] = list[0]
                v['pwd'] = list[1]
                v['age'] = list[2]
                info.append(v)
        return info
    
    date1 = a()
    date2 = b()
    date3 = c()
    print(date1,date2,date3)
  1. summary
#The basic structure of the function:
#Situation One
def f1():
    //Function Content
    
f1()

#Situation 2
def f2(a):
    //Function Content
    
f2(1)

#Situation Three
def f3():
    //Function Content
    return 1

v1 = f3()

#Situation IV
def f4(a1,a2):
    //Function Content
    return a1+a2

v2 = f4(1,7)

Tags: Python Programming encoding

Posted on Sat, 30 Nov 2019 02:40:13 -0800 by jon2396