13 python tips you don't know

Posted by simon_belak on Wed, 05 Jan 2022 21:23:57 +0100

Python is one of the top programming languages. It has many hidden functions that many programmers have never used.

In this article, I'll share 13 Python features you may never have used.
Don't waste time, let's start.

Click here to run the code

1. Data retrieval by step

Knowledge points: list[start:stop:step]

  • Start: start indexing. The default value is 0
  • End: end the index. The default is the length of the list
  • Step: the step size is 1 by default. It can be negative. If it is negative, it is in reverse order
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(data[::2]) # [1, 3, 5, 7, 9]
print(data[::-1]) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(data[2:7:-2]) # []  ⚠️ Note: when the step size is negative, the result is empty
print(data[7:1:-2]) # [8,6,4] # ⚠️  index belongs to [7 - > 1], and the step size is 2.

2. find method

Knowledge points: list find(obj, [start, [stop]])

  • List: list or string
  • obj: elements to find
  • Start: start indexing. The default value is 0
  • stop: end the index. The default is the length of the list

Return - 1 not found

x = "Hello From Python"
print(x.find("o")) # 4
print(x.find("o", 5)) # 8
print(x.find("From Python")) # 6
print(x.find("No exist")) # -1

3. iter() and next()

# The iter() function is used to convert an iteratable object into an iterator
# The next() function is used to get the next return value of the iterator
values = [1, 3, 4, 6]
values = iter(values)
print(next(values)) # 1
print(next(values)) # 3
print(next(values)) # 4
print(next(values)) # 6
print(next(values)) # StopIteration

4. Test documents

The Doctest function will let you test your function and display your test report. If you check the following example, you need to write a test parameter in triple quotes, where > > > is a fixed syntax. You can add a test case and run it! As follows:

# Doctest
from doctest import testmod
  
def Mul(x, y) -> int:
   """
   This function returns the mul of x and y argumets
   incoking the function followed by expected output:
   >>> Mul(4, 5)
   20
   >>> Mul(19, 20)
   39
   """
   return x * y
testmod(name='Mul')

# The output is as follows:
"""
**********************************************************************
File "main.py", line 10, in Mul.Mul
Failed example:
    Mul(19, 20)
Expected:
    39
Got:
    380
**********************************************************************
1 items had failures:
   1 of   2 in Mul.Mul
***Test Failed*** 1 failures.
"""

5. yield

The yield statement is another amazing feature of Python. It works like a return statement. But instead of terminating the function and returning, it returns to where it returns to the caller.

yield returns a generator. You can use the next() function to get the next value of the generator. You can also use the for loop to traverse the generator.

def func():
    print(1)
    yield "a"
    print(2)
    yield "aa"
    print(3)
    yield "aaa"

print(list(func())) ## ['a', 'aa', 'aaa']
for x in func():
    print(x)

6. Handling of missing keys in dictionary

dic = {1: "x", 2: "y"}
# Dict cannot be used_ 1 [3] get value
print(dic[3]) # Key Error
# Use the get() method to get the value
print(dic.get(3)) # None
print(dic.get(3, "No")) # No

7.for-else, while-else

Did you know that Python supports for else and while else? This else statement will be executed after your loop runs without interruption. If the loop is interrupted in the middle, it will not be executed.

# for-else
for x in range(5):
    print(x)
else:
    print("Loop Completed") # executed
# while-else
i = 0 
while i < 5:
    break
else:
    print("Loop Completed") # Not executed

8. The power of f-string

a = "Python"
b = "Job"
# Way 1
string = "I looking for a {} Programming {}".format(a, b)
print(string) # I looking for a Python Programming Job
#Way 2
string = f"I looking for a {a} Programming {b}"
print(string) # I looking for a Python Programming Job

9. Change recursion depth

This is another important feature of python, which allows you to set the recursion limit of Python programs. Take a look at the following code example to better understand:

import sys
print(sys.getrecursionlimit()) # 1000 default
sys.setrecursionlimit = 2000
print(sys.getrecursionlimit) # 2000

10. Conditional assignment

The conditional assignment function uses ternary operators to assign values to variables under specific conditions. Take a look at the following code example:

x = 5 if 2 > 4 else 2
print(x) # 2
y = 10 if 32 > 41 else 24
print(y) # 24

11. Parameter unpacking

You can decompress any iteratable data parameter in the function. Take a look at the following code example:

def func(a, b, c):
    print(a, b, c)

x = [1, 2, 3]
y = {'a': 1, 'b': 2, 'c': 3}
func(*x) # 1 2 3
func(**y) # 1 2 3

12. Call the world (useless)

import __hello__ # Guess what?
# other code
import os
print(os) # <module 'os' from '/usr/lib/python3.6/os.py'>

13. Multiline string

This feature will show you how to write a multiline string without triple quotes. Take a look at the following code example:

# Multiline string
str1= "Are you looking for free Coding " \
"Learning material then " \
"welcome to py2fun.com"
print(str1) # Are you looking for free Coding Learning material then welcome to Medium.com

# Triple quote string
str2 = """Are you looking for free Coding
Learning material then 
welcome to py2fun.com
"""
print(str2) #Different from the above, the newline will also be output.

Section

These are the 13 features of Python shared today. I hope you find this article interesting and useful.

Welcome to praise, collect and support!

pythontip Happy Coding!

Official account: quark programming

Topics: Python Back-end