Implementing the famous ELIZA chatbot in Python

ELIZA is a conversational agent, or “chatbot”, first implemented in 1966 by Joseph Weizenbaum. It was meant to emulate a Rogerian psychologist. Since then there have been various implementations, more or less similar to the original one. Emacs ships with ...

Private methods and attributes in Python

Unlike Java, which enforces access restrictions on methods and attributes, Python takes the view that we are all adults and should be allowed to use the code as we see fit. Nevertheless, the language provides a few facilities to indicate which methods and ...

How to write a Reddit bot in Python

Something I have seen a lot of interest in is writing bots to interact with Reddit and provide useful services to the community. In this post, I’m going to show you how to build one. Introducing BitesizeNewsBot The bot we’re going to write is called Bit ...

Multi-line strings in Python

At some point, you will want to define a multi-line string and find that the obvious solutions just don’t feel clean. In this post, I’m going to take a look at three ways of defining them and give you my recommendation. Concatenation The first way of do ...

How to obfuscate Python source code

A lot of the Python code you will come across is open source. The whole point is to distribute it freely, share knowledge and let people play around with it and learn from it. Sometimes, though, you might want to prevent the end-user from reading the c ...

Python descriptors made simple

Descriptors, introduced in Python 2.2, provide a way to add managed attributes to objects. They are not used much in everyday programming, but it’s important to learn them to understand a lot of the “magic” that happens in the standard library and third-p ...

A quick guide to nonlocal in Python 3

Python 3 introduced the nonlocal  keyword that allows you to assign to variables in an outer, but non-global, scope. An example will illustrate what I mean. Python >>> def outside():<br /> msg ...

List, Dict and Set Comprehensions By Example

One type of syntactic sugar that sets Python apart from more verbose languages is comprehensions. Comprehensions are a special notation for building up lists, dictionaries and sets from other lists, dictionaries and sets, modifying and filtering them in t ...

Python Regular Expression Basics

Regular expressions is one of those topics that confuse even advanced programmers. Many people have programmed professionally for years without getting to grips with them. Too often, people just copy and paste Regexes from StackOverflow or other websites ...

The two ways to sort a list in Python

Today I’m going to take a look at another element of the language that tends to trip up Python beginners – the difference between sorted(my_list)  and my_list.sort(). The built-in function sorted sorts the list that is passed into it, and returns a new ...