8 interesting facts about Python in the eye of a newcomer

Tram Ho

Recently I just jumped into Python, because of my curious nature, I often look for good tricks of that language =)) So today I will list the good things I found under the eyes of a young man. Ruby jumped: 3

else paired with for ????

Have you ever seen the else else go with the for loop? =)) But Py has a special type of syntax that only executes if the for loop exits naturally without any interrupt statements. .

Result of above function:

1st Case: 2

2nd Case: No call for Break. Else is executed

Decompress variable: 3

Argument Unpacking (variable decompression) function is another great feature of Python. We can extract a List or Dictionary to use as a variable using * and **. This is often called the Splat operator. Example here:

Output:

3 4

2 3

Find the index in the loop

This is fairly simple, but unlike Ruby, each_with_index has a name that specifies its function =)) Py has the corresponding ‘enumerate’ function but the name is not very relevant =,., = In general It also returns an element of the loop associated with its index:

Output:

(0, ‘a’)

(1, ‘e’)

(2, ‘i’)

(3, ‘o’)

(4 U’)

To infinity and beyond !!! and back ??

Can we define infinity? But wait! Not with Python. Take a look at this great example:

Output:

Infinity is greatest

Negative Infinity is least

Slice Operator

Python’s has something special called the Slice Operator. It is actually just a collection of fancy ways to retrieve items from the list, as well as change them. Take a look at this code:

Output:

[twelfth]

[1, 2, 3, 4]

[5, 4, 3, 2, 1]

[1, 3, 5]

[5, 3, 1]

If there’s a decompression, there must be compression, right? (The two are not related to each other =)))))

Want to compress two Lists into a 2-dimensional matrix. Just use zip to do it.

Results (try using a decompression to see if it looks good):

[(1, 4), (2, 5), (3, 6)]

Function declaration in place (wow)

You want to declare a small function, but you don’t want to scroll down and declare it below. Don’t worry, you can use lambda. The keyword lambda in python is used to declare the function anonymously, you can declare the function anytime and anywhere without worrying about which father =)) (kidding, declaring some small functions: v)

Loop String N times

Normally in other languages ​​to do this we will use the loop, but python has a simple trick involving a string and some inside the print function. (I thought Ruby had it anyway)

Output:

PointPointPoint

I just started learning so I only learn the beauty of the language, next time I will come back and benefit from the good points of the Django framework. Many thanks to everyone who read my article (bow).

Share the news now

Source : Viblo