17 Tips to Improve Your Python Programming Skills

Follow + Star, learn new Python skills every day

Source: Internet

“Python is a truly wonderful language. When someone has a good idea, it takes about a minute and 5 lines of code to write something that can almost achieve what you want. Then it takes just an hour to expand the script to 300 lines, and it still almost meets your needs.” – Jack Jensen

In today’s article, I will share 17 development tips for Python.

1. Print a String N Times

While you might typically use a loop to print a string N times, I will share a Pro method to print a string N times in a single line of code.

string = "Python "ntimes = string * 3print(ntimes) # Python Python Python

2. Return Multiple Values from a Function

Sometimes we need to return multiple values from a function, and we can use the following trick to do that.

def Mulvalues():return 1, 2, 3a, b, c = Mulvalues()print(a, b, c) # 1 2 3

When you return multiple values from a function (separated by commas), Python automatically stores them in variables count, matching the number of values returned by the function.

3. Get the File Path of Imported Modules

Did you know that we can get the file path of any imported module in Python? This is a fantastic feature when you need to know the path of a module. Check out the following code example.

import osimport jsonimport tkinter#get path of imported modulesprint(os)print(tkinter)print(json)

First, you need to import the target module in your Python file, then use the print function, passing the name of the target module as an argument. Check the following output.

#OUTPUT <module 'os' from 'C:\Users\Medium\AppData\Local\Programs\Python\Python37\lib\os.py'><module 'tkinter' from 'C:\Users\Medium\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py'><module 'json' from 'C:\Users\Medium\AppData\Local\Programs\Python\Python37\lib\json\__init__.py'>

4. Quick Method to Reverse a String

I bet any of you have used a loop to reverse a string. But did you know there is a faster way to reverse a string in one line of code?

string1 = "Coder"string2 = "Algorithm"#reversing the stringsprint(string1[::-1]) # redoCprint(string2[::-1]) # mhtiroglA

5. Multiple Assignment

Many other languages like C++, Java, and JavaScript only allow a single assignment to a variable. However, Python allows you to perform multiple assignments, which is very useful in different situations.

#multiple assignmentsa, b, c = 1, 2, 3print(a) # 1print(b) # 2print(c) # 3

6. Quick Way to Remove Duplicates

You no longer need a loop to remove duplicates from a list; you can use built-in functions to do this quickly and easily. Check out the code below.

lst1 = [1, 3, 3, 4, 5, 1]lst2 = ["A", "A", "B", "C", "D", "D"]newlst1 = list(set(lst1))newlst2 = list(set(lst2))print(newlst1) #  [1, 3, 4, 5]print(newlst2) # ['C', 'D', 'A', 'B']

7. String Formatting

You typically use the ” + ” operator to format your strings. Simply put, when you want to append a variable to a string, you use the unary operator (+). But I will show you how to format this in a simple and quick way.

name = "Haider"skill = "Python"#method 1text = "My name is n and I'm a s Expert".format({"n": name, "s": skill})print(text)#method 2text = "My name is {} and I'm a {} Expert".format(name, skill)print(text)#method 3text = f"My name is {name} and I'm a {skill} Expert"print(text)

8. Understand Object Memory Usage

Did you know that the built-in Python module “sys” can tell you how much memory an object consumes in Python?

import sysval = 500print(sys.getsizeof(val))  # 28

9. Initialize Empty Containers

You can initialize empty containers in Python. In short, you can declare data structures without assigning values or filling them.

my_list = list()my_dict = dict()my_tuple = tuple()my_set = set()print(my_list) # []print(my_dict) # {}

Note: Remember that tuples and sets are immutable.

10. Reverse a List

You no longer need a reverse function to reverse any list. You can do this with a simple line of code without calling any built-in functions. Check out the following code example.

my_list1 = [1, 2, 3, 4, 5, 100]my_list2 = ["A", "B", "C"]#reversing the listprint(my_list1[::-1]) # [100, 5, 4, 3, 2, 1]print(my_list2[::-1]) # ['C', 'B', 'A']

11. Reverse a Dictionary

I will share an example code to reverse a dictionary. In short, the keys and values will swap their positions.

dict = {'x': 1, 'y': 2, 'z': 3}new_dict = {value: key for key, value in dict.items()}print(new_dict) # {1: 'x', 2: 'y', 3: 'z'}

12. Advanced Multiple Assignment

We have learned how to accomplish multiple tasks. In this tip, I will share an advanced method of demonstrating multiple assignments. Now we can also assign list values.

a, *b, c, d = 3, 4, 5, 6, 7print(a, b, c, d) # 3 [4, 5] 67

The first value is stored in variable “a”, the next 2 values are converted to a list and stored in “b” because there is an asterisk “*” on variable “b”. The last two are stored in variables “c” and “d”.

13. Quick Way to Join Strings

You might use a loop to iterate through a list and concatenate each item in the list together. But this takes many lines of code. However, you can use the join() method to do this quickly and easily.

#Bad waylst = ["I'm", "a", "Programmer"]text = ""for x in lst:    text = text + x + " "print(text)# faster waytext = " ".join(lst)print(text) # I'm a Programmer

14. Merge Two Dictionaries

I will share a simple trick to merge two dictionaries into one. Check out the following example code.

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

15. Change Recursion Limit

This tip will be very useful when you are using recursive functions and do not know that Python has set the default recursion limit to 1000. But you can change that limit.

import syscurrent_limit = sys.getrecursionlimit()print(current_limit) # 1000set_limit = sys.setrecursionlimit(5000)print(sys.getrecursionlimit()) # 5000

16. Multi-Prefix Search

You might have to use the “startswith” and “endswith” methods to search for prefixes in a string. And you always pass a single text to them for searching. Here, I will share how to pass multiple texts to search within a string.

string1 = "www.medium.com"if string1.startswith(("www", "http")):print("True")if string1.endswith(("com", "co.uk")):print("True")

17. IF Statement Tips

This tip is known to many, but if you don’t know it, then it is a rarity for you. Check out the example code below.

a = [1, 2, 3]#Way 1if a[0] == 1 or a[1] == 1 or a[2] == 1:    print("Number is present in the list")#Faster Wayif 1 in a:    print("Number is present in the list")

You can use the “in” operator to perform the same operation instead of matching the number with each item in the list. This is the most accurate and fastest way to accomplish the task.

17 Tips to Improve Your Python Programming Skills

Scan the QR code below to consult Teacher Qi Qi! Free access to Python public courses and hundreds of GB of learning materials compiled by experts, including but not limited to Python e-books, learning paths, career planning, artificial intelligence, game development, web development, automation, data scraping tutorials, interview questions, side job orders, high-paying Python employment, etc.~

If you encounter bottlenecks in learning, lack of direction, lack of practical experience, employment issues, side job issues, spending hours searching for answers on Baidu, needing half an hour to install software, not knowing how to learn English, not knowing how to localize, wanting to develop in this area, improving efficiency in data analysis, full-stack development, mini-programs, game development, script development, financial analysis, stock trading analysis, web development, junior programming, automation processing, artificial intelligence, machine learning, you can consult Teacher Qi Qi.

Recommended Reading
20 Python Code Snippets to Solve Everyday Programming Problems
10 Python Scripts to Automate Your Daily Tasks
11 Python Tips to Show Off Your Advanced Skills
10 Most Difficult Python Problems!

Click to read the original text for more information

Leave a Comment