Python basics [Article 3], python Article 3

Source: Internet
Author: User

Python basics [Article 3], python Article 3

Def function name (parameter):... function body...

Functions are defined as follows:

  • Def: indicates the function keyword.
  • Function Name: name of the function. The function will be called Based on the function name in the future.
  • Function body: perform a series of logical calculations in the function, such as sending emails and calculating the maximum number in [11, 22, 38,888, 2...
  • Parameter: provides data for the function body.
  • Return Value: After the function is executed, the caller can return data.

Parameters and return values are important in the preceding key points:

Differences from other advanced languages:
1. declare that the function name must end with a colon.
2. It does not need to enclose statement blocks with curly brackets and indent them with the TAB key.

The most important thing in functional programming is to enhance code reusability and readability.

Instance:

Def test_a (): print 'Hello world' print 'www .jeapedu.com' def test_ B (varl, var2): # Function Definition, form parameter, provide an interface to the user. print val1, print val2, print 'entry scheme' test _ a () test_ B () # function call, real parameter. print 'Leave programme'

1. Return Value

A function is a function block. Whether the function is successfully executed or not, the caller must be informed of the returned value.

Def send SMS (): the code for sending the SMS... if the message is sent successfully: return True else: return False while True: # The returned value is automatically assigned to result # Each time the SMS sending function is executed, and logs can be written based on the result, or resend and other operations result = send SMS () if result = False: record the log, SMS sending failed...

2. Parameters

Why is there a parameter? See the following example:

If no parameter is defined, use a function: (write a function for each function with the same function. What about code simplification ?)

Def CPU alarm email () # Send email reminder connect email server send email close connection def hard disk alarm email () # Send email reminder connect email server send email close connection def memory alarm email () # Send email reminder connect to email server send email close connection while True: if cpu usage> 90%: CPU alarm email () if hard disk space> 90%: Hard Disk alarm email () if memory usage> 80%: Memory alarm email ()

The function has three different parameters:

  • Common Parameters
  • Default parameters
  • Dynamic Parameters
  • 1. receive multiple parameters
    2. Automatically construct tuples internally
    3. sequence, *. Avoid constructing tuples internally.

  • 1 >>> li = (, 'Alex ') 2 >>> 3 >>> def func (* args): 4... print args 5... 6 >>> func (li) 7 (1, 2, 3, 4, 5, 66, 'Alex '),) 8 >>> func (* li) 9 (1, 2, 3, 4, 5, 66, 'Alex ') 10 >>> li = [1, 2, 3, 4, 5, 66, 'Alex '] 11 >>> def func (* args): 12... print args13... print args [0] obtain element 14 through subscript >>> func (li) 15 ([1, 2, 3, 4, 5, 66, 'Alex '],) 16 >>> func (* li) 17 (1, 2, 3, 4, 5, 66, 'Alex ') 18 >>>
Common parameter default parameter dynamic parameter 1 dynamic parameter 2 dynamic parameter 3

If the last parameter in a function definition has a ** (double star) prefix, all other keyword parameters other than the normal parameter will be placed in a dictionary and passed to the function. For example:

1 def contacs (a, ** B): 2 print "a is: % s" % a 3 for I in B: 4 print I + ": "+ str (B [I]) 5 6 contacs (100, saneri = 1234567890, rain = 007) # Call 7 8 a is: 100 # execution result 9 saneri: 123456789010 rain: 7

Extended: mail sending instance

Import smtplibfrom email. mime. text import MIMETextfrom email. utils import formataddrdef email (message): msg = MIMEText ("mail alarm test", 'plain ', 'utf-8 ') msg ['from'] = formataddr (["saneri", 'saneri @ 126.com ']) # sender and sender's email msg ['to'] = formataddr (["recipient ", '1970 @ qq.com ']) msg ['subobject'] = message # Here I called the parameter server = smtplib. SMTP ("smtp..com", 25) server. the login ("saneri@126.com", "password") server. sendmail ('shuaige @ 126 . Com ', ['2014 @ qq.com',], msg. as_string () server. quit () if _ name _ = U' _ main _ ': cpu = 100 disk = 500 ram = 50 for I in range (1 ): if cpu> 90: alert = u'cpu problems '# An email (alert) variable is set here # The above variable is referenced when the function is called, when the function is executed, the parameter description will be replaced, and message = 'cpu is faulty 'will be sent! If disk> 90: alert = U' hard disk problems 'email (alert) if ram> 80: alert = U' memory problems 'email (alert)

Bytes --------------------------------------------------------------------------------------------------

If you execute python test. py, it is equivalent to _ name _ = '_ mail __'

 

Steps of execution, __name _ 'value =__ mail __

The return statement is used to return (return) from a function, that is, to jump out of the function. Similarly, we can selectively return a value from the function.

1 def maximum (x, y): 2 if x> y: 3 return x4 elif x = y: 5 return 'two numbers are equal to '6 else: 7 return y8 9 print (maximum (2, 3 ))

Output:
3

 

 

 

 

Python is more and more widely used. To a certain extent, it also relies on providing a large number of modules for programmers. If you want to use modules, You need to import them.

Python has three methods for importing modules:

Import modname

From modname import funcname as rename

From modname import fa, fb, fc orFrom modname import *

The import module is based on the path sys. path as the benchmark.

1 import sys2 3 print sys. results of path4 7: 8 9 ['/Users/wupeiqi/PycharmProjects/calculator/p1/pp1','/usr/local/lib/python2.7/site-packages/setuptools-15.2-py2.7.egg ', '/usr/local/lib/python2/

If the sys. path list does not have the desired path, you can use sys. path. append ('path') to add

 

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.