Date:

Share:

10 Python Tips & Tricks that no One Teaches

Related Articles

Python is the most popular programming language in the world, which is why Python programmers enjoy working with it.

It has simple syntax, numerous libraries and a short learning curve have made it popular with both new and old developers.

So today I will share 10 of the best Python tricks that are not usually learned.

Change the way pandas display numbers

If you want to change the way numbers are displayed within DataFrames, use these useful options to round decimal numbers.

pd.set_option(‘precision’, 2) # Round to two decimal points

This second option also provides the functionality of comma separators between three digits of larger numbers:

pd.options.display.float_format = ‘:,.2f’.format 

Select a random element from a sequence

The standard library’s random package offers a variety of useful functions. However, random.choice (seq) is extremely useful.

This allows you to select a random element from an indexable sequence, for example, lists, tuples, or even strings

import random as r
my_list = [1, 2, 3, "go"]
print(r.choice(my_list))

# Random item
A practical example

A book selector function that receives a sequence of books receives a random selection, removes the item from the list and returns the selection as a string

# We import only the function we need
from random import choice

def book_picker(books):
    book_choice = choice(books)
    books.remove(book_choice)    
    return f"You picked book_choice"

books = ["Harry potter", "Don Quixote", "Learn Python by Daniel Diaz", "Dracula"]

print(book_picker(books)) # Random choice
print(books) # Remaining books

Limitations and Exceptions

If you try to use random.choice(seq) In a non-indexable sequence, for example, dictionaries, sets, And numeric types, Python will cost an error.

# With Dictionary
import random as r
scores = "Jhon": 4, "Ben": 3, "Diana": 5

print(r.choice(my_scores)) # Key error

Also, if the Python blank sequence goes up an IndexError.

# With an empty sequence
import random as r
empty_list = []

print(r.choice(empty_list)) # Index error

Unloading elements with *

The most common technique I have seen for printing the elements of iterables separated by a space is

my_list = [1, 2, 3, 5, 7]

for i in my_list:
   print(i, end=" ") # 1 2 3 5 7 

Although it solves the problem, the code is not it Pythons. There is a simpler solution using the unloading operator “*”

my_list = [1, 2, 3, 5, 7]

print(*mylist) # 1 2 3 5 7 

As you can see, the unpack operator is always set on the left side of Iternes, and he says to the python:

Assign each component of this return to the patient or desired list

Any sequence we can repeat using a for loop is a repeatable sequence. Use the iter () function to determine if a data type can be repeated.

print(iter("This is a string")) # Str Iterable object
print(iter(["this", "is", "a", "list"])) # List iterable object
print(iter(1))
# Raises an error
# Integers can't be iterated

View the properties and methods of a class without leaving the editor

God dir() The function returns the attributes and methods of a class. We can use this useful trick to list all the settings within a class type.

-> $ python 
string = "A string"

print(dir(string))

# ['__add__', .....,'upper', 'zfill']

For example, if we needed a string method to convert a string to uppercase but did not want to open the browser, we could use the dir function with a string as input to find the appropriate method.

Call the debugger in 10 letters

The function breakpoint Available from python 3.6+. This will be called a session of pdb.set_trace().

It may sound like pure comfort (and maybe it is) but for me it’s a really short and elegant way to call a debugger

Example
n_odds = 0

for i in range(1, 14, 2):
    # Check for the value of i in each iteration
    breakpoint()
    # Bad condition
    if i % 2 == 0:
        n_odds += 1

print(n_odds)

Check the size of the packages

Your SSD may be loaded after the pip has installed all the libraries required to run your theme park. You can figure out which packages take up the most space by looking at the size of the packages installed. From here, you can decide which packages “sparked joy” and move on Conmaric Process accordingly.

To find the path to the packages installed on your Linux computer, type:

pip3 show "some_package" | grep "Location:"

This will return a path / to / all / packages. Something like: /Users/yourname/opt/anaconda3/lib/python3.7/site-packages

Enter the file path for the command below:

du  -h  path/to/all/packages

where du Reports disk space usage in the file system.

This code will take out the size of each package. The final output line will contain the size of all the packages.

Promote your command-line tool

knock Is a command-line tool for Python that allows you to create intuitive programs and interfaces for the bash shell. Click supports dialogs of options, user guidelines, approval requests, values ​​from environment variables and more.

The following is a sample script that can be used to request a password from a trip operator:

@click.command()
@click.option('--password', prompt=True, hide_input=True,
              confirmation_prompt=True)
def encrypt(password):
    click.echo('Encrypting password to %s' % password.encode('rot13'))

Will issue:

$ encrypt
Password: 
Repeat for confirmation:

Summary

In this tutorial you learned:

  • To select a random element from a sequence
  • Unload elements with them * sets off
  • The ability of sets to delete duplicates efficiently
  • How to search for methods and variables without leaving the code editor
  • The diverse uses of python slices
  • How to call a debugger with the function breakpoint

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles