Python functions (Chapter II: Functions)

Source: Internet
Author: User
Tags stack trace

A-how to create a function.

B-gives some guidelines to help you think about how to create and organize programs to use functions.

C-How to write functions so that you can then ask them how they work and what they implement.

2.1 Put the program in a separate file

For added convenience, from now on, you should enter the program you are using in the Python Code editor and put the case of the book in a file so that you can reference and run the case later. One possible recommendation is to name the directory "Learning Python", which can then be named after the program's appearing chapters.

2.2 Functions: Aggregating code under a name

Modern programming languages provide the ability to assemble code under a name whenever they are used, as long as they are called.

To create a named function that contains code, you can use Def, which defines a block of code functionality.

We define a function:

def In_fridge ():     Try :         = Fridge[wanted_food]    except  keyerror:        = 0    return Count

When calling ch5.py, if only the In_fridge function is defined, this will not see any output, however, the function will be defined and can be called from an interactive Python session that has been created.

To use the In_fridge function, you must make sure that you have a fridge dictionary that contains the various food names, and that you must have a string named Wanted_food. When you use In_fridge, you can ask if there is something in the string.

>>>fridge = {'apples': Ten,'orange': 3,' Milk ': 2}'apples'>>>in_fridge ()' Orange '>>>In_fridge (3)

This can reduce the workload. When writing a program, a function can be thought of as a process of asking and answering. Because when they are called, they often ask a question, how many, when, does this exist, can this change, and so on. In response, the function returns the value that contains the answer.

Choosing a name, giving a good name to a function, is helpful in remembering their function, even forgetting the code implementation, does not matter much.

Functions described in the function

You can add a description to a function after the function name is selected, and Python can do it in a simple and meaningful way. If you see a string as the first part of a function, and you don't use a name to reference it, Python stores it in a function for later reference. This string is often called docstring (documentation string).

The function's document string is used to describe the function, and few computer software have done a good job of explaining it. Python provides a simple document string feature, with more information available in Python programs than in other languages that lack friendly and helpful conventions.

Such as:

The document character is referenced by the name in the function, as if the function were a dictionary. This name is _DOC_.

The function also has additional information (the set of information it holds can be viewed using the built-in function dir), and Dir shows all the properties of the object (such as a function) you are interested in, including the properties used internally by Python

Same name in different locations:

(1) Note the global scope.

(2) #注释

Calling a function with parameters (not detailed)

Check parameters

The type of parameter you intend to use may be different from the type provided when the function is called, such as the possibility of writing a function that expects a dictionary parameter, but occasionally passing in a list, where the function runs until it needs to access the dictionary-specific operations. The program exits because of an exception.

Python does not check which type of data is associated with a function's parameter name, which in most cases is not an issue because the operation on the given data is specific to a type, and if the name references a data type that is not correct, the program will not work correctly.

When Python attempts to access a value as a dictionary, it throws a except: no error is caught. The resulting TypeError error indicates that the type Python is trying to manipulate does not do what Python expects it to do.

To confirm the type of some data, you can use the built-in function type to validate the variable type at the beginning of the function.

defMake_omelet (omelet_type):ifType (omelet_type) = =type ({}):Print("Omelet_type is a dictionary with ingredients")        returnMake_food (Omelet_type,"Omelet")    elifType (omelet_type) = = Type (""): Omelet_ingredients=get_omelet_ingredients (Omelet_type)returnMake_food (Omelet_ingredients,omelet_type)Else:        Print("I dont think I can make this kind of omelet:%$"% Omelet_type)

Now the definition of Make_omelet does not work, because it also relies on several other functions that are not written.

Using string comparison types

Many objects in Python can be represented as strings, and many object-built methods can convert them into strings

For example:

Because you can know in advance what a string representation of a type is, you can compare that string to an object that is converted to a string by using the STR function.

Calling other functions in a function

Functions declared at the top-level or global scope can be used by other functions and other included functions. The name of the global scope can be used anywhere, because the most useful function needs to be available in other functions.

In order for the Make_omelet function to work as previously seen, other functions it relies on should be available to be used by Make_omerlet.

The way it works is L a function plays the role of a recipe, it is given a string specifying an omelet type, and returns a dictionary containing all the components and their components, which will be called get_omelet_ingredients, and he needs a parameter, which is the name of the omelet:

defget_omelet_ingredients (omelet_name): Ingredients= {"eggs": 2,"Milk": 1}    ifOmelet_name = ="Cheese": ingredients["Cheddar"] = 2elifOmelet_name = ="Westren": ingredients["Jack_cheese"] = 2ingredients["Ham"] =1ingredients["Pepper"] =1ingredients["Onion"] =1elifOmelet_name = ="Greek": ingredients["Feta_cheese"] =2ingredients["Spinach"] =2Else:        Print("thats not on the menu,sorry!")        returnNonereturnIngredients

The second function required to make an omelet is called Make_food, which requires two parameters, and the first parameter is a list of the required components, which are completely derived from the Get_omelet_ingredients function. The second parameter is the food name, which should be the type of omelet:

def Make_food (ingredients_needed,food_name):      for inch Ingredients_needed.keys ():         Print ("adding%d of%s to make a%s"%(ingredients_needed[ingredient],ingredient,food_ Name        )print("made%s"% food_name)          return Food_name

Now that you can use the Make_omelet function, he needs to call functions Get_omelet_ingredients and Make_food to get the job done. Each function provides a part of the process of making an omelet.

Call a completed function

All of the functions are ready to be called, so you just need to specify the name of the omelet you want to make, and then you can use Make_omelet.

function nesting functions

It is important to define a function before using it, and if you try to call it before you define a function, Python does not know the existence of the function at the time of the call, so it cannot be called! Of course, this will cause an error and cause an exception. Therefore, the function is defined at the beginning of the file so that it can be used until the end.

2.3 Hierarchy of functions

Let's consider how they are called and how Python records the call hierarchy.

When a program calls a function, or when a function calls a function, Python creates a list inside it called a stack, sometimes called the call stack.

When the function is called, Python stops for a moment, remembering where the program called the function, and then storing that information in its internal list. Then enter the function and execute it. The following code records how to enter and leave the function:

At the top level, Python starts recording from the first row, and then when the function Make_omelet is called on line 64th, then Make_food is called by Make_omelet, and when the Make_food function ends, Python determines that it is on line 64th, Then return to line 64th and continue execution, the function in this case is fictitious, but you can understand the meaning of it. This list is called a stack, which graphically represents the way to enter a function. As you can imagine, until you exit, a function is at the top of the stack, and when it is removed, the stack's length is reduced by 1.

How to interpret the deep errors

Suppose you pass a dictionary that contains a list instead of a numeric value, which results in an error like this:

When a file enters a function, Python will indicate where you are in the stack (which means how many layers and each layer in the stack is called on which line of the program the error occurred), so you can open the problematic file to confirm what happened.

When you call more functions or use functions to call other functions and create a deep stack, you get the experience of using stack traces (which is the generic name that Python uses for output when throwing an exception or an error). The previous stack trace depth is 3, which you can see in line 45th, when calling Make_food, there is a problem with the parameter type. Stack tracking is a readable form of the stack that can be checked to confirm the problem.

Python functions (Chapter II: Functions)

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.