13 python tricks you didn't know

Python is one of the top programming languages ​​and it has many hidden features that many programmers never use.

In this article, I will share 13 Python features that you may never use.
Without wasting time, let's get started.

Click here to run the code

1. Take the number by step

Knowledge points:list[start:stop:step]

  • start: start index, default is 0
  • end: end index, defaults to list length
  • step: The step size, the default is 1, it can be negative, if it is negative, the order is reversed.
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]) # [] ⚠️注意:步长为负数时,结果为空
print(data[7:1:-2]) # [8,6,4] # ⚠️ index 属于 [7 -> 1),步长为2。

2. find method

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

  • list: list or string
  • obj: element to find
  • start: start index, default is 0
  • stop: end index, defaults to list length

not found returns -1

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()

# iter() 函数用于将一个可迭代对象转换为一个迭代器
# next() 函数用于获取迭代器的下一个返回值
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 documentation

DoctestFeatures will let you test your features and display your test report. If you check the example below, you need to write a test parameter in triple quotes, where >>>is the fixed syntax, you can add test cases, 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')

# 输出如下:
"""
**********************************************************************
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

yieldStatements are another amazing feature of Python that work like returnstatements . But instead of terminating the function and returning, it returns to where it returned to the caller.

yieldWhat is returned is a generator. You can use the next()function to get the next value of the generator. You can also use a forloop to iterate over 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_1[3] 获取值
print(dic[3]) # Key Error
# 使用 get() 方法获取值
print(dic.get(3)) # None
print(dic.get(3, "No")) # No

7.for-else, while-else

Did you know that Python support comes with for-else, while-else? This elsestatement will be executed after your loop has finished running without interruption, and will not be executed if the loop is interrupted midway.

# 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-strings

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 the recursion depth

This is another important feature of Python that allows you to set recursion limits for Python programs. Take a look at the code example below for a better understanding:

import sys
print(sys.getrecursionlimit()) # 1000 默认值
sys.setrecursionlimit = 2000
print(sys.getrecursionlimit) # 2000

10. Conditional assignment

The conditional assignment feature uses the ternary operator to assign values ​​to variables under certain conditions. Take a look at the code sample below:

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 unpack any iterable data parameter in the function. Take a look at the code sample below:

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 (it's useless)

import __hello__ # 你猜输出啥?
# other code
import os
print(os) # <module 'os' from '/usr/lib/python3.6/os.py'>

13. Multi-line strings

This function will show you how to write multi-line strings without triple quotes. Take a look at the code sample below:

# 多行字符串
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

# 三重引号字符串
str2 = """Are you looking for free Coding
Learning material then 
welcome to py2fun.com
"""
print(str2) #和上面的是不同的,换行也会被输出。

subsection

Those are the 13 features of Python shared today, I hope you found this article interesting and useful to read.

Everyone is welcome to like, subscribe, and support!

Produced by pythontip , Happy Coding!

Public number: Quark programming

Related Posts