1. Hangman in more than three lines of Python

    Recently, Danver wrote about a brilliant implementation of the Hangman game in just three lines of Python. But the shortened code might be hard to understand. In this post we will rewrite his code in a more idiomatic Python 3 style.

    Spoiler Alert: If you prefer a fun exercise, try doing it yourself first and then compare with my version.

    Danver’s implementation cleverly uses the system dictionary (pre-installed in Linux and Mac, but we’ll see how it can work in Windows too) for picking a random word. It also displays a neat ASCII-art hangman at every step. Except for a few minor improvements, I have tried to retain the essence of Danver’s original in my rewrite below.

    # -*- coding: utf-8 -*-
    """A simple text-based game of hangman
    A re-implementation of Hangman 3-liner in more idiomatic Python 3
    Original: http://danverbraganza.com/writings/hangman-in-3-lines-of-python
      A dictionary file at /usr/share/dict/words
      $ python hangman.py
    Released under the MIT License. (Re)written by Arun Ravindran http://arunrocks.com
    import random
    DICT = '/usr/share/dict/words'
    chosen_word = random.choice(open(DICT).readlines()).upper().strip()
    guesses = set()
    scaffold = """
    |   |
    | {3} {0} {5}
    |  {2}{1}{4}
    |  {6} {7}
    |  {8} {9}
    man ...
    Continue Reading →
  2. Python 3 Cheatsheet for Djangonauts

    If you are already convinced to use Python 3 then you can directly jump to the section “Python 2 vs Python 3” for the cheatsheet

    There is an intense debate whenever Python 3 is mentioned. Some think it is an unnecessary shift and Python 2 series should be continued. However, I chose Python 3 for my book because I strongly believe that it is the future of the language. Besides, the divide might not be as large you think.

    Why Python 3?

    Think of your favourite programming language and what you love about it. Now think of things that you don’t like about it or wish was improved. Sometimes these improvements might break older codebases but you badly want them.

    Now imagine if the creator of the language takes upon himself/herself to revamp the language and rid of its warts. This is what actually led to Python 3 - Guido led the efforts to clean-up some fundamental design flaws with the 2.x series based on over fifteen years of experience developing a successful language.

    While the development of Python 3 started in 2006, its first release, Python 3.0, was on December 3, 2008. The main reasons for ...

    Continue Reading →
  3. Python One-liner Games

    I took a break from the intense book schedule this weekend (don’t worry everything is on schedule). Was reading about Commodore’s one-liner maze when it struck me.

    I wondered - why not make some one-liner games in Python? And just to make it insanely hard, I would try to make it fit a tweet i.e. 140 characters. Let’s see what we could manage.

    NOTE: All the one-liners below work only in Python 3. Depending on your platform, you might want to change the code by replacing python with python3.


    Game recording

    python -c "while 1:import random;print(random.choice('|| __'), end='')"

    Create an infinite maze with this deceptively short one-liner. It is quite easy to understand too. The while loop is infinite. The import statement had to move inside the loop but Python takes care not to re-import it each time.

    A random character is picked from one of the maze drawing characters and printed. An alternate version below has better maze drawing characters. But this version used characters which were displayable on the Windows shell (and possibly portable to other operating systems).

    Prettier Version

    python -c "while 1:import random;print(random.choice('╱╲'), end='')"

    This version ...

    Continue Reading →
  4. Edge v2.0 - More Edgy Ideas

    Edge v2.0 has just been announced. Since the first release, there have been numerous feature requests and pull requests. I am happy to share that we have been able to incorporate most of the planned features and fixes, including:

    • Email-based logins!: Most websites don’t need usernames. Furthermore, the users have to come up with a unique and memorable username. But their email address is already unique and memorable, hence more widely used for logins these days.

    • User profiles!: In 90% of the user based applications you will need to create a user profile. So we have added one with nice default fields like a user avatar image, bio etc. They are extendable too.

    • Python 2.7 support!: Supporting Python 2.7 was a much requested change. Back-porting needed not just syntactic changes but some tricky Unicode management as well.

    • Less Bootstrappish: After browsing through several examples of well designed bootstrap-based sites, several design improvements have been added like see-through navbar that changes on scroll, full cover image etc.

    • Environment specific Settings and Requirements files: This was a convention most Django developers follow so the environment specific files have been split out.

    • Authentication Workflows: In addition to signup, login ...

    Continue Reading →
  5. Django Design Patterns and Best Practices Book - Coming Soon

    Here is the big news I hinted at in my last Pycon talk. I have been working on a book titled “Django Design Patterns and Best Practices”. Most of the early drafts have been reviewed and it is slated for publishing in March.

    You can pre-order it here right now! Click here if you like to be notified when it will be published.

    Some of the highlights of this book:

    • Guides advanced beginners to web application fundamentals and patterns
    • Updated for Django 1.7 (upcoming 1.8 features also mentioned)
    • Covers the creation of a fun project - a social network for superheroes
    • Uses engaging story elements to illustrate real world challenges
    • A short read at less than 200 pages

    Why Patterns?

    Most Python programmers I know, rarely use a Gang of Four pattern like the Strategy Pattern or the Iterator Pattern. It makes sense, too. After all, they were designed for object-oriented programming languages like C++ and Smalltalk, while Python has better higher-order abstractions. Many of these patterns are not even required in Python.

    But while working in Django, we come across patterns at a higher level of abstraction. They could be anything from implementing models to store user profile ...

    Continue Reading →
  6. Introducing Edge - a Modern Django Project Template

    A newer version has been announced

    Have you ever begun creating a web app only to abandon it while setting it up? I have done it more times than I would have liked.

    Many programming environments involve so much ritual to setup that we tend to forget what we set out to create. Recently, I had to setup an Android development environment from scratch. Despite downloading the latest version of the IDE, I waited until several additional updates downloaded to patch it to the latest version. The trend of packages getting more granular and updates being made several times a day is here to stay.

    It is like if you have an idea for a painting then you have to go shopping for all the art-supplies first. But the moment you step out, you have lost your muse. Scientists call this encoding specificity or as a famous paper calls it “Walking through doorways causes forgetting.”

    Django Projects

    Of course, in Django I use startproject which builds an excellent but minimal project structure. But once I start coding I inevitably tend to install packages like the django braces. Most of my project use Bootstrap, so I end up downloading the bootstrap ...

    Continue Reading →
  7. Recreating the “Building a Blog in Django” Screencast

    Few days back, Django 1.7 release candidate 1 was announced. I have never been so excited about a release in recent memory. It has a new app loading framework and schema migrations baked right in!

    It is also the significant release that I had been waiting for to update my original Django screencast. With more than 77 thousand views, it is by far the most popular Django screencast on YouTube.

    Back in 2012, when I was working in Django, there were a lot of comparisons between Rails and Django. One of the biggest selling points of Ruby on Rails was their official 15-minute blog screencast. It was fascinating to watch an expert Rails developer build an entire site from scratch especially how deftly they use TextMate, which could nearly read his mind.

    Armed with a Linux terminal and Emacs, I set out to create a similar screencast for anyone interested in Django. Live coding was something that I had not tried before. I remember starting at 11 pm one night, hoping to complete my recording by midnight.

    But by the time I finished a recording without any major goofups it was 5 am in the morning. So with barely ...

    Continue Reading →
  8. Understanding Test Driven Development with Django

    Test-driven Development (TDD) has been getting a lot of attention these days. While I understand the importance of testing, I was sceptical of Test-Driven Development for a long time. I mean, why not Development-Driven Testing or Develop Then Test Later? I thought figuring out the tests before one can write even a single line of code would be impossible.

    I was so wrong.

    Test-driven Development will help you immensely in the long run. We will soon see how. We will approach TDD from a sceptical viewpoint and then try to create a simple URL shortener like bit.ly using TDD. I will conclude with my evaluation of the pros and cons of the technique; to which you may directly jump to as well.

    What is TDD?

    Test-driven development (TDD) is a form of software development where you first write the test, run the test (which will fail first) and then write the minimum code needed to make the test pass. We will elaborate on these steps in detail later but essentially this is the process that gets repeated.

    This might sound counter-intuitive. Why do we need to write tests when we know that we have not written any code and ...

    Continue Reading →
  9. An Easy Guide to Install Python or Pip on Windows

    I enjoy studying other people’s development environments. They give me plenty of insights into their aesthetic choices and their productivity shortcuts. But I have seen a lot of horrible environments cobbled together by flaky batch files that are one update away from blowing up, often leaving no option but to reinstall everything from scratch. Unfortunately, they have all been Windows environments.

    Recently, I tried to install Python and pip on a Windows laptop. Though I have installed Python on Windows XP and Windows Servers for several years till 2010; there have been a lot of changes both in the Windows world such as Powershell and the Python world. So there is a lot of confusing information out there for the Python beginner. And then there is Python 3. Sigh!

    Suffice to say I wanted to share what I learnt in a video aimed at the Python beginner or anyone struggling to install Python on Windows. The video and the high-level transcript follows:

    What is covered?

    • Installing Python 2 or Python 3 on Windows 7
    • Installing pip from PowerShell
    • Setting up a virtualenv
    • Installing via pip


    How to install Python / Pip on Windows 7 (or 8)

    1. Download the MSI installer ...

    Continue Reading →
  10. Binary Clock - Django Nibbles

    Django can be used to build great websites. But it is also really good for solving small problems quickly. Introducing a new series called “Django Nibbles”, to help you learn an aspect of Django say Templates through a short and simple problem. You can either solve the problem yourself or follow my step-by-step solution.

    Q. Create a page that displays a binary clock showing the current time (when the page was loaded).

    For instance, if the time is “23:55:02” then we should see:


    Each column represents a binary digit when read from top to bottom. For more details, read the Binary Clock wiki page.

    Django Feature: Views

    Time Given: 1 Hour

    Go ahead. Try it yourself before reading further!

    A. We will be using Python 3 (not 2.7) and Django 1.6 for solving this. Both are the latest versions at the time of writing.

    Setting up the project

    This section can be skipped if you know the basics of setting up a project in Django (which is simpler in Django 1.6)

    On Linux command-line (indicated by the ‘$’ prompt), enter the following to create the binclock project:

    $ cd ~/projects
    $ django-admin.py startproject binclock
    $ cd binclock

    Getting ...

    Continue Reading →

Page 1 / 17 »