Essential Python Programming Tips and Tricks for Everyone


ProgrammingResourcesTips & Tricks

Here is a set of valuable tips and tricks for Python Programmers. We start out with some quick tricks that you might have figured out if you’ve spent some time with Python.


1. Generating Random Strings

One of the most commonly required logics for programmers is generating a random string. You may come across this mostly while trying to generate a password, so here is a code sample that works for this case in using Python.

# first we have to import random module as this
# provides the backbone for our random string
# generator and then we have to import the string
# module.

>>> import random
>>> import string

# now lets see what this string module provide us.
# I wont be going into depth because the python
# documentation provides ample information.
# so lets generate a random string with 32 characters.

>>> random = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(32)])
>>> print random
>>> print len(random)

Another way of doing the same using a function

>>> import string
>>> import random
>>> def random_generator(size=6, chars=string.ascii_uppercase + string.digits):
...    return ''.join(random.choice(chars) for x in range(size))
>>> random_generator()
>>> random_generator(3, "6793YUIO")


Want to learn Python in an Instructor-led online session? Learn Python from Live Expert.


2. Concatenating Strings

You may have to concatenate strings very frequently to output a sentence or your code result, so here is a simple code showing how to concatenate strings using ‘+’.

# See how to use '+' to concatenate strings.
>>> print('Python' + ' Programming' + ' Tips')
# Output:
Python Programming Tips


3. Using Integer Vs. Float

By default, if you divide one integer by another, the result will be truncated into an integer. For example, executing 5/2 returns 2.

There are two was to fix this. The first and simplest way is to just turn one of the integers into a float. If the values are static, you can just append a .0 to one to make it a float: 5.0/2 returns 2.5. Alternatively, you can just cast one of the values: float(5) / 2 returns 2.5.

The other way will result in cleaner code, but you must make sure none of your code is relying on this truncation. You can do a from __future__ import division to change Python to always return a float as the result of a division. After such an import, 5/2 will return 2.5. If you still need to use the truncating integer division somewhere, you can then use the // operator: 5//2 will always return 2.

5/2        # Returns 2
5.0/2      # Returns 2.5
float(5)/2 # Returns 2.5
5//2       # Returns 2

from __future__ import division
5/2        # Returns 2.5
5.0/2      # Returns 2.5
float(5)/2 # Returns 2.5
5//2       # Returns 2


4. Using Lambda Functions

Sometimes you need to pass a function as an argument, or you want to do a short but complex operation multiple times. You could define your function the normal way, or you could make a lambda function, a mini-function that returns the result of a single expression. The two definitions are completely identical:

def add(a,b): return a+b

add2 = lambda a,b: a+b


The advantage of the lambda function is that it is in itself an expression, and can be used inside another statement. Here’s an example using the map function, which calls a function on every element in a list, and returns a list of the results.

squares = map(lambda a: a*a, [1,2,3,4,5])
# squares is now [1,4,9,16,25]

Want to learn Python in an Instructor-led online session? Learn Python from Live Expert.


5. The __INIT__ Method

The __init__ method is invoked soon after the object of a class is instantiated. The method is useful to perform any initialization you plan. The __init__ method is analogous to a constructor in C++, C# or Java.

# Implementing a Python class as
class Employee(object):
def __init__(self, role, salary):
self.role = role
self.salary = salary
def is_contract_emp(self):
return self.salary <= 1250 def is_regular_emp(self): return self.salary > 1250
emp = Employee('Tester', 2000)
if emp.is_contract_emp():
print("I'm a contract employee.")
elif emp.is_regular_emp():
print("I'm a regular employee.")
print("Happy reading Python coding tips!")


6.Using Enumerate() Funciton

The enumerate() function adds a counter to an iterable object. An iterable is an object that has a __iter__ method which returns an iterator. It can accept sequential indexes starting from zero. And raises an IndexError when the indexes are no longer valid.

A typical example of the enumerate() function is to loop over a list and keep track of the index. For this, we could use a count variable. But Python gives us a nicer syntax for this using the enumerate() function.

# First prepare a list of strings
subjects = ('Python', 'Coding', 'Tips')
for i, subject in enumerate(subjects):
print(i, subject)


# Output:
0 Python
1 Coding
2 Tips


7. Returning Multiple Values Form Functions

Not many programming languages support this feature. However, functions in Python do return multiple values.

Please refer the below example to see it working.

# function returning multiple values.
def x():
return 1, 2, 3, 4
# Calling the above function.
a, b, c, d = x()
print(a, b, c, d)
#-> 1 2 3 4


8. Conditional Expressions

Python allows for conditional expressions. So instead of writing an if .. else with just one variable assignment in each branch, follow the below example.

# make number always be odd
number = count if count % 2 else count - 1
# Call a function if the object is not None.
data = data.load() if data is not None else 'Dummy'
print("Data collected is ", data)


9.Using Enums in Python

We can use the following approach to create enum definitions.

class Shapes:
Circle, Square, Triangle, Quadrangle = range(4)
#1-> 0
#2-> 1
#3-> 2
#4-> 3


10. Using Dictionary to Store a Switch

We can make a dictionary store expressions. One such example is here.

stdcalc = {
'sum': lambda x, y: x + y,
'subtract': lambda x, y: x - y
#1-> 12
#2-> 6

Want to learn Python in an Instructor-led online session? Learn Python from Live Expert.


Has something to add to the article? Share your thought in comments.



Comments are closed.