Fun tricks with Python

Fun tricks with Python, a collection of fun tricks for Python 3. They can save you time, make programming code more easy to read and some are entertaining.

You may like:
Python Programming Bootcamp: Go from zero to hero

Starting a simple HTTP web server
A simple HTTP Server can be started in seconds.

python -m SimpleHTTPServer

For Python3:

python -m http.server

Once started you can open The browser will show you the contents of the directory.

A funny text
Try the statement below to display a poem by Tim Peters.

import this

XKCD web comic
You can open a comic on XKCD using:

import antigravity

Using Zip to combine arrays
You can zip the two arrays with:

b = [[1, 2, 3, 4], [6, 5, 4, 3]]
[(1, 6), (2, 5), (3, 4), (4, 3)]

Reverse a list
To reverse a list, you could implement a function. But why go through the trouble if it’s already implemented?

b = [1,2,3,4,5]
print b
[5, 4, 3, 2, 1]

Reverse a string
Instead of creating a method to reverse a string you can use:

s = "Hello world"
s = s[::-1]
print s
dlrow olleH

Swapping variables
You do not need to define a temporary variable to swap to variables in Python:

a = 1
b = 3
b,a = a,b
print a
print b

If you know of any tips or tricks, leave a comment. :-)

You may like:
Python Programming Bootcamp: Go from zero to hero


3 thoughts on β€œFun tricks with Python”

  1. Arishem
    - July 5, 2015

    Hello Frank!
    I wanted to know in which order should I study the tutorials in your website(I mean,after Beginner)

    1. Frank
      - July 5, 2015

      Hi, after beginner tutorials you could learn:
      Flask (web apps)
      GUI programming (pick one of the modules)

      I will create intermediate and more tutorials, stay tuned πŸ™‚

Leave a Reply

Login disabled