Lesson 17: Functions: Lego bricks for python

Source: Internet
Author: User
Tags decimal to binary gcd greatest common divisor

Directory:

First, create and Invoke functions

Second, the parameters of the function

Third, the return value of the function

Iv. 17 lessons After class exercises and answers

To make the code of the program simple, you need to break the program down into smaller parts. There are three ways to implement: Functions, objects, modules.

***********************

First, create and Invoke functions

***********************

The previous contact with the BIF is python to help us encapsulate the function. Create a function with the DEF keyword in python.

def myfristfunction ():       Print ("DC Love zww")       Print ("1314520")

Note: After the function, add a pair of parentheses . This parenthesis is essential. Next is the invocation of the function:

>>> myfristfunction () DC love Zww1314520

function invocation and operation mechanism : when the function myfristfunction () occurs, Python will automatically find the definition of Def myfristfunction (), and if not found it will error. It then executes the portion of the block of code that the function contains (that is, the portion of the content that is indented after the colon). Only one statement is required to implement the functions within the function.

If, I want to print the content just 3 times, I just need to call 3 times function:

 for  in range (3):    myfristfunction ()    DC love zww1314520dc love zww1314520DC Love ZWW 1314520

******************

Second, the parameters of the function

******************

The parameters of the function are placed in parentheses. Parameters are what makes a function possible to personalize:

def mysecondfunction (name):     Print (name+" love zww")     >>> mysecondfunction ("DC") DC love Zww>>> mysecondfunction ("DC") DC Love Zww

When using multiple parameters, you only need to separate them with commas:

def Add (name1,name2):     Print (name1+""+name2)     >>> Add ("DC","zww") DC Love ZWW 

How many parameters can that actually be? How many you want in theory.

*********************

Third, the return value of the function

*********************

For our function to have a return value, just use the keywordreturn in the function, followed by the value to be returned.

>>>defAdd (name1,name2):Print(name1+" Love"+name2)return " Love">>> Add ("DC","ZWW") DC Love Zww' Love'>>>defAdd (name1,name2):Print(name1+" Love"+name2)returnname1>>> Add ("DC","ZWW") DC Love Zww'DC'

*******************************

Iv. 17 lessons After class exercises and answers

*******************************

Test questions:

0. Have you ever heard of dry?

Answer: Dry is a well-known guideline for programmers:Don ' t Repeat yourself.
Just arm your mind, pick up the function, and don't repeat the code again.

1. Repeating a piece of code, why should I use a function instead of a simple copy sticker?

For:

Using Functions :

0) can reduce the amount of code (call function only need one line, and copy paste requires n times code)1) can reduce maintenance costs (function only need to modify the Def part of the content, while the copy paste will require each occurrence of the place to be modified)2) Make the order easier to read (no one would want to see a program repeat 10,000 lines "I love Fishc.com")

2. Can a function have more than one parameter?

A : Yes, theoretically you want to have how many can have how many, but if the function of too many parameters, in the call when the probability of error will be greatly improved, so the programmer writing this function will be the corresponding greetings to the ancestors, so, as far as possible, in the python world , the simplification is the kingly way!

3. What keywords are used to create functions, and what should be noted?

A : use the "def" keyword, notice that the function name is followed by the parentheses "()", and then the parentheses are followed by a colon ":", and then the indentation is part of the function body content, for example:

def myfun ():     # I am the function body    # I'm also a function body    . # we all belong to the function myfun () # Oh, I don't belong to the Myfun () function anymore.

4. What are the parameters of this function?

def Myfun ((x, Y), (A, B)):     return x * y-a * b

A : If you answer two, then congratulations on your mistake, the answer is 0, because similar to the writing is wrong!

In our analysis, the parameters of the function need variables, and here you try to use the "meta -ancestor" form to pass is not feasible.

I think if you write like this, you should be saying something like this:

def myfun (x, y):         return x[0] * x[1]-y[0] * y[1]>>> myfun ((3, 4), (1, 2))10

5. What will be printed by calling the following function?

def Hello ():         Print ('Hello world! ' )        return        print('Welcome to fishc.com! ')

A : it will print:

>>> hello () Hello world!

Because when Python executes to the return statement,Python considers the function to end and needs to return (although there is no return value).


Moving hands:


0. Write a function power () to simulate the built-in function pow (), that is, power (x, y) is the value that calculates and returns the Y-power of X.

Solution:

def Power (x, y):     = 1 for in          Range (y):        *= x    return  result Print (Power (2, 3))

1. Write a function that uses the Euclidean algorithm (brain complement link) for greatest common divisor, such as gcd (x, y) to return a value of greatest common divisor of parameter x and parameter Y.

Solution:

def gcd (x, y):      while y:         = x% y        = y        = t    return  x    print(GCD (4 , 6))

2. Write a function that converts decimal to binary, requiring the use of the "except 2" (brain-complementary link) method, and the result is returned as a string as the call Bin ().

Solution:

def Dec2bin (dec):     = []    'while          Dec        := Dec% 2        = Dec//2         Temp.append (Quo)    while  temp:        + = str (temp.pop ()        )  return  resultprint(Dec2bin (62))

Lesson 17: Functions: Lego bricks for python

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.