Python’s an interesting language. Here are five of its quirkiest aspects.

1. You can use an ‘else’ along with for loop!

Using the property that a for loop is a condition-checking mechanism as much as it is iterative, you can actually use an else to specify statements that you would like to execute when the for loop condition fails. However – remember not to use a ‘break’ statement in the for loop– otherwise the program will skip the else condition execution.

The else execution fails when a break is applied:

2. You can define infinity

Now this is something high up on the cool scale. The ‘infinity’ defined by python as <numeric_type>(‘Inf’) has all the properties of an infinity – from the fact that it’s higher than any number, to the idea that adding infinity to itself is still infinity.

Check out the following example, for how you can have the result from a divide by zero to
‘infinity’ instead of a ‘ZeroDivisionError’.

3. Slice function

To be fair, some of you already know this. But still, it’s great to know that any time you want a ‘piece’ of any collection, you just have to specify the start and end – and you apply any method or built-in function on just that section.

4. Run a quick httpserver

Let’s say that you’re writing a python script. Somewhere in between your script depends upon an HTTP server for whatever reason. In this scenario you could setup a server before running your script, or, you could quickly start a simple HTTP Server with this magic line:

 python -m http.server

This command will run an HTTP server that serves the files present in whichever directory Python is installed in, right onto your local web server (by default, port 8000).

At this point you would most likely want to server a different directory rather than the one in which Python is installed. All you need to do is run the command as follows:

 python -m http.server --directory web

5. Applying a regular expression on a string

Regular expressions are among the most powerful ways to search for some text-criteria inside another text. You can search for a large criteria of text followed by extracting a small sub-string (again, based on some criteria) from the result.

You can find and replace parts of strings using the ‘re’ (regular expression) package in Python. Without going into too much details at this point about regular expressions (which will be part of another post), the following code is a brief gist of how to use regular expressions

import re
str = "some sentence containing our payload and a lot of other words"
first_search ='containing our (.*) and', str)
containing our payload and

Leave a Reply

Your email address will not be published. Required fields are marked *