Top 10 Python Codes And Tricks For Programmers

Python is one of the most preferred , an interpreted, high-level and general-purpose programming language. Its brevity and high readability makes it so popular among all programmers.
So here Top 10 Python Codes And Tricks For Programmers , you can use to bring up your Python programming .

1. Reversing a string using Python : ( There is no built-in function to reverse a String in Python , but to reverse a sting the fastest way is to use a slice that steps backwards, -1 ) As :


str = "Digitechbits"
print("Output is", str[::-1])

Output :

 Output is stibhcetigiD

2. In-Place Swapping Of Two Numbers : Using a temporary variable / Without using a temporary variable

Without Using a temporary variable :

x, y = 30, 40
print(x, y) 
x, y = y, x 
print(x, y)

Using a temporary variable :


x = 30
y = 40

# create a temporary variable and swap the values

temp = x
x = y
y = temp

print('x after swapping: {}'.format(x))
print('y after swapping: {}'.format(y))

3. Create a single string from all the elements in list :

a = ["digi", "tech", "bits"] 
print(" ".join(a))

Output :

digi tech bits

4. Comparison Operators in python.

n = 12
result = 1 < n < 205
print(result) 
result = 1 > n <= 9
print(result)

Output :

True
False

5. How to Print The File Path Of Imported Modules

import os 
import socket 
  
print(os) 
print(socket)


6. Use Of Enums In Python.

class MyName: 
    digi, tech, bits = range(3) 

print(MyName.digi) 
print(MyName.tech) 
print(MyName.bits) 

Output:

2
1
2

7. Return Multiple Values From Functions.

def x(): 
    return 1, 2, 3, 4
a, b, c, d = x() 

print(a, b, c, d) 

Output:

1 2 3 4

8. Find The Most Frequent Value In A List.

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] 
print(max(set(test), key = test.count)) 

Output:

4

9. Check The Memory Usage Of An Object.

import sys 
x = 1
print(sys.getsizeof(x)) 

Output:

28

10. Print string N times.

n = 2
a = "Digitechbits"
print(a * n) 

Output:

DigitechbitsDigitechbits

Top 10 Python Codes And Tricks For Programmers

Leave a Reply

Your email address will not be published.