[ TOC]
For data type conversion, you only need to use the data type as the function name. There are also several built-in functions that can perform conversion between data. These functions return a new object that represents the converted value;
complex(real [,imag ]) #Used to create a complex number with the value real + imag * j or convert a string or number to a complex number (if the first parameter is a string, you do not need to specify the second parameter. .)
repr(x) #Convert the object x into an expression string, in a form for the interpreter to read;
tuple(s) #Convert the sequence s into a tuple
list(s) #Convert the sequence s into a list
set(s) #Convert to a variable set
dict(d) #Create a dictionary d must be a sequence (key, value) tuple.
chr(x) #Convert an integer to a character
hex(x) #Convert an integer to a hexadecimal string
oct(x) #Convert an integer to an octal string
ord(x) #Convert a character to its ASCII integer value
frozenset(s) #Return a frozen set. After freezing, the set can no longer add or delete any elements. The parameter iterable- iterable object, such as list, dictionary, tuple, etc.
Case: Use of data type conversion function
#! /usr/bin/python3
# coding:utf-8
# Features:Numerical type conversion built-in functions
print("Plastic surgery: 0xa=",int('0xa',16)," 0x12=",int('12',16)," 010=",int('10',8))
# Convert to integer in hexadecimal,And octal conversion into integer
print("floating point:",float('123'),float(1)) #Floating point type
print("plural:",complex(1,2),complex("1+2j")) #转化一个字符串或数为plural
# note:This place is"+"There can be no spaces on both sides of the number, that is, it cannot be written as"1 + 2j",should be"1+2j", Otherwise an error will be reported
cdict =dict(zip(['one','two','three'],[1,2,3])) #Mapping function to construct a dictionary
print(str(cdict)) #Convert the object to string form.
print(repr(cdict)) #Convert the object into a form for the interpreter to read.
print(eval(' 2 ** 2'),eval('pow(2,2)')) #Execute a string expression,Can perform some mathematical functions and calculations of python
print(set('runoob'),set('google')) #Duplicate values in the set are deleted setprint(frozenset(range(10))) #Generate a new immutable collection setprint(chr(48),chr(65),chr(97)) #ASCII code==>character
print(ord('0'),ord('A'),ord('a')) #Character==> ASCII
print(hex(255),hex(15))print("255 oct =",oct(255),"10 oct =",oct(10))
Python data type conversion function use
**Q: What is an operator? **
A: Let variables perform four arithmetic operations of addition, subtraction, multiplication and division;
Python priority
Python priority details
Bitwise operation in Python:
Bitwise operators treat numbers as binary to perform calculations.
& Bitwise AND operator: the two values involved in the operation, if the two corresponding bits are both 1, the result of the bit is 1, otherwise it is 0.
| Bitwise OR operator: As long as one of the two corresponding binary bits is 1, the result bit is 1.
^ Bitwise XOR operator: When two corresponding binary bits are different, the result is 1
~ Bitwise inversion operator: Invert each binary bit of the data, that is, change 1 to 0 and 0 to 1. (~x is similar to -x-1, in the complement form of a signed binary number).
<< Left shift operator: all binary digits of the operand are shifted to the left by several bits. The number on the right of "<<" specifies the number of shifted bits, the high bits are discarded, and the low bits are filled with 0.
Right shift operator: shift all the binary digits of the operand on the left of ">>" by several digits, and the number on the right of ">>" specifies the number of digits to move.
Python language supports logical operators: (similar to Jade C language short-circuit evaluation &&)
x and y Boolean "and"-if x is False, x and y return False, otherwise it returns the calculated value of y.
x or y Boolean "or"-if x is True, it returns the value of x, otherwise it returns the calculated value of y.
not x Boolean "not"-If x is True, return False. If x is False, it returns True.
Python member operators:
Contains a series of members, including strings, lists or tuples.
in returns True if the value is found in the specified sequence, otherwise returns False.
not in returns True if the value is not found in the specified sequence, otherwise returns False.
Python identity operator:
is is to determine whether two identifiers refer to an object
x is y, similar to id(x) == id(y), return True if the same object is referenced, otherwise return False
is not is to determine whether the two identifiers refer to different objects
x is not y, similar to id(a) != id(b). If the reference is not the same object, it returns True, otherwise it returns False.
Case: Python various operators
#! /usr/bin/python3
# coding:utf-8
# Features:Special operation symbol verification demo
#""" Python arithmetic operators"""print("2 / 4 = ",2/4) #division,Get floating point
print("2 // 4 = ",2// 4) #division,Get integer print("2 ** 4 = ",2**4) #power,(Highest priority)print("5 % 4 = ",5%4) #Take the remainder,
#""" Comparison operator###
a =1
b =2if( a == b ):print("1 -a is equal to b")else:print("1 -a is not equal to b")
#""" Assignment operator###
c = a + b
c +=1print("The C value is:",c)
c **= c
print("The C value is:",c)
#""" Python bit operations"""
a =1
b =8print("a&b = ", a&b) #versus
print("a|b = ", a|b) #or
print("a^b = ", a^b) #Or
print("~a = ",~a) #Negate
print("a<<2 = ", a<<2) #Move left
#""" Python logical operators"""
a =1
b =2print((a and b)) #If x is False, x and y return False, otherwise it returns the calculated value of y.
print((a or b)) #If x is True, it returns the value of x, otherwise it returns the calculated value of y.
print(not(a or b)) #If x is True, return False. If x is False, it returns True.
#""" Python member operators"""
a =10
b =5
list =[1,2,3,4,5]if(a in list):print("a in the list")else:print("a is not in the list")if(b not in list):print("a is not in the list")else:print("b is in the list")
#""" Python member operators"""
a =20
b =20if( a is b ):print("1 -a and b have the same logo")else:print("1 -a and b do not have the same logo")
# Note: id()Function is used to obtain the memory address of the object
if(id(a)==id(b)):print("2 -a and b have the same logo")else:print("2 -a and b do not have the same logo")
a,b,c,d,e =20,10,15,5,0
#""" Arithmetic operator priority verification"""
e =(a + b)* c / d #(30*15)/5print("(a + b) * c /d The result of the operation is:", e)
e =((a + b)* c)/ d # (30*15)/5print("((a + b) * c) /d The result of the operation is:", e)
e =(a + b)*(c / d); # (30)*(15/5)print("(a + b) * (c / d)The result of the operation is:", e)
e = a + b * c / d; # 20+(150/5)print("a + (b * c) /d The result of the operation is:", e)
Python various operator cases
Branch syntax:
if expression:
Execute statement
elif expression:
Execute statement
else:
Execute statement
# Ternary operator
x if condition else y//If the condition is true, assign the value of x to small, and if it is false, assign the value of y to small
# else statement
1) The else statement is combined with the if statement to form a "what or not" context
2) else statement followed by for/The while sentence is used to form the context of "what can be done after doing it, and don’t think about it if it’s not done"
2) The else statement is combined with the try statement to form a "no problem, let's do it" context
Exit loop keywords: break, continue, and its loop syntax:
while (expression condition):
True to execute the code block
else:
If the statement is false, execute the else statement block:
for variable in expression:
Loop body
else:It's an exhaustive list(For loop)Or condition becomes false(In a while loop)Be executed when the loop terminates,But the loop is not executed when it is terminated by break.
Case: Condition is controlled by loop statement
#! /usr/bin/python3
# coding:utf-8
# Features:Branch and loop
#- - - - - - - - - - - if statement-----------------
guess =8
temp =int(input("Please enter a 1-10 value:"))if guess == temp:print("congratulations,The value entered is just right")
elif guess > temp:print("that's too regretful,The value entered is less than it")else:print("that's too regretful,The value entered is greater than it")
x,y =1,3print("#Ternary operator:",end="")print( x if x >3else y )
#- - - - - - - - - - - - while statement---------------
# Fibonacci series:Fibonacci sequence (the sum of two elements determines the next number)
a,b =0,1while b <10:print(b,end=",")
a,b = b, a+b
print("\n\n")while(1):print('Python!')
# Adopt while..else calculates prime numbers
count =11/2while count >1:if num % count ==0:print("%d The largest divisor is%d "%(11,count))break #Use break to escape without executing else
count -=1else:print("%d is prime"11) #The loop is exhausted (when it is false, the execution will not be executed when it encounters break)
#- - - - - - - - - - - - for statement---------------for i in"python":print(i,end="|") #Print letters sequentially and start with|segmentation
print()
sites =["baidu","Google","Runoob","taobao"]for i in sites:print(i,end=",") #Print out the value of the list
print()for i inrange(len(sites)): #Or the length of the list 4 is generated(0-3);print(i,sites[i],len(sites[i])) #index,列表中以index下标的元素,Element length
print()
# Query whether it is a prime number 2-10 those are prime numbers
for x inrange(2,10):for y inrange(2,x):if x % y ==0:print(x,'equal',y ,'*', x // y)breakelse:
# Find element in loop,It's an exhaustive list(For loop)Or condition becomes false(In a while loop)Be executed when the loop terminates,But the loop is not executed when it is terminated by break.
print(x,'Is prime')
Python condition is controlled in loop case
Python pass is an empty statement, in order to maintain the integrity of the program structure, pass does not do anything, generally used as a placeholder statement, the following example:
while True:
pass #Wait for keyboard interrupt(Ctrl+C)
# Smallest class:classMyEmptyClass:
pass
Iteration is one of the most powerful features of Python is a way to access collection elements. Iterator is an object that can remember the position of the traversal; the iterator object is accessed from the first element of the collection until all elements are The visit is over, and you can only go forward without going back.
Iterator parameters: list/dictionary
There are two basic methods for iterators: iter() and next().
Create an iterator, use two methods iter() and next() that need to be implemented in the class; and the iter() method returns a special iterator object, this iterator The object implements the next() method and uses the StopIteration exception to identify the completion of the iteration to prevent an infinite loop.
Case: iterator (magic method)
#! /usr/bin/python3
# coding:utf-8
# Function: Iterator and Generator
import sys #Introduce the sys module
list =[1,2,3,4]
it =iter(list)
#** Method 1for**#
## In fact, the implementation of the for statement is similar to the iter iterator##
for x in it:print("value", x, end=", ")else:print("\n---------------------------")
#***Method 2 next**#
it =iter(list)while True:try:print(next(it), end=",")
except StopIteration: #StopIteration exception is used to identify the completion of the iteration and prevent an infinite loop;
sys.exit()
#**Method 3 iterator-Magic method**#
# Create an iterator that returns numbers, with an initial value of 0, and gradually increasing by 1: Run four times
# Magic method case(1)classMyNumbers:
def __iter__(self): #Magic method
self.a =0return self
def __next__(self): #when
try:if self.a <=3:
x = self.a
self.a +=1return x
else:
raise StopIteration
except StopIteration:return('End of iteration')
myclass =MyNumbers()
myiter =iter(myclass) #Actually triggered__iter__Middle a=0print(next(myiter), end=" ") #Run 1 next
print(next(myiter), end=" ") #Run next 2 times
print(next(myiter), end=" ") #Run next 3 times
print(next(myiter), end=" ") #Run next 4 times
print(next(myiter)) #The fifth run of next due to conditions(Or throw StopIteration to exit iteration)
# Case 2: Using magic methods to realize the Fibonacci sequence
classFibs:
def __init__(self):
self.a =0
self.b =1
def __iter__(self):return self #Return itself because it is an iterator
def __next__(self):
self.a, self.b = self.b,self.a + self.b
return self.a #a is the next Fibonacci value
# def __next__(self):
# self.a, self.b = self.b,self.a + self.b
# if self.a >10:
# raise StopIteration #Means
# return self.a
fibs =Fibs()for each in fibs:if each <20: #return
print(each, end=" ")else:break
#######################
# $ python demo3.24.py
# 0123 End of iteration
# 11235813
Python iterator case
A function that uses yield is called a generator. Unlike ordinary functions, a generator is a function that returns an iterator; it can only be used for iterative operations. It is simpler to understand that a generator is an iterator.
Important: Calling a generator function returns an iterator object.
In the process of calling the generator to run, each time it encounters yield, the function will pause and save all current running information, return the value of yield, and continue from the current position when the next() method is executed next time.
Case: Generator
#! /usr/bin/python3
# Function: generator yieldimport sys
# Case 1:
def gener():print("Generator is executed!",end=" ")yield1 #Run the first next pause here
yield2 #Run the second next display two
my =gener()next(my) #The generator is executed!2next(my) # 2
# Method 2:
def fibonacci(n): #Generator function-Fibonacci
a, b, counter =0,1,0while True:
# When counter==10 end (that is, calculate 10 times)
if(counter > n):returnyield a #Generator returns
a, b = b, a + b
counter +=1
f =fibonacci(10) #f is an iterator, returned by the generator
while True:try:print(next(f), end=" ") #Return one Fibonacci sequence at a time 011235813213455
except StopIteration:
sys.exit()
# Method 3: The for loop will automatically parse the Stopiteration exception and end
def fbli():
a =0
b =1while True:
a, b = b, a+b
yield a
for each infbli(): #each and return the value of generator a
if each <=55:print(each,end=" ")else:break
########## Results of the##########
# 1235813213455
The function can improve the modularity of the application, and the reuse rate of the code can be called by itself. The function created by the user is called the user-defined function;
Function function, object object, module moudule.
Function and procedure: * Procedure (procedure) is simple, special and has no return value. General programming languages separate functions and procedures.
But Python actually only has a function without a procedure, and a function has a return value. When there is no return statement in the function, it will return the None type. But Python can return multiple values, use lists [multiple types coexist] or tuples;
Q: How to define a function? *
A: The following are simple rules:
Function syntax:
#.__ doc__(Default properties of the function,He is a special attribute,The special attribute format is like this)
def function name(Parameter list):'Function documentation: by function name.__doc__transfer'
Function body
#( Formal parameters) formal parameters
#( Arguments) actual parameters
def first(name="default"):'Name is a formal parameter in the function definition process' #Because ta is only a form, it means occupying a parameter position.
print(name,"At this time, the value of name is the actual parameter, because it is the specific parameter value!")>>> def hello():print("hello world") #Since there is no return statement, None will be returned
>>> temp =hello() #Return the value of the function to temp
hello world
>>> temp #But temp does not return return value
>>> print(temp)
None #Print-None type is returned when Temp
>>> type(temp)<class'NoneType'>>>> def back():return["Python","Flash",3.1415926]>>>back()['Python','Flash',3.1415926] #Back to list
>> def back():return"Python","Flash",3.1415926>>>back()('Python','Flash',3.1415926) #Return tuple
By default, parameter values and parameter names are matched in the order defined in the function declaration.
Function example:
#! /usr/bin/python3
# Function: realize function function
def fun(num1,num2):'Function function: find the sum of two numbers' #By function name.__doc__Call function documentation
return num1 + num2 #Use return to return parameters or the results of program execution
def saypython(name='Small turtle',words="Change time"): #Set default parameters, display when no value is assigned to the function
' Function documentation: our voice'print(name +'miss you->'+ words)print("1 + 2 =",fun(1,2))print("Function description:(",fun.__doc__,end=")\n-------------")print("I",saypython('weiyigeek','change the world')) #Since there is no return statement, none is returned
saypython('weiyigeek','change the world')saypython() #Use function default parameters,Can run without parameters,Because there is a built-in optional parameter name='Small turtle',words="Change time"print("Function description:(",fun.__doc__,end=")\n")
Python function definition example
Python function parameter passing:
The following are the formal parameter types that can be used when calling a function:
Variable parameters are used between uncertain multiple parameters:
(1) A single asterisk * is added to the parameter name. For example, (*params) will be packed into a tuple. If no parameters are specified when the function is called, it is an empty tuple, and we can also not pass it to the function Unnamed variable.
(2) Two asterisks are added to the parameter names, such as (**params) will be imported in the form of a dictionary (dict)
Function parameter example:
#! /usr/bin/python3
# Function: Function parameter
# For example: Actually PRINT()Comes with collection parameters*Objects
# print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
# /*Immutable object**/
def ChangeInt(a):
a =10print("(Immutable)Within the function:",a) #The result is 10
b =2ChangeInt(b)print("(Immutable)Outside the function:",b,end="\n\n") #The result is 2
# /*Mutable object**/
def changeme(mylist):
mylist.append([1,2,3,4]) #At this time the incoming list has been changed
print("(variable)Value in function:",mylist)return
mlist =[6,6,6]changeme(mlist)print("(variable)Value outside the function:",mlist) #List has changed
#! /***variable parameter(*)With keyword arguments**/
def test(*params,exp="weiyi"):print("Parameter length:",len(params),"The second parameter:",params[1],"Name :",exp)forvarin params:print(var,end=",")return0test(1,"love you",1024,1,exp='weiyigeek')
#! /***variable parameter(**) **/
def printmm(arg1,**vardict):'Function documentation: the formal parameter is a dictionary type'print("\n\n outputs arg1:",arg1)print("Output vardict dictionary:",vardict)printmm('test',a=1,b=2,c=3)
#! /***Use of a single asterisk(note)**/
def star(a,b,*,c):print("a :",a ," b:",b ,' c:', c)star(1,2,c=1024) #c must specify the keyword to pass in the value, otherwise an error will be reported
Python function parameter example
Python uses lambda to create anonymous functions. The so-called anonymous means that a function is no longer defined in a standard form such as the def statement.
The benefits of lambda expressions: make the code more streamlined, no need to consider naming control, and simplify code readability.
Q: How to create an anonymous function?
A: Lambda is just an expression, and the function body is much simpler than def.
The syntax of lambda function contains only one statement, as follows:
lambda [arg1 [ ,arg2,…..argn ]]:expression
Case:
#! /usr/bin/python3
# Function: Use anonymous functions
# Function definition
sum = lambda arg1,arg2: arg1 + arg2
sum.__doc__ ='Function documentation'
# Call anonymous function
print("1 +99 added value:",sum(1,99))print(sum.__doc__)
# Advanced usage and BIF built-in function filter/Use of map
# Advanced anonymous functions(Set the filter function to return a value that can be divisible by 2)
show =list(filter(lambda x: x %2,range(10)))print(show)
# Map mapping display is%2 The result after division.
show =list(map(lambda x:x %2,range(10)))print(show)
Python dictionary case
In Python, the variables of the program are not accessible at any location. The access authority depends on where the variable is assigned. The scope of the variable determines which part of the program can access which specific variable name. The scope has a total of The 4 types are:
The search is based on the following rules, that is: if you can't find it locally, you will find it locally (such as a closure), if you can't find it, you will find it globally, and then you will find it in the built-in.
g_count =0 #Global scope
def outer():
o_count =1 #In the function outside the closure function
def inner():
i_count =2 #Local scope
# The built-in scope is implemented by a standard module called builtin, but the variable name itself is not put into the built-in scope, so this file must be imported to use it.
If you modify the global variable in the function, it will appear. Create a new local variable with the same name as the global variable, and assign the value of the global variable to it. The modification is actually the value of the local variable, and the value in the global variable has not changed. .
Case: Function scope
#! /usr/bin/python3
# Code function: global and local variables Variable
# The msg variable is defined in the if statement block, but it is still accessible from outside
if True:
msg ="I am from Weiyigeek"print("\The nmsg variable is defined in the if statement block, but it is still accessible from outside:",msg)
def discount(price,rate):
final_price = price * rate #Local variable
# print("Here is trying to print the global variable old_value of price(Report wrong):",old_price)
local_price =100 #Defined in the function,Then it is a local variable,No outside access
print("Local variable_price :",local_price) # 100
old_price =50print("After modification in the function old_The value of price is 1:",old_price)return final_price
old_price =float(input('Please enter the original price:'))
rate =float(input('Please enter the deduction rate: '))
new_price =discount(old_price,rate)print('Modified old outside the function_The value of price is 2:',old_price)print('Discounted price:',new_price)
Python function scope example
Description: Python introduces {Shadowing} to protect global variables. When the internal scope wants to modify the external scope variables, the global and nonlocal keywords must be used.
global and nonlocal keywords:
The global keyword can change the global variable in the defined function. If you want to modify the variable in the nested scope (enclosing scope, outer non-global scope), you need the nonlocal keyword
Case: scope keywords
#! /usr/bin/python3
# Function: global variable scope and non-global scope
""" global"""
num =1
def fun1():
global num #Need to use global keyword declaration
print("global:",num,end=",")
num =123print(num,end=",")
num +=133fun1()print(num)
# global:1,123,256"""nonlocal"""
def outer():
num =10
def inner():
nonlocal num #nonlocal keyword declaration
num =100print("nonlocal:",num,end=" | ")
num *=10.24inner()print(num,end=" | ")outer()print(num) #The num here has not changed because the global keyword is not used in the outer function
# nonlocal:100|1024.0|256
Functions in Python can be defined and used inline, and closures can be considered more stable and safer when global variables are not applicable.
Container (container), such as all the previous array (array) = list (list), tuple (tuple)
Case:
#! /usr/bin/python3
# Function: Use of embedded functions and closures
#""" Built-in function"""
def fun1():print("Fun1 main function is called")
def fun2():print("Fun2 embedded function is being called\n")fun2() #Internal function (built-in function),Can only be used by fun1()transfer
fun1()
#""" Closure"""
def funX(x):
def funY(y):return x * y
return funY
i =funX(8)print("Type of i:",type(i))print("8 * 5 =",i(5)) #40 Since x has already been assigned to,Give y later=5."""
# Similar to:
def funX(x):
def funY(y):return x * y
returnfunY(2)>>>funX(3)6"""
#""" Advanced closures (in a way similar to an array of numbers--List(Incoming is the address))"""
def demo1(arg):
x =[arg]
def demo2():
# Use nonlocal keywords
x[0]**= x[0] #Use this method to list the values(**Exponentiation)|Do not reference local variables(Local variable),Use an array to make a dark transition into a warehouse.return x[0]returndemo2()print("2 ** 2 =",demo1(2)," - 5 ** 5 =",demo1(5))
#""" A typical case of closure"""
def funA():
x =5
def funB():
nonlocal x #//Force x to indicate that it is not a local variable
x +=13return x
return funB
a =funA() #When a is assigned for the first time,As long as it has not been reassigned,funA()Was not released,In other words, the local variable x is not reinitialized.
print("The first call:",a(),"The second call:",a(),"The third call:",a())
Python built-in functions and closures
Recommended Posts