The fourth chapter of NU python----Function and module

Source: Internet
Author: User
Python functions: In fact, it is very similar to C + +, but because it is a weak type of language (it feels like ...). ), the declaration of those types are removed, the value is not a reference (at least 2.7 is), a little bit small difference is the first must be defined by DEF (like a macro definition). ), show examples below

def sum (A, B): #sum为函数名, note the colon ...
c = A + b #这一部分是函数的语句块
Return c #到这里函数就结束了, same as C + + print sum (1, 2) #根据函数名调用函数, output 1+2 value

There is also a lambda function, similar to C++11 's, giving an example of the preceding addition function

sum = lambda A, b:a + b #这就是lambda函数的定义, starts with lambda, and then passes in parameters, regardless of how many are separated by "," and then ":" After the expression that you want to implement for the operation print sum (1, 2)

Python module: This part of the feeling is related to Java, but the module gives me the feeling is C + + inside the header file and implementation of the file written together, the following examples

The code for the module of the addition function is given first, if there is a fun.py inside the current directory

#!/usr/bin/pythondef sum (A, B):
c = A + B return c

Given the code of the main function, if the current directory is named test.py, import the module fun (this is not Java ...). ),

#!/usr/bin/pythonimport Funprint fun.sum (1, 2)

And sometimes feel very troublesome, that fun is a C + + namespace The same thing, so you can actually put sum through the From...import statement into the current space, give the code

#!/usr/bin/pythonfrom Fun Import Sumprint sum (1, 2)

Sometimes there will be road problems, this is to ensure that the import module in and the main program in a directory is good

The above is the fourth chapter of Nu python---function and module content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.