The most important thing is to learn the Pythonic way of writing a code. Here are a few examples:
Example 1. The ‘non-Pythonic’ way of writing a code is:
def test(a, b):
[stextbox id=”info”]a[0] = 2
b[0] = 7.5
abc = [0]
xyz = [0]
test(abc, xyz)
abc = abc[0]
xyz = xyz[0][/stextbox]
The Pythonic way of writing the same code is:
def test():
[stextbox id=”info”]
return 2, 7.5
alpha, beta = foo()
Example 2. The non-Pythonic way of writing code is:
i = 0
while i < mylistleng:
do(mylist[i])
i += 1[/stextbox]
The Pythonic way of writing the same code is:
[stextbox id=”info”]for i in range(mylistleng):
do(mylist[i])[/stextbox]
Another Pythonic way of writing the same code is:
for item in mylist:
[stextbox id=”info”]do(item)[/stextbox]
Example 3. A short program for reversing a string is shown below:
[stextbox id=”info”]‘Hello Python’[::-1][/stextbox]
This article first appeared in EFY’s Open Source For You May issue