Python Basics - functions

Keywords: Python JSON encoding

A function, also known as a method, is a piece of code used to implement a specific function
Function to improve code reusability
Function must be called to execute
The variables defined in the function are local variables. Local variables can only be used in the function and cannot be used outside the function
A function does only one thing

import json
def get_file_content(file_name): #Formal parameter
    #Enter parameter: pass in a file name
    #Return: the contents of the file are converted into a dictionary and returned
    with open(file_name, encoding='utf-8') as f:
        res = json.load(f)
        return res
abc = get_file_content('stus.json') #The function call is executed only when the actual parameter is passed in here. The function has a return and needs to be received with a variable
print(abc)
def write_file(filename,content):
    with open(filename,'w', encoding='utf-8') as f:
        #f.write(json.dumps(content))
        json.dump(content,f,ensure_ascii=False,indent=4)
dict = {'name':'wrp','age':'18'}
write_file('wrp.json',dict)
'''
//Homework:
    1,Realize a commodity management procedure.
        #Output 1, add item 2, delete item 3, view item
        //Add item:
            //Name of product: xxx if the product already exists, it indicates that the product already exists
            //Price of goods: xxxx quantity can only be an integer greater than 0
            //Product quantity: xxx, quantity can only be an integer greater than 0
        2,Delete item:
            //Enter product name:
                iphone If the entered product name does not exist, you should be prompted that it does not exist
        3,To view product information:
             //Enter product name:
                iphone: 
                    //Price: xxx
                    //Quantity: xxx
                all: 
                    print Give all product information 
'''


FILENAME = 'products.json'

import json
def get_file_content():
    with open(FILENAME, encoding='utf-8') as f:
        content = f.read()
        if len(content) > 0:
            res = json.loads(content)
        else:
            res = {}
    return res

def write_file_content(dict):
    with open(FILENAME,'w',encoding='utf-8') as fw:
        json.dump(dict, fw, indent=4, ensure_ascii=False)

def check_digit(st:str):
    if st.isdigit():
        st = int(st)
        if st > 0:
            return st
        else:
            return 0
    else:
        return 0
def add_product():
    product_name = input("Please enter the product name:").strip()
    count = input("Please enter product quantity:").strip()
    price = input("Please enter commodity price:").strip()
    all_products = get_file_content()
    if check_digit(count) == 0:
        print("Illegal quantity input")
    elif check_digit(price) == 0:
        print("Illegal price input")
    elif product_name in all_products:
        print("Item already exists")
    else:
        all_products[product_name] = {"count":int(count),"price":int(price)}
        write_file_content(all_products)
        print("Add success")

def del_product():
    product_name = input("Please enter the product name to delete:").strip()
    all_products = get_file_content()
    if product_name in all_products:
        all_products.pop(product_name)
        print("Delete successful")
        write_file_content(all_products)
    else:
        print("Item does not exist")

def show_product():
    product_name = input("Please enter the product name to query:").strip()
    all_products = get_file_content()
    if product_name == 'all':
        print(all_products)
    elif product_name not in all_products:
        print("Item does not exist")
    else:
        print(all_products.get(product_name))

Copy

Shallow copy, memory address unchanged, point two objects to the same content,
Deep copy, which will regenerate the variables of the same content in memory

l = [1,1,1,2,3,4,5]
l2 = l #Shallow copy
#l2 = l.copy() #Shallow copy 
for i in l2:
    if i % 2 != 0:
        l.remove(i)
print(l)
#In this program, if you traverse and delete the same list, you will find that the result is inconsistent with the expectation, and the result is [1,2,4]. It is OK to use a deep copy
import copy
l = [1,1,1,2,3,4,5]
l2 = copy.deepcopy(l) # Deep copy
for i in l2:
    if i % 2 != 0:
        l.remove(i)
print(l)

Non null is true, non zero is true

name = input('Please enter a name:').strip()
name = int(name) #False when entering 0
if name:
    print("Input correct")
else:
    print("name Can not be empty")

Default parameters

import json
def op_file_tojson(filename, dict=None):
    if dict: #If dict passes parameters, write json to the file
        with open(filename,'w',encoding='utf-8') as fw:
            json.dump(dict,fw)
    else: #If no parameter is passed, read json from the file
        f = open(filename, encoding='utf-8')
        content = f.read()
        if content:
            res = json.loads(content)
        else:
            res ={}
        f.close()
        return res

Check decimal type

def check_float(s):
    s = str(s)
    if s.count('.') == 1:
        s_split = s.split('.')
        left, right = s_split
        if left.isdigit() and right.isdigit():
            return True
        elif left.startswith('-') and left[1:].isdigit and right.isdigit():
            return True
        else:
            return False
    else:
        return  False

print(check_float('1.1'))

global variable

def te():
    global a
    a = 5
    
def te1():
    c = a + 5
    return c

res = te1()
print(res) #The code will report an error. a defined in te() cannot be used before the function is called
money = 500
def t(consume):
    return money - consume
def t1(money):
    return  t(money) + money

money = t1(money)
print(money) #The result is 500
name = 'wangcai'
def get_name():
    global name
    name = 'hailong'
    print('1,In function name', name)
def get_name2():
    print('2,get_name2', name)

get_name2() #wangcai
get_name() #hailong
print('3,Out of function name', name) #hailong

recursion

Recursion means that a function calls itself
Recursion up to 999 times

def te1():
    num = int(input('please enter a number:'))
    if num%2==0: #Judge whether the input number is even
        return True #If it is even, the program exits and returns True
    print('Not even, please re-enter')
    return  te1()#If not, continue to call yourself and input the value
print(te1()) #Call test1

parameter

Position parameter

def db_connect(ip, user, password, db, port):
    print(ip)
    print(user)
    print(password)
    print(db)
    print(port)

db_connect(user='abc', port=3306, db=1, ip='192.168.1.1', password='abcde')
db_connect('192.168.1.1','root', db=2, password='123456', port=123)
#db_connect(password='123456', user='abc', 2, '192.168.1.1', 3306) #The method is wrong. The location parameter must be written in the front and one-to-one correspondence. The key=value method must be written in the back

Variable parameters

def my(name, sex='female'):
    #name, required parameter, location parameter
    #sex, default parameter
    #Variable parameters
    #Key parameters
    pass
def send_sms(*args):
    #Variable parameter
    #1. Not necessary
    #2. Put multiple elements in the tuple
    #3. Unlimited number of parameters
    #4. It is used when there are many parameters
    for p in args:
        print(p)


send_sms()
send_sms(123456)
send_sms('123456','45678')

Key parameters

def send_sms2(**kwargs):
    #1. Not necessarily
    #2. Unlimited number of parameters
    #3.key=value format storage
    print(kwargs)

send_sms2()
send_sms2(name='xioahei',sex='nan')
send_sms2(addr='Beijing',county='China',c='abc',f='kkk')

aggregate

Assemble, born to be heavy
Set out of order, list out of order

l = [1,1,2,2,3,3,3]
res = set(l) #Convert list to set
l = list(res) #set to list after de duplication
print(res)
print(l)
set = {1,2,3} #set format

jihe = set() #Define an empty collection

xn=['tan','yang','liu','hei']
zdh=['tan','yang','liu','jun','long']

xn = set(xn)
zdh = set(zdh)
# res = xn.intersection(zdh) #intersect
# res = xn & zdh #intersect

res = xn.union(zdh) #Union and collection
res = xn | zdh #Union and collection
res = xn.difference(zdh) #Take the difference set, yes in A, no in B
res = xn - zdh #Difference set

res = xn.symmetric_difference(zdh) #Symmetric difference set, take the data that is not coincident between the two
res = xn ^ zdh
print(res)
import string
l1 = set(string.ascii_lowercase)
l2 = {'a','b','c'}
print(l2.issubset(l1)) #Is l2 a subset of l2
print(l2.issuperset(l1)) #Is l2 the parent set of l2
print(l2.isdisjoint(l1)) #If there is intersection, if there is, then false, if there is no, then True

l2.add('s') #Additive elements
print(l2)
print(l2.pop()) #Randomly delete an element
l2.remove('a') #Delete specified element
for l in l2:
    print(l)

Posted by Riparian on Wed, 20 Nov 2019 07:27:11 -0800