The fourth day of vegetable learning python -- string object learning, slicing operation, function, global \ local variable

Keywords: Python Lambda Programming C

1, String object·

1,What is a string
	//Enclosed by single quotation mark, double quotation mark and triple quotation mark
2,Definition string
	s = 'today is friday'
	ss = "wo shi meinv"
	sss = """wo bu hui"""
	s1 = str("aaa")
3,Common methods for Strings:
	1)'capitalize'		#Capitalize the first letter of a string
	2)'center'		#Center the string, and the second parameter represents the filled symbol
		a.center(50)
		a.center(20,"#")
	3)'count'			#Count the number of characters or strings in a string
	4)'encode'		#This method can convert a string to bytes
		//In the future, it is suggested that you use utf-8 in the code conversion
		//Note: code and decode must use the same code
		//It corresponds to the decode of bytes
		s = "today is firday"
		#Using utf-8 encoding
		s.encode("utf-8")
		tt = s.encode("utf-8")
		type(tt)
		>>><class 'bytes'>
		tt.decode("utf-8")
		>>>'today is firday'
	5)'endswith'		#Determine whether the string ends in xx
	6)'startswith'		#Determine whether the string starts with xx
		s.startswith("t")
	        >>>True
                s.startswith("today")
                >>>True
	7) 'find'		#Find a character in a string or where the string first appears
				#Note: if not, return - 1
	8)'index'		#Find a character in a string or where the string first appears
				#Note: if not, an exception is thrown
	9) 'format'		#A new way to format strings introduced by Python 3
				#It's important to use this for formatting later
		print("{ } - { } = { }".format(a, b, (a - b)))  	
	10)'join'		#To concatenate strings, note: the parameter is an iterative object
		a = ["day","wo"]
		"-".join(a)
		>>>'day-wo'
	11)'lower'	#Turn lowercase
	12)  'upper'	#Turn capitalization
	13)'title'		#Convert string to a rule that matches the title
	14)'split'		#Split string
		s.split(" ")
		>>>['today' 'is' 'firday']
		s.split("o")
		>>>['t', 'day is firday']
	15) 'rfind'		#Find the last one
	16)'rsplit'	#
	17)   'strip'	#Clear spaces on both sides of string
	18)'rstrip'	#Clear space on right
	19)'lstrip'	#Clear space on left
	20)  'replace'	#Replace string
		s = "today is firday"
		s.replace("firday","saturday")
		>>>'today is saturday'
	#As long as you know how to use it, you can		
	 'istitle'	#Determine whether the string is a title
	 'isspace'	#Determine if it is a blank character
	 'islower'	#Determine if it's a lowercase letter
	 'isupper'	#Decide if it's a capital letter 
	 'isalnum'	#Judge whether it is composed of letters or numbers (other types are not allowed)
	 'isalpha'	#Determine whether it is made up of letters (capitalized)
	 'isdigit'	#Judge whether it is composed of numbers

2, Slice (for – ordered sequence)

The string itself does not provide a way to intercept the string --- slicing
 Slicing is python's way of cutting, dividing and intercepting containers
 Note: the slice is a front closed and back open interval
 Container [start:] ාintercept the container from the start position to the end
 The container [start:end] starts from the start position and ends at the end position. Note: the end bit is not included
 Container [: end] ා if it is not written on the left, the position with subscript 0 will start by default
 Container [start:end:step] ා note: step represents step, default is 1,
s = "today is saturday"
s[3:]
>>>'ay is saturday'

Interview questions:
	Given a list ls = [1,2,3,4,5,6,67]
	Please flip the list instead of using the method provided by the list itself (ls.reverse()).
	Answer:
		ls[::-1]

3, Function learning

function
 This function in programming is not the same as mathematics
 1. What is a function?
	A collection of code with specific functions
	This code is used to solve a problem or a class of problems
	Give this code a name,

	Function is function and procedure.
	c language process refers to the function!!!

	Pick up express (function, process)
		You -- stand up -- walk to the rookie station -- walk back
	A large process (target) - decomposed into n small processes
		1) Simplify operations
	For reuse
	c language -- > process oriented programming -- > goal setting -- > decomposes goals into n small goals -- > to achieve one by one
 2. Why use functions
	Code repetition!!!
	|--It is possible to encapsulate repeated code to form a name. When using this code, calling this name is essentially the code being called	
3. How python defines functions
	Rule:
	#Def = = = > define function
	#The name definition of function is consistent with the naming rule of variable!!!
	def function name ([parameter list...]):
		Function body
		#[return value]
#Define a function
def my_fun():
	"""
	    This is the comment of the function
	    When a function is defined, it will not be executed immediately and needs to be called
	"""
	print("this is my first function")
#Call function
my_fun()
4. How to call a function
	Function name ([argument list])
#With parameters - when a function is defined, parameters need to be passed in order to make the function more flexible and convenient
#Output personal information
#name,age parameter formal parameter (can have or not)  
def show_info(name,age):
	print("My name is", name)
	print("I{}Year old".format(gender))
#Calling function
#”Small ", 16 actual parameters
show_info("Little",16)
5. Classification of functions
	There is a standard, there is a classification
	1) According to the parameters
		|--Parametric function
		|--Nonparametric function
		Future code, our function definer and function caller are not necessarily one person			
def show_info(name, info):
	print("{}The basic information about this person is{}".format(name,info))
	
#Calling function
show_info("Adzuki Beans","He is a very good man")
	2) According to the returned value	
		|--Function with return value		
		|--Function without return value	
		If the function is completed, you need to give a result to the caller's return result
#If we need function operation, and finally we need to get the operation result, then
#We need to define the function with return value
def add(x,y):
	#Get the sum of two numbers
	res = x + y
	#If you need to return the operation result to the caller, return returns the result
	return res
	
a = float(input("Please enter the first number:"))
b = float(input("Please enter the second number:"))
#Call function calculation result
c = add(a,b)
print("{} + {} = {}".format(a,b,c))
	3) Defined by:
		|--System function
		|--Custom
		|--Third party defined (open source company, organization, organization)

Global and local variables:
Calls to functions in memory

	1. Interpretive language code is executed from top to bottom!!!
	2. Calling procedure of function
		Function calling process, called stack pressing -- when calling, the entire function structure is placed in the stack
				 Pop stack -- when the function execution is completed, the function will be out of the stack immediately
	3. Using global variables in functions
		In python, if a function wants to modify a global variable, it must declare
		Global global variables
#index, msg global variable
msg = "it's a nice day today"
index = 10
def show():
	print("This is the code at the beginning of the function")
	print(msg)
	#In python, if you need to modify a global variable within a function, it is not allowed normally
	#To modify, be sure to declare global global variables
	global index
	#print(index)
	index += 1
	print(index)
	print("The function is over")

#call
show()
6. Value passing and reference passing problems
def test(msg):
	print("Received a message-->{}".format(msg))
	return "haha"

test("What a nice day today")

#Citation transfer
#Test itself is a function, so test stores a heap address in the stack
#Then a will execute the function corresponding to test
#That is to say, a and test both correspond to the same function
a = test
print(a)

#function call
b = test("Don't make a mistake")
print(b)
7. On the parameters of functions
 When there are many function parameters, in order to solve the problem of parameter passing during calling
	1) Use default parameters
		Default parameter must be placed after normal parameter
#Find the area of a circle
#The default value of the function, in python, if there are some parameters
#In general, the value is fixed and a default value is given
#(r, PI=3.14). If this function is called, if the parameter is passed, the parameter is the passed value
#If this value is not passed during the call, it will be calculated by default
def get_circle_area(r,PI=3.14):
	return PI*r*r
	
float(input("Enter the radius of the circle:"))
area = get_circle_area(3.14159,r)
print("The radius is{}Circle with an area of{}".format(r,area))

r = float(input("Enter the radius of the circle:"))
area = get_circle_area(r)
print("The radius is{}Circle with an area of{}".format(r,area))
	2) In python, when a function has many parameters
		Variable parameters can be used to receive these parameters
		*Variable name * args
#Variable parameters
def test(x,y,z,k,n, *args):
	#Parameters that cannot be accepted by ordinary parameters will be received uniformly. Note: it is a tuple
	print(args)
	print(args[2])
	print(x+y+z+k+n)

test(1,2,3,4,5,6,7,8,89)
#Named parameter
def test(a,b, **kwargs):
	print(kwargs["cc"])
	print(a + b)
	
test(3,5,name="Little",age=16, cc="Ha-ha")
#When we are defining functions, sometimes we need to keep the functions of extension functions
#Using variable and named parameters to do this
#Universal parameter
#*And * * are fixed and cannot be replaced
#General order: general parameter, default parameter, variable parameter, named parameter
def add(x,y, *args, **kwargs):
	print(args)
	print(kwargs)
	return x + y

res = add(5, 10, 20,age=80)
print(res)
8. lambda function (anonymous function)
	lambda [parameter 1, parameter 2,..., parameter n]: statement

	lambda x,y:x + y
	Equivalent to:
	def add(x,y):
		return x + y
	Note: in python, lambda simplifies code writing, increases code maintenance cost, and reduces code readability
def msg(fn):
	#fn is a function
	#In this case, fn is actually ps function
	fn()

#def ps():
#	print("hello")
	
#msg(ps)
#This is the use of anonymous functions
#lambda expressions 
#lambda:print("hello")
msg(lambda:print("hello"))
9. Function recursion
	Recursion:
		1. It calls itself, which is called recursion
		2. Recursion must have a termination condition, otherwise it is a dead cycle		
#General method
#The sum of function 1-100
def sum(n):
	s = 0
	for i in range(1,n+1):
		s += i
	return s

res = sum(100)
print("1~100 The sum is{}".format(res))
#Recursive Method
def sum(n):
	#100 + 99 + 98 +... Infinitesimal
	#In recursion, if there is no end condition, recursion is a dead cycle
	if n == 1:
		return 1
	return n + sum(n - 1)

sum(100)
print("1~100 The sum is{}".format(res))
Python allows functions to return multiple values:
def test():
	a = 10
	b = 20
	c = 30
	#To return values from multiple functions to the caller
	return a, b, c
	
#res = test()
#print(res)
#print(res[0])

x,y,z = test()
print(x,y,z)
10,Global function:
	40 Several global functions
	import builtins
Published 21 original articles, won praise 8, visited 1201
Private letter follow

Posted by jonahpup on Wed, 04 Mar 2020 06:25:24 -0800