Have you mastered these 16 must-know Python coding skills? worth collecting!

Insert image description here

Python is a versatile programming language with a large number of libraries and frameworks. There are some little-known Python coding tips and libraries that can make your job as a developer easier and your code more efficient.

This article explores some lesser-known Python tricks that are very useful but not widely known. By learning and using these techniques, you can save time and effort and make your code more elegant and efficient. So, let’s dive into these hidden gems of the Python language!

1. Ternary operator

The ternary operator is short for if-else statement. The syntax is value_if_true if condition else value_if_false. The ternary operator is a single line of code that can replace multiple lines of if-else statements, making your code more concise.

a = 5 
b = 10 
max = a if a > b else b  # value_if_true if condition else value_if_false

print(max)
# 10


The above code works by checking if "a" is greater than "b" and returns "a" if true and "b" if false.

2. Enumeration function

enumerate()The function adds a counter to the iterable object and returns it as an enumeration object. This function is useful when you want to iterate through a list and keep track of the index.

fruits = ['apple', 'banana', 'mango'] 
for index, fruit in enumerate(fruits): 
    print(index, fruit)

# 0 apple
# 1 banana
#2  mango


3. Compression function

The zip() function aggregates the elements from each iterable and returns an iterator of tuples. This function is useful when you want to iterate through two or more lists simultaneously.

list1 = [1, 2, 3] 
list2 = ['a', 'b', 'c'] 
for x, y in zip(list1, list2):
    print(x, y)

# 1 a
# 2 b
# 3 c


4. List generation

List comprehensions are a concise way to create a list from an existing list or any iterable object. This is a one-liner that can replace a for loop, making your code more efficient and more readable.

squared_numbers = [x**2 for x in range(1, 6)]

print(squared_numbers)
# [1, 4, 9, 16, 25]


5. Anonymous functions

LambdaFunctions are anonymous functions defined using the lambda keyword. defThey are useful when you need to write small one-off functions and don't want to use keywords to define named functions.

add = lambda x, y: x + y 

result = add(3, 4)

print(result)
# 7


6.any() and all() functions

The any() function and all() function return True or False based on the authenticity of the elements in the iterable. The function any() returns True if any element in iterable is true, and the function all() returns True if all elements in iterable are true.

numbers = [1, 2, 3, 0, 4] 
result = any(numbers) # True 
result = all(numbers) # False。0使结果为False


7. Iteration module

itertoolsThe module provides a set of functions for working with iterators. Functions in this module include chain, productand permutations.

import itertools 
numbers = [1, 2, 3] 
result = list(itertools.permutations(numbers)) 


# 输出所有排列组合 
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]


8. Generator

A generator is an iterable type that generates values ​​on the fly rather than storing them in memory. It is defined using the yield keyword and is used to create custom iterators.

# 使用yield关键字创建生成器 
def fibonacci_series(n):
    a, b = 0, 1
    for i in range(n):
        yield a
        a, b = b, a + b

# 输出迭代器中的值 
for number in fibonacci_series(10):
    print(number)

# 0
# 1
# 1
# 2
# 3
# 5
# 8
# 13
# 21
# 34



9. Decorator

A decorator is a way to modify the behavior of a function or class. Defined using the @ symbol, which can be used to add functionality to the function, such as logging, timing, or authentication.

def log_function(func):
    def wrapper(*args, **kwargs):
        print(f'Running {func.__name__}')
        result = func(*args, **kwargs)
        print(f'{func.__name__} returned {result}')
        return result
    return wrapper

@log_function
def add(x, y):
    return x + y


print(add(5,7))

# 运行add函数,返回值为12


10. Using multiple function parameters

In Python, you can use the * and ** operators to handle multiple function parameters. The * operator is used to pass the argument list as separate positional arguments, and the operator ** is used to pass a dictionary of keyword arguments.

def print_arguments(*args, **kwargs):
    print(args)
    print(kwargs)

print_arguments(1, 2, 3, name='John', age=30)

# (1, 2, 3)
# {'name': 'John', 'age': 30}


11. Dynamic import

When you want to import a module based on user input or configuration, you can use module dynamic import module importlib.

import importlib

module_name = 'math'
module = importlib.import_module(module_name)
result = module.sqrt(9)


12. Dictionary generation

Dictionary generation is a concise way to create a dictionary from an existing dictionary or any iterable object. It is a single line of code that can replace the for loop, making your code more efficient and more readable.

squared_numbers = {x: x**2 for x in range(1, 6)}
print(squared_numbers)

# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}


13. Callable objects

In Python, any object that can be called a function is called a callable object, including functions, methods, classes, and even __call__objects that define methods.

class Adder:
    def __call__(self, x, y):
        return x + y

adder = Adder()
result = adder(3, 4)

print(result)
#7


14. Separate large numbers/characters with underscores

Large numbers are hard to tell at first glance, so in Python you can use underscores to make numbers easier to read.

num_test = 100_345_405 # 一个大数字

print(num_test)
# 100345405


15. Quickly merge two dictionaries

You can use the following code to quickly merge 2 two dictionaries in Python.

dictionary_one = {"a": 1, "b": 2}
dictionary_two = {"c": 3, "d": 4}

merged = {**dictionary_one, **dictionary_two}

print(merged)  
# {'a': 1, 'b': 2, 'c': 3, 'd': 4} 


16. Lists, Sets and Dictionaries are mutable

Mutable means that an object (list, set, or dictionary) can be changed or updated without changing the object's pointer in memory. The actual effect can be seen in the following example.

In the example below, updating the list of cities by adding a new city, you can see that the ID (object pointer) remains the same, as do the collection and dictionary.


cities = ["Munich", "Zurich", "London"]
print(id(cities)) # 2797174365184
cities.append("Berlin")
print(id(cities)) # 2797174365184


# 集合 

my_set = {1, 2, 3}
print(id(my_set))  # 2797172976992
my_set.add(4)
print(id(my_set))  # 2797172976992


dictionary

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(id(thisdict))  #2797174128256
thisdict["engine"] = "2500cc"
print(id(thisdict))  #2797174128256


Finally, here is a set of free learning materials shared with you for free, including videos, source codes/e-books. I hope it can help those friends who are dissatisfied with the current situation and want to improve themselves but have no direction. You can also add me on WeChat to learn and communicate together.

Python所有方向的学习路线图, know clearly what to learn in each direction

100多节Python课程视频, covering essential basics, crawlers and data analysis

100多个Python实战案例, learning is no longer just about theory

华为出品独家Python漫画教程, you can also learn on your mobile phone

历年互联网企业Python面试真题, very convenient when reviewing

Insert image description here

1. Learning routes in all directions of Python

The Python all-direction route is to organize the commonly used technical points of Python to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.

2. Learning software

If a worker wants to do his job well, he must first sharpen his tools. The commonly used development software for learning Python is here, saving everyone a lot of time.

3. Full set of PDF e-books

The advantage of books is that they are authoritative and have a sound system. When you first start learning, you can just watch videos or listen to someone’s lectures. But after you finish learning, you feel that you have mastered it. At this time, it is recommended that you still read the books. Authoritative technical books are also the must-have for every programmer.

Insert image description here

4. Introductory learning video

When we watch videos and learn, we can't just move our eyes and brain but not our hands. The more scientific learning method is to use them after understanding. At this time, hands-on projects are very suitable.

4. Practical cases

Optical theory is useless. You must learn to follow along and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

5. "Read Comics and Learn Python" produced by Tsinghua University Programming Master

Use easy-to-understand comics to teach you to learn Python, making it easier for you to remember and not boring.

Insert image description here
Supporting 600 episodes of video:

Insert image description here

6. Interview materials

We must learn Python to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and Alibaba bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.


**Learning resources have been packaged, friends who need them can comment or send me a private message

Guess you like

Origin blog.csdn.net/Python_HUHU/article/details/131010794