Data flow control tools in Python

Tram Ho

(image from internet)


Welcome to the next post in the “The Python Tutorial” section of the “Explore Python Citadel” series.

The Python Tutorial brings out the most basic Python concepts and features and its syntax.

I already know through the basic data types as well as related calculations in the previous article. In this article, I continue to learn about data flow control tools, also known as Control Flow Tools, and go deeper into Python functions.

The content in this series article is mainly from and then rewritten in my own language. There are words in specialized English, I am not sure if the translation is correct, so I keep half fat (English and Vietnamese).

Data flow control tools in Python

if, for, break, continue, pass, else in loops and range ()

The if, else statement is probably the most popular group of branch statements in the world, it represents our “If … then” mantra. But not one if one is okay, this world is very complicated, so sometimes it takes many if many to finish, so the group of if… elif… elif…… else commands was born. “Switch … case” in javascript.

As for loops, with a for statement, you can loop through each element in a list (list) or a dictionary (dict), even loop through a string and work with each element of it.

However, when iterating over reference values ​​such as dict, list (don’t know how to use the word, like ref to a data position in js), the value of each element is changed. will affect the original value so people encourage you to make a copy to use, or create a new value to save the changes.

Please see an example below:

Besides, there is a convenient function that can be used to loop through strings of numbers, which is the range () function.

By default, range (number) loops from 0 to number , with the default iteration increment by 1.

If you want to start from a nonzero number, you can write range (start_number, end_number) as range (3, 5).

– If you want a step other than 1, change the 3rd parameter to the iteration value, for example, range (0, 10, 3) will iterate through 0, 3, 6, 9.

In the past, it was common to combine range () and len () to iterate over a list because indexes showing the order of the elements in the list correspond to the range of the length of the list, like this: range ( wool())

But later on, using the enumerate () function is more convenient.

With range (), it is an object of class “range”, and is a generator (which can be looped through) rather than a list as you think, if you want it to be a list you must use the list to convert it to. .

break, continue and else in a loop and pass

If there is a loop, there must be a way to jump out of that loop, or continue to loop through another element without reading all the code of this element, break and continue help you do that. In Python, there is something strange, that else can go with for too.

As for the pass command, it represents the “do nothing”, “ignore”, it is useful when I write structure for the app, set the class name, function freely and then add the pass in the body, there will be no error. Where is the syntax.


In Python, the function is defined by the keyword ” def ” followed by the function name and a list of parameters encased in () . Usually each function will have docstrings on the first line of the body describing that function. When calling the function and passing the argument, the argument will be received according to its position or its keyword (if that position has no arguments passed).

In the function, to return something we use return . If no specific value is returned then return is None by default.

There are default functions of each object type in Python, for example append () is the function of object list. We can check with the dir () command of that object.

When defining a function, often with its arguments, three types of arguments are used:

Default Argument Values ​​(Default Argument Values)

The arguments associated with their default values. In the case no corresponding value is passed, the value of that argument is the default value, for example:

def ask_ok(promp, retries=4, reminder=”Please try again”)

the retries parameter has a default value of 4

the reminder parameter defaults to “Please try again”.

Note: the default value is only assigned once, so when this value is assigned with mutable objects (can be changed) such as list, dict or class instance, it will be confusing as the following example :

Keyword Arguments

By default, the values ​​pass in the order of their respective arguments. If an argument has no default value then it is a required argument to be passed.

The keyword argument is of the form kwarg = value , and uses the keyword to define which argument the value to pass in, regardless of its order.

The placement argument must precede the keyword argument

When there are too many arguments, you can use * or ** with a name for the wildcard argument, for example def bananashop(kind, *args, **kwargs) . A representative argument is a list of arguments (more under the argument section is a list).

Special parameters

Because a function’s arguments can be positional or keyword-driven and both types can be either alone or in the same function. So set up a general formula, so that from which one can look at and know what is the positional argument, which is the keyword argument, and what is possible either by the following formula:

Here, / and * are optional. If used, these special arguments indicate how the values ​​are passed to the function:

position only : includes only position arguments

positional or keyword : can be a position argument or keyword argument

keyword only : includes only the keyword argument

For example

Below is a function that has arbitrary arguments, be it the positional argument or the keyword argument is allowed:

Here is the function that allows only the join position argument, defined with the special keyword / and the argument preceding it:

Below is a function that allows only the keyword argument to join, defined with the special keyword *, and the argument after it:

Finally, the function allows all 3 types (allows only position arguments, allows only keyword arguments, allows both types) to participate and specifically divide by two special keywords /, *

In a nutshell, keep in mind the Python function definition formula:

And a few instructions for each type:

  • The positional argument should only be used when the parameters don’t know how to name it properly (since it has no specific meaning).
  • The keyword argument should be used preferably to define clear, understandable keyword names.
  • For the API, use the positional argument only to prevent changes if the parameter names can be modified in the future.

The argument is an optional list

This is an argument type that can fluctuate depending on the arbitrary argument lists, these values ​​will be wrapped in a tuple (args in the example below), for example:

Usually, this argument is placed at the end of the list and in the case behind it, it must be the keyword argument.

Extract a list of arguments

Above, we see the arguments passed separately but when entering the function they are wrapped in a tuple (is args). And vice versa, sometimes I pass a list, or a tuple and want to decompress it in the function, this process is called “unpacking”.

Example 1 : function range () takes two arguments start and stop, but args is a list so we unpacking it with * when used with range.

Example 2 : unpacking a dictionary where the key is the keyword argument and the value is the value passed in **.

Lambda expression

In addition to defining functions using def , the lambda keyword can be used to define an unnamed function that is limited to a single expression.

A lambda function is often used when it is necessary to quickly define nested functions in another function, for example assigning a key in a sort function to a lambda function.

Docstrings of the function

Docstrings are a type of notation that can span multiple rows, beginning and ending with “” (3 quotes), often used just below the function declaration in Python to interpret the content and meaning. arguments and return value.

Some conventions about its content and format like the first line is a concise sentence that expresses the general meaning, followed by a blank line, then more specific content for the description. .

Function Annotations

Function Annotations are function annotations about user-defined data types in a function.

Annotations are stored in the annotations property of the function, which is defined after the: of the argument name and the data type of the function to be returned with a -> sign, for example:

full_name. annotations will have the value of:

{'full_name': <class 'str'>, 'return': <class 'str'>, 'first_name': <class 'str'>, 'last_name': <class 'str'>}

Coding Style

Above, I have learned through commands and groups of commands as well as learned about functions from simple to detailed, and this is the time to talk about coding style in Python (because the code is long, I can’t just like to write. ^^):

In Python, PEP8 is very popular as a guide on how to write Python code that most projects adhere to, making the code easy to read and pleasant, here are a few important things you need to know:

→ The indent is 4 spaces (no tabs are used)

→ One line must not exceed 79 characters long

→ Each function, class is separated by 2 blank lines, and the code in function / class is separated by one line

→ Annotation should be placed on the comment line, using docstring to define the meaning of the function and related information.

→ The space is completely used around the operators and after the sign, for easy reading

→ The class name is set to UpperCamelCase and the function and method name in the class is set to lowercase_with_underscores . Always use self as the name of the first param of the method in the class

→ Use common encoding types such as UTF-8, ASCII

→ Do not use different languages ​​in code (for example, do not comment in Vietnamese @@)


I work with Python every day, use its control flow and function every day, but now I can really say that I’ve learned through them ^^

Today, all of you will learn Python to come here with me, these contents are all basic Python knowledge that I both read and write to keep reviewing.

In the following article, I will continue to learn about Python’s data structure in ” The Python Tutorial ” in the great crap series “Explore Python Citadel”.

Thanks for reading,

I’m practicing blogging, everyone visit my house to play. Follow / like this fanpage to update the latest posts. Some good sources that I can collect are also saved here


Share the news now

Source : Viblo