DEV Community

Cover image for Five Python features you should know!
Shreyas Daniel
Shreyas Daniel

Posted on

Five Python features you should know!

I listed down five Python features developers should use to improve their workflow.

These are not over the top complicated things, just small steps to take better advantage of Python.

These features are slightly inclined more towards beginner Python developers, I've been coding in Python for a while now but looking back, even though I was somewhat aware of these features, I didn't use them in my code, so I though I could make a list of some good ones.

If you are more comfortable to learn about this through a video, here's a youtube video I made, else continue with the blog

Now let's dive right into the list!

dive



1. Fstrings

Properly known as formatted string literals, it's arguably the best way to form strings. It has a simple syntax and is easy to keep track of.

The syntax is simple, we just have to precede a string with upper or lower-case f and the variables/expressions can be wrapped in curly braces.

one thing to notice in the below example is that the strings in the expression use double quotes instead of single quotes because this fstring example uses single quotes, keep in mind to avoid syntax errors

name = 'Shreyas'
age = 20
message = f'{name} is {age} years old'
# Shreyas is 20 years old

# we can also write expressions inside the braces

vote_status = f'{name} {"can vote" if age>=18 else "cannot vote"}'
# Shreyas can vote
Enter fullscreen mode Exit fullscreen mode

2. Unpacking

If you know Python, you must surely be aware of how we can unpack the contents of an iterable as individual variables like this:

a,b,c = (1,2,3)
# a = 1
# b = 2
# c = 3
Enter fullscreen mode Exit fullscreen mode

Along with this, we can take advantage of asterisk * also known as the unpacking/packing operator. It packs multiple values to a single variable and forms a iterable which we can use to our liking. For example:

random_values = [True, 17, 'dev_to', 84.3943, f'{12*3}', -35]
a,b,*c,d = random_values
# a = True
# b = 17
# c = ['dev_to', 84.3943, f'{12*3}']
# d = -35
Enter fullscreen mode Exit fullscreen mode

Another proper example use for this is as *args in a function, if uncertain about the number of parameters to be passed, using *args, all the parameters are packed into a tuple.

def product(*numbers):
    result = 1
    for n in numbers:
        result *= n
    return result

product(1,2,3)
# 6
product (12,334,31,353,3)
# 131578632
Enter fullscreen mode Exit fullscreen mode

3. Argparse

For Python developers who write a lot of scripts, passing in parameters from the shell instead of input() saves a lot of time and is intuitive.

After importing argparse, we define the parser object, here can also pass in a simple description for the script along with a name.

Then we add arguments to it, argument names are preceded by one or more dashes and we can have alternative names for a single argument, we call the parse_args() which returns a namespace object.
We can then just access the values using argument names as shown below:

# example.py
import argparse

parser = argparse.ArgumentParser(description='simple script info')
parser.add_argument('--num','-n', default=20)
args = parser.parse_args()
print(args.num)
Enter fullscreen mode Exit fullscreen mode

In shell:

python example.py --num 5
5
python example.py 
20
Enter fullscreen mode Exit fullscreen mode

4. Interactive Mode

If you've used Python at least once, you must already familiar with how you can start the interpreter from the shell, just by typing python

Python 
>>> print('hello')
hello
>>> 
Enter fullscreen mode Exit fullscreen mode

Mostly developers write code in an editor and run it on shell, but what if I told you that you can combine the best of both methods?

Here's a simple file:

# example.py

unit_price = 10
stock = 200

def get_stock():
  return stock

def purchase_units(quantity):
  global stock
  if stock-quantity > 0:
    stock -= quantity
    return quantity*unit_price

  return -1


get_stock()
Enter fullscreen mode Exit fullscreen mode

Now, instead of running python example.py add -i flag before the name, it will run the script once first, but the interpreter will still be active, now you can call functions of that script, get values of variables, etc.
This is a quick and useful way to test or debug your code.

python -i example.py
200
>>> unit_price
10
>>> purchase_units(5)
50
>>> stock
195
>>>
Enter fullscreen mode Exit fullscreen mode

5. Enumerate

In the traditional way, to iterate over a list, you'll use for index in range(0,len(example_list)): which is fine, but enumerate does it better.

If we wrap the iterable in enumerate() for each iteration, enumerate returns a tuple, the first element a counter/index and the second element in the item of that iterable. We can unpack the tuple in the for loop and use as we wish.

If we don't like the counter to start at 0, we can change that as well.

example_list = [4,30,38,7,48]

for counter, element in enumerate(example_list):
  print(counter, element)

# 0 4
# 1 30
# 2 38
# 3 7
# 4 48

for counter, element in enumerate(['a','b','c'], start=97)
    print(counter, element)

# 97 a
# 98 b
# 99 c
Enter fullscreen mode Exit fullscreen mode

So these were the five features you can use, pretty easy to grasp, straightforward and quite useful.

Thank you for taking the time to read this! 😊️

Find me on Twitter

Top comments (0)