Fun tricks with Python


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 http://127.0.0.1:8000/. 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]]
zip(*b)
[(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]
b.reverse()
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
1

If you know of any tips or tricks, leave a comment. 🙂


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)
      Databases

      I will create intermediate and more tutorials, stay tuned 🙂