Twelve Python Tips for Beginners

0
853

In a previous article published in the March 2021 edition of Open Source For You (‘Python: A Few Useful Tips for Beginners’), the author of this article had written some simple but useful tips for those beginning to learn the Python language. He has now compiled twelve more tips that are interesting and useful for Python programmers. These tips will help write concise and easy-to-read code.

As per both the TIOBE index and the PYPL (PopularitY of Programming Language) site, as on September 2022, Python is the most popular programming language and has retained its popularity for almost three years now. This is because of its ease of programming and the availability of a very large number of libraries covering a large number of areas, right from business and finance to scientific computing and AI. It is also easy to learn compared to other languages like C/C++ and Java.

So let’s begin with the Python tips that will help you write concise code easily.

Use of underscore to separate digits of long numbers

It is difficult to count the number of digits if a number, be it an integer or floating-point number, is very long. Python allows the use of underscores (_) as visual separators for grouping digits to make it easier to read the number. Hence, the number 1000000000 can be written as 1_000_000_000.

>>> num = 1_000_000_000
>>> num
1000000000

List unpacking and partial assignment

If we need to assign some of the elements of a list to particular variables and the remaining values to some other variable, the ‘*’ notation for unpacking can be used in Python.

>>> numlist1 = [ 1,2,3,4,5 ]
>>> num1, *numlist2 =  numlist1
>>> print ( "num1 = ", num1 )
num1 = 1
>>> print ( " numlist2 = ", numlist2 )
numlist2 = [ 2,3,4,5 ]

Unpacking is used in the assignment statement below to assign values from the list to three variables simultaneously, and the ‘*’ is used to assign all the remaining values.

>>> numlist1 = [ 1,2,3,4,5 ]
>>> num1, *numlist2, num3 =  numlist1
>>> print ("num1 = ", num1)
num1 =  1
>>> print ( "numlist2 = ", numlist2 )
numlist2 =  [ 2, 3, 4 ]
>>> print ( "num3 = ", num3 )
num3 =  5

Use of underscore in unpacking

The underscore (_) can also be used to ignore specific values while unpacking. The value that has to be ignored is assigned to underscore (_).

>>> num1, _, num2 = [ 1,2,3 ]
>>> print ( num1 )
1
>>> print ( num2 )
3

The ‘*’ symbol is used as a prefix to underscore (_) to unpack multiple values and assign them to a list.

>>> num1, *_, numlist2 = [ 1,2,3,4,5,6 ]
>>> print ( num1 )
1
>>> print ( numlist2 )
6

Getting a password from a user

An easy way to get a password as input from the user is to use the getpass function defined in the getpass module. The function displays a prompt and then prevents echo on the display when the user types the password.

!pip install getpass

from getpass import getpass
uname = input ( “Username: “ )
password = getpass ( “ Password: “ )

List comprehension

List comprehension offers an easy way to create a new list in a single line, compared to the traditional methods. An example is given below. If we want to create a new list using the for loop, the code will be as follows:

#create a list containing the cube of the first 9 integers
>>> cubelist = [ ]
>>> for i in range ( 1,10 ):
>>>     cubelist.append ( i * i  * I )
>>> print ( cubelist )
[ 1, 8, 27, 64, 125, 216, 343, 512, 729 ]

The same can be written using list comprehension in the following way in a single line of code:

>>> cubelist = [ i * i * i for i in range (1,10) ]
>>> print ( cubelist )

You can even use it for conditional logic and filtering.

>>> numlist1 = [ 35, 49, 45, 75, 90, 15, 65, 63, 84, 54 ]
>>> #create a new list whose elements are divisible by 7
>>> numlist2 = [ i for i in numlist1 if i % 7 == 0 ]
>>> print ( numlist2 )
[ 35, 49, 63, 84 ]

Zip() function

The zip() function is an inbuilt function in Python that takes two or more iterable contents passed as arguments like list, dictionary, string or even iterables that are user defined, and combines them to create a single tuple, an iterator object. The zip function combines the elements with the same index in pairs (or more if the number of iterators is more) in a tuple. The first item of each argument iterator is combined, then the second is combined, and so on, until the length of the shorter iterable is covered, by default, to create a tuple object. Given below is a simple example:

>>> names = [ "Ganesh","Siva Sundar","Gunasekhar","Santosh" ]
>>> marks = [ 90, 88, 75, 72 ]
>>> marklist = tuple ( zip ( names, marks ) )
>>> print ( marklist )
(('Ganesh', 90), ('Siva Sundar', 88), ('Gunasekhar', 75), ('Santosh', 72))

The zip function is extremely powerful as it can take iterators like strings and dictionaries as arguments. It can also take more than two iterables as arguments, and the iterables can be of varying lengths. It even gives options for iterating all the elements of the longer tuple if the iterable arguments are not of the same length.

Combining two lists into a dictionary

We can combine two lists and create a dictionary by using the zip function.

>>> names = [ "Ganesh", "Siva Sundar", "Gunasekhar", "Santosh" ]
>>> marks = [ 90, 88, 75, 72 ]
>>> marklist = dict ( zip ( names, marks ) )
>>> print ( marklist )
{'Ganesh': 90, 'Siva Sundar': 88, 'Gunasekhar': 75, 'Santosh': 72}

The pass keyword

The pass keyword can be used as a placeholder for incomplete code. This keyword is a statement by itself and results in NOP (no operations) as it is discarded during the byte-compile phase and nothing is executed. It is useful for code that you want to add later. Two examples are given below.

Example 1:

def passDemo ():
  pass
  return
passDemo ()

Example 2:

marks = 80
if marks >= 75:
   pass

Counter function in collections module

The collections module of Python has different types of containers. Counter, one of the containers in the collections module, is a dict subclass that provides an efficient way to count objects. The keys component of the dictionary stores the object, whose occurrence has to be counted, and the values component of the dictionary holds the object’s count, that is, its frequency. Counter takes an iterable list as an argument and returns a dict object containing each distinct item in the iterable list and its frequency as a key-value pair. For example:

>>> from collections import Counter
>>> alphabets = [ 'a', 'b', 'c', 'd', 'b', 'a', 'b', 'c', 'a', 'b', 'c' ]
>>> num_alphabets = Counter ( alphabets )
>>> print ( num_alphabets )
Counter({'b': 4, 'a': 3, 'c': 3, 'd': 1})

Notice that the key-value pairs are ordered as per the descending order of the count of the occurrences in the iterable. The Counter can also be used to merge two dictionaries. The keys are preserved and the values of matching keys are added. For example:

>>> from collections import Counter
>>> marks1 = { 'Ganesh': 90, 'Siva Sundar': 88, 'Gunasekhar': 75, 'Santosh': 72 }
>>> marks2 = { 'Ganesh': 90, 'Siva Sundar': 88, 'Gunasekhar': 75, 'Santosh': 72, 'Shashank':78 }
>>> finalmarks = Counter( marks1 ) + Counter ( marks2 )
>>> print ( finalmarks )
Counter({'Ganesh': 180, 'Siva Sundar': 176, 'Gunasekhar': 150, 'Santosh': 144, 'Shashank': 78})

Expression evaluation using the eval function

The built-in eval function accepts a string as an argument. If the string is an expression, then the expression is evaluated. This is useful for evaluating any Python expression that comes as an input dynamically. For example:

>>> x = 7
>>> y= 45
>>> eval('x * y')
315

>>> eval ('2 ** 8')
256

>>> z = eval('x * y + 4')
>>> print (z)
319

Factorial

Factorial of a non-negative integer ‘n’ is the product of all positive integers less than or equal to ‘n’, but greater than or equal to 1. The math module of Python has a function named factorial to compute the factorial of an integer passed as an argument to the function.

>>> import math
>>> num = 9
>>> fact = math.factorial ( num )
>>> print ( fact )
362880

Playing sound notifications in Python

If you need to notify the user of the sound of some event, you can use the chime module to generate the standard sounds.

import chime
chime.info ()
chime.success ()
chime.error ()
chime.warning ()

The above tips will help programmers code faster, create more efficient and concise code, and will increase their productivity. The use of powerful features like zip, Counter and list comprehension makes the code concise and easy to understand. Happy Pythoning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here