Python Functions | Python Tutorial for Absolute Beginners #1

未能成功加载,请稍后再试
0/0

So far you have learned how to use some of the built-in functions in Python such as print, round and so on.

In this section you're going to learn how to write your own functions.

Now you might ask but why do we even need to write our own functions?

Well, when you build a real program that program is going to consist hundreds or thousands of lines of code.

You shouldn't write All that code in one file like we have done so far You should break that code into smaller more maintainable and potentially more reusable chunks You refer to this chunks as functions.

So let me show you how to create your own custom functions We start with a def keyword which is short for define Next we need to give our function a name So let's call this greet all the best practices You learned about naming your variables also apply to naming your functions.

So make sure your function names are meaningful Descriptive use lowercase letters to name your functions and an underscore to separate multiple words Now after the name we need to add parentheses.

You will see why shortly and then we'll add a Colon now what is gonna happen?

You know it we're gonna get indentation Which means the following statements will belong to this function So here I'm going to add two statements hi there and Welcome aboard Both designs belong to this function because they're indented Now we're done with this function.

We need to call it So we remove the indentation and we add two line breaks after this function This is what pep8 recommends to keep our code clean and maintainable now If you forget to add two line breaks, don't worry As soon as you save the changes auto pep8 will automatically add these line breaks for you.

下载全新《每日英语听力》客户端,查看完整内容