python--function

Source: Internet
Author: User

Definition of a function

Def sendmail ():      # # # # #定义函数, SendMail is defined by itself
n = 100
N +=1
Print (n)

SendMail () ##### #执行函数 result is 101
f = SendMail # #将函数名赋值给f
F () ##### #执行函数 result is 101

Below is a formal function on the line can send success, knowledge production environment need to consider the network to send mail, by the network, third-party server (NetEase's mailbox) more restrictive
Principle Realization:
First define a value RET
Executes the contents of the try and succeeds, the following content is not executed, thus returning the RET value is the beginning of the assignment of true
Executes the contents of the try, does not succeed, executes the following content, thus returning the RET value is the start assignment true
‘‘‘
‘‘‘
Import Smtplib
From Email.mime.text import Mimetext
From email.utils import formataddr
Def sendmail ():
RET = True
Try
msg = Mimetext (' e-mail Content-This is the message I sent by writing the program ', ' Plain ', ' utf-8 ')
Msg[' from '] = formataddr ([' wangshiqing ', ' [email protected] ')
#msg [' to '] = formataddr ([' Wangqq ', ' [email protected] ')
Msg[' to '] = formataddr ([' Jingjing ', ' [email protected] ')
msg[' Subject ' = "Subject--python program test"

Server = Smtplib. SMTP ("smtp.126.com", 25)
Server.login ("[Email protected]", "[Email Protected]_4")
#server. SendMail (' [email protected] ', [' [email protected] ',],msg.as_string ())
Server.sendmail (' [email protected] ', [' [email protected] ',],msg.as_string ())
Server.quit ()
Except Exception:
RET = False
return ret

ret = SendMail ()
IF RET:
Print ("Send Success")
Else
Print ("Send Failed")


# msg[' to ' = formataddr ([' Jingjing ', ' [email protected] ')

# server.sendmail (' [email protected] ', [' [email protected] ',],msg.as_string ())
‘‘‘
‘‘‘
Def show ():
Print (' a ')
If 1 ==2:
return [11,22,33]
Print (' B ')

ret = Show ()
Print (ret)
‘‘‘
‘‘‘
The result is
A
B
None
The point is that no return statement is executed, and none is returned by default
‘‘‘
‘‘‘
Def show ():
Print (' a ')
If 1 = = 1:
return [11,22,33]
Print (' B ')

ret = Show ()
Print (ret)
‘‘‘
‘‘‘
The result is
A
[11, 22, 33]
The explanation is: after executing the IF statement, the execution of the return [11,22,33] program is also interrupted
‘‘‘
‘‘‘
###### #程序的debug模式 # # #
In the left gray position of the statement with the mouse point, a red dot will appear, which is the program's breakpoint
There is a debug mode run key on the right side of the normal execution button. After execution, the program will proceed normally,
In the normal execution of the feedback interface, there is a button, click, the program will go down one step, you will see the program run debugging process.
‘‘‘

‘‘‘
##### #形式参数
Import Smtplib
From Email.mime.text import Mimetext
From email.utils import formataddr
def sendmail (user):
RET = True
Try
msg = Mimetext (' e-mail Content-This is the message I sent by writing the program ', ' Plain ', ' utf-8 ')
Msg[' from '] = formataddr ([' wangshiqing ', ' [email protected] ')
Msg[' to '] = formataddr ([' Wangqq ', ' [email protected] ')
msg[' Subject ' = "Subject--python program test"

Server = Smtplib. SMTP ("smtp.126.com", 25)
Server.login ("[Email protected]", "[Email Protected]_4")
Server.sendmail (' [email protected] ', [User,],msg.as_string ())
Server.quit ()
Except Exception:
RET = False
return ret

ret = SendMail (' [email protected] ')
IF RET:
Print ("Send Success")
Else
Print ("Send Failed")
‘‘‘
‘‘‘
# # # #一个参数
Def show (A1):
Print (A1)
ret = Show (100)
Print (ret) # # #结果是 100
# # # None
‘‘‘
‘‘‘
##### #二个参数
Def show (A1,A2):
Print (A1,A2)
ret = Show (123,999)
Print (ret)
# # #结果是
#123 999
#None
‘‘‘
‘‘‘
####### #默认参数
Def show (a1,a2=999):
Print (A1,A2)
ret = Show (123)
Print (ret)
# # #结果是
#123 999
#None
# # # # #默认参数1: Only at the end, 2 if you assign a value, the value of the new assignment is the standard
‘‘‘
‘‘‘
# # # #指定参数
Def show (A1,A2):
Print (A1,A2)
ret = Show (a2=999,a1=123)
Print (ret)
‘‘‘
‘‘‘
####### #动态参数
#def Show (*args):
# Print (Args,type (args))
#ret = Show (11,22,33,44,55)
#print (ret)

#def Show (**args):
# Print (Args,type (args))
#ret = Show (n1= ' ere ', n2= ' Sffds ', n3=100)
#print (ret)

Def show (*args,**kwargs):
Print (Args,type (args))
Print (Kwargs,type (Kwargs))

ret = Show (11,22, ' SDFs ', 33,n1= ' ere ', n2= ' Sffds ', n3=100)
Print (ret)
‘‘‘
‘‘‘
(One, A, ' SDFs ', ") <class ' tuple ' >
{' N1 ': ' ere ', ' N2 ': ' Sffds ', ' N3 ': <class ' dict ' >
None
1 * After the parameters are passed in, a tuple is obtained
2,** passed in the parameter, the resulting dictionary, that is, the parameters passed in the form of ####=###
32 forms Mixed Words, * written in front * * Written in the back of the parameters when the 11,22 this form must also be written in front
‘‘‘

‘‘‘
Def show (*args,**kwargs):
Print (Args,type (args))
Print (Kwargs,type (Kwargs))

L = [11,22,33,44]
D = {' N1 ': ' abc ', ' Alex ': ' EF '}
#ret = Show (L,d)
#print (ret)
ret = Show (*L,**D)
Print (ret)

Print (Show (L,D)) executes as follows, because l,d conforms to *args, and the tuple can contain lists and dictionaries
([One, one, one, and], {' Alex ': ' EF ', ' N1 ': ' abc '}) <class ' tuple ' >
{} <class ' dict ' >
None

Print (Show (*l,**d)) execution results are as follows, is explicitly told the program, its own needs
(One, all, <class) ' tuple ' >
{' N1 ': ' abc ', ' Alex ': ' EF '} <class ' Dict ' >
None

‘‘‘



‘‘‘
S1 = "{0} is {1}"
#ret = S1.format (' Alex ', ' 2b ')
#print (ret)

L = [' Alex ', ' 2b ']
ret = S1.format (*l)
Print (ret)

S1 = "{name} is {acter}"
#ret = S1.format (name = ' Alex ', acter = ' 2b ')
#print (ret)

D = {' name ': ' Alex ', ' acter ': ' 2b '}
ret = S1.format (**d)
Print (ret)
‘‘‘



‘‘‘
The above content implementation "function dynamic parameter implementation string Formatting"
The results are Alex is 2b
‘‘‘

# # # #lambda representation of simple functions of expressions
# #创建了形式参数a
# # #有了函数内容, a+1 and return the results
#def func (a):
# b = a +1
# return B
#ret = func (4)
#print (ret)

Func = Lambda a:a+1
ret = func (4)
Print (ret)

####### #上面5行, and the following three lines of expression mean the same.


######## #内置函数 #########
# # #内置函数有哪些
‘‘‘
ABS () absolute value
All () determines whether the elements in the sequence (list, tuple, dictionary) are all true
Fake None empty string, empty tuple, empty dictionary, empty tuple
Any () to determine that the return value is true as long as an element is true
BOOL (None) #判断元素的布尔值

ASCII () ASCII code
Bin () binary
ByteArray () converted to byte array
>>> ByteArray ("Fsdfsfsdfds", encoding= ' Utf-8 ')
ByteArray (b ' Fsdfsfsdfds ')

Callable () is executable
>>> f = Lambda x:x+1
>>> callable (f)
True
>>> F (6)
7

Chr () number to ASCII
Ord () ASCII converted to digital
General application scenario, generate verification code
>>> Import Random
>>> Random.randint (1,99)
75
>>> Random.randint (1,99)
68
>>> Random.randint (1,99)
37
>>> Chr (78)
N

Compile () compilation
Delattr () launch
Dict () dictionary
Dir () All variables all keys
Divmod ()
Enumerate ()
>>> li = [' Alex ', ' yy ', ' ZZ ']
>>> for I in Li:print (i)
...
Alex
Yy
Zz
>>> for I,item in Enumerate (li,1):p rint (I,item)
...
1 Alex
2 yy
3 ZZ
# # #enumerate increased from 1 onwards

Eval ()
Filter () uses the map () function to process a new list of values that the original list meets the requirements
Map () Processes a new list of all values in the original list by using the map () function
11:34
>>> li = [11,22,33,44]
>>> map (Lambda X:x+100,li)
<map Object at 0x0050b990>
>>> New_li = map (lambda x:x+100,li)
>>> for I in New_li:print (i)
...
111
122
133
144

>>> li = [11,22,33,44]
>>> def foo (a):
... if a>33:
.... return True
.. else:
... return False
...
>>> New_li2 = Filter (Foo,li)
>>> List (NEW_LI2)
[44]


Float ()
Format ()

GetAttr ()

Frozenset () Freeze set
Set ()

Globals () current global variable
Locals () Local variables

Hash ()

Help ()
Hex () hexadecimal 0x indicates
The Oct () octal 0o represents

Max ()
Min ()
SUM ()

Pow
Range () Interval 17:40
>>> i = range (1,10)
>>> for A in I:print (a)
...
1
2
3
4
5
6
7
8
9


Reversed () reversal
Round () rounding

Slice () slices
Sorted () sort
STR () string



Super ()
VARs () dir all keys

Zip () # # #混合, get a list
>>> x = [+ +]
>>> y = [4,5,6]
>>> zipped = Zip (x, y)
>>> List (zipped)
[(1, 4), (2, 5), (3, 6)]

‘‘‘


########## #open function
#f = open ("Test.log", ' W ', ' Encoding=utf-8 ')
# #f. Write (' ABCDEFG ')
#f. Close ()
#print (f)


f = open (' Test.log ', ' W ')
F.write (' ABCDEFG ')
F.close ()
Print (f)

python--function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.