10 essential tips for programming in Python
- Tram Ho
Python is one of the most popular and loved languages today. Python’s brevity and receptivity make it popular among all programmers. Here are some tips and tricks you can use in your Python programming.
1. Swap in place of two numbers
1 2 3 4 5 | >>> x, y = 50, 100 >>> print(x, y) >>> x, y = y, x >>> print(x, y) |
Output
1 2 3 | 50 100 100 50 |
2. Reverse a string
1 2 3 | >>> name = "Eminem" >>> print(name[::-1], "is the best rapper of all time") |
Output
1 2 | menimE is the best rapper of all time |
3. Create a string from all the elements in the list
1 2 3 | >>> list = ["My", "name", "is", "NoName"] >>> print(" ".join(list)) |
Output
1 2 | My name is NoName |
4. Incorporating comparative conditions
1 2 3 4 5 6 | >>> number = 22 >>> result = 8 < number < 94 >>> print(result) >>> result = 16 > number <= 21 >>> print(result) |
Output
1 2 3 | True False |
5. Using Enums in Python
1 2 3 4 5 6 7 | >>> class Number: >>> One, Two, One = range(3) >>> >>> print(Number.One) >>> print(Number.Two) >>> print(Number.One) |
Output
1 2 3 4 | 2 1 2 |
6. Return multiple values from functions
1 2 3 4 5 6 | >>> def x(): >>> return 1, 2, 3, 4 >>> a, b, c, d = x() >>> >>> print(a, b, c, d) |
Output
1 2 | 1 2 3 4 |
7. Find the value that appears most in the list
1 2 3 | >>> arr = [1, 2, 3, 4, 5, 1, 2, 1, 1] >>> print(max(set(arr), key = arr.count)) |
Output
1 2 | 1 |
8. Check the memory usage of an object
1 2 3 4 | >>> import sys >>> x = 1 >>> print(sys.getsizeof(x)) |
Output
1 2 | 28 |
9. Print string N times
1 2 3 4 | >>> n = 3 >>> vn = "VietNamVoDich! " >>> print(vn * n) |
Output
1 2 | VietNamVoDich! VietNamVoDich! VietNamVoDich! |
10. Check if two words are inversions
1 2 3 4 5 6 7 8 9 10 11 12 | >>> # Cach 1 >>> from collections import Counter >>> def is_anagram(str1, str2): >>> return Counter(str1) == Counter(str2) >>> # Cach 2 >>> def is_anagram(str1, str2): >>> return sorted(str1) == sorted(str2) >>> >>> print(is_anagram('yeuthuong', 'thuongyeu')) >>> print(is_anagram('yeuthuong', 'thuongyek')) |
Output
1 2 | True False |