4 Simple Tips From Python’s Inventor to Improve Your Code | by Murtaza Ali | Aug, 2022


Take advantage of easy-to-implement lessons from one of the language’s most knowledgeable experts

Photo by Campaign Creators on Unsplash

You may not know it, but a Python installation comes with a wonderful and helpful poem, free of charge. To access it, all you need do is type import this into the terminal. You’ll then be greeted with the following:

“The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one — and preferably only one — obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!”

The author of this poem is Tim Peters, a famous software engineer and one of the chief contributors to the development of the Python programming language. Although it’s meant to be a language quirk that is both fun and humorous, the poem also has some damn good advice.

Let’s take a look at what we can learn.

Please make your code easy to read

Readability counts.

The following is a completely valid block of code in Python; it accomplishes its goal and runs without any errors:

x =   'All Too Well'
if x == 'All Too Well': print("Taylor Swift rocks")
else:
print("You need to re-evaluate your life choices.")

Turns out as long as you’re consistent with spaces and tabs, Python’s interpreter doesn’t really care how widely or evenly you space out your code.

But you know who does care? Three very important people, all of whom will hate you if you choose to write code that isn’t styled properly:

  1. Your teachers/mentors: These people have to either grade or review your code, and they won’t be thrilled about having to stare an extra several minutes just to figure out where to start.
  2. Your coworkers: They need to build off your code. If you needlessly make their lives harder at an already stressful (although rewarding) job, they will not be fond of you.
  3. Your future self: You may well find yourself pulling your own code out a few days in the future to start working on it again. At that point, you’ll really hate your past self for writing a jumbled mess instead of clear, clean, and maintainable code.

A life where this many people hate you is not a fun life, so it’s really in your better interest to write code that conforms to Python’s detailed and well-written style guide [1]. Make sure your indentations match up and your variable names are reasonable — and also add some well-placed comments to guide the reader:

my_favorite_song =   'All Too Well'# This block of code ensures the my_favorite_song variable has
# the correct value.
if my_favorite_song == 'All Too Well':
print("Taylor Swift rocks")
else:
print("You need to re-evaluate your life choices.")

Your mentors, your coworkers, and your future self will thank you.

And while you’re at it, make it pretty

Beautiful is better than ugly.

There is an important question that needs to be answered here: what is beautiful code?

It depends on the context. Python is a language designed for readability and simplicity, and so it stands to reason that the simplest code (which is still easy to understand) is also the most beautiful and elegant.

There are many relevant examples, but one of my favorites is a redundant construct common among new programmers. It involves returning True or False depending on the value of the variable one is interested in. Consider the following:

# This code returns whether or not my code is beautifuldef my_function(is_code_beautiful):
if is_code_beautiful == True:
return True
else:
return False

In principle, there is nothing wrong with this code. In fact, for newer coders, it’s arguably an effective teaching tool, as it provides way to think about what a conditional statement is actually meant to do.

However, it can be written in a much simpler (and thus more beautiful) way. Since the variable itself is already a Boolean (True or False) value, we can achieve the same effect with the following code:

# This code returns whether or not my code is beautifuldef my_function(is_code_beautiful):
return is_code_beautiful

Simple. Elegant. Pythonic.

Beautiful.

Isn’t complex the same as complicated?

No.

Complex is better than complicated.

Many people use the words complex and complicated interchangeably, so let’s start by talking about the difference between the two. They might have similar connotations colloquially, but are not the same in a programming context.

Complex code may be hard to understand, but usually out of necessity because the underlying algorithm itself is sophisticated (and no one has written simpler code that you can use rather than coding the algorithm from scratch). Complicated code is needlessly convoluted, in particular because there is a simpler way to achieve the same solution.

Let’s look at an example. Say we have the following deeply nested list:

data = [[[0, 255, 255], [45, 0, 0]], [[0, 0, 0], [100, 100, 100]]]

As a quick aside, you might think that a list nested this deeply serves no practical purposes, but this is in fact how images are stored in Python — as rows of pixels, where each pixel is a 3-element list consisting of red, green, and blue (RGB) values.

For a project in the course I am currently a TA for, students had to program an operation where they flipped a photo horizontally by reversing the order of pixels in all the rows.

While I was prepping for the project this is the solution I initially came up with:

for row in data:
for i in range(len(row) // 2):
temp = row[i]
row[i] = row[len(row) - 1 - i]
row[len(row) - 1 - i] = temp

At first, I thought this was a pretty nifty solution to reversing a list. That is, until my professor pointed out that I could just do the following:

for row in new_pixel_data:
row.reverse()

The difference is astounding.

One could argue that the second solution is still complex in principle, since reversing a list is a fairly involved task. However, it is exceedingly clear that in comparison to my first manual solution, it is far less complicated and thus much easier to understand.

Note that whether or not your code is complicated largely depends on the context. In the example above, my initial code is complicated because there exists much cleaner code which achieves the same goal. If a simple way to reverse Python lists didn’t exist, then my code would be fine (if still complex) simply by virtue of being the best available option.

A good rule of thumb: before you code something super involved, check if someone’s already done some work to make your life easier.

Check for errors!

Errors should never pass silently.
Unless explicitly silenced.

Interestingly enough, this is a topic often overlooked in introductory programming classes. My own first programming course only briefly touched on catching errors, never explicitly teaching how to do it. It’s an important skill, primarily because it enables your program to give the user more detail in the event of an error (or even keep the program running smoothly).

The simplest way to handle errors in Python is through a try-except block. You write your code as you normally do within the try, and if there is an error, the code starts running the except block:

>>> try:
... print(x)
... except:
... print("You never defined your variable.")
...
You never defined your variable.

You can also catch specific errors:

>>> try:
... 1/0
... except ZeroDivisionError:
... print("Can't divide by 0; sorry m8")
...
Can't divide by 0; sorry m8

Catching errors enables you to continue with a program even if something breaks. For instance, the following code fails with a ZeroDivisionError, and as a result we don’t compute the later expressions in the loop either:

>>> for i in range(3):
... print(1/i)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

But if you add in a try-except block, you get better results:

>>> for i in range(3):
... try:
... print(1/i)
... except ZeroDivisionError:
... print("Can't divide by 0; sorry m8")
...
Can't divide by 0; sorry m8
1.0
0.5

Feels nice, doesn’t it?

Recap and Final Thoughts

Here’s a Pythonic tips sheet for you:

  1. Readability counts. Format and structure your code cleanly.
  2. Beautiful is better than ugly. Avoid redundant solutions.
  3. Complex is better than complicated. It’s okay if your code is necessarily sophisticated, but it’s not okay if it is needlessly convoluted.
  4. Errors should never pass silently. Learn to handle errors — it’s worth your time!

And with that, I wish you the best of luck on your Pythonic adventures.


Take advantage of easy-to-implement lessons from one of the language’s most knowledgeable experts

Photo by Campaign Creators on Unsplash

You may not know it, but a Python installation comes with a wonderful and helpful poem, free of charge. To access it, all you need do is type import this into the terminal. You’ll then be greeted with the following:

“The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one — and preferably only one — obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!”

The author of this poem is Tim Peters, a famous software engineer and one of the chief contributors to the development of the Python programming language. Although it’s meant to be a language quirk that is both fun and humorous, the poem also has some damn good advice.

Let’s take a look at what we can learn.

Please make your code easy to read

Readability counts.

The following is a completely valid block of code in Python; it accomplishes its goal and runs without any errors:

x =   'All Too Well'
if x == 'All Too Well': print("Taylor Swift rocks")
else:
print("You need to re-evaluate your life choices.")

Turns out as long as you’re consistent with spaces and tabs, Python’s interpreter doesn’t really care how widely or evenly you space out your code.

But you know who does care? Three very important people, all of whom will hate you if you choose to write code that isn’t styled properly:

  1. Your teachers/mentors: These people have to either grade or review your code, and they won’t be thrilled about having to stare an extra several minutes just to figure out where to start.
  2. Your coworkers: They need to build off your code. If you needlessly make their lives harder at an already stressful (although rewarding) job, they will not be fond of you.
  3. Your future self: You may well find yourself pulling your own code out a few days in the future to start working on it again. At that point, you’ll really hate your past self for writing a jumbled mess instead of clear, clean, and maintainable code.

A life where this many people hate you is not a fun life, so it’s really in your better interest to write code that conforms to Python’s detailed and well-written style guide [1]. Make sure your indentations match up and your variable names are reasonable — and also add some well-placed comments to guide the reader:

my_favorite_song =   'All Too Well'# This block of code ensures the my_favorite_song variable has
# the correct value.
if my_favorite_song == 'All Too Well':
print("Taylor Swift rocks")
else:
print("You need to re-evaluate your life choices.")

Your mentors, your coworkers, and your future self will thank you.

And while you’re at it, make it pretty

Beautiful is better than ugly.

There is an important question that needs to be answered here: what is beautiful code?

It depends on the context. Python is a language designed for readability and simplicity, and so it stands to reason that the simplest code (which is still easy to understand) is also the most beautiful and elegant.

There are many relevant examples, but one of my favorites is a redundant construct common among new programmers. It involves returning True or False depending on the value of the variable one is interested in. Consider the following:

# This code returns whether or not my code is beautifuldef my_function(is_code_beautiful):
if is_code_beautiful == True:
return True
else:
return False

In principle, there is nothing wrong with this code. In fact, for newer coders, it’s arguably an effective teaching tool, as it provides way to think about what a conditional statement is actually meant to do.

However, it can be written in a much simpler (and thus more beautiful) way. Since the variable itself is already a Boolean (True or False) value, we can achieve the same effect with the following code:

# This code returns whether or not my code is beautifuldef my_function(is_code_beautiful):
return is_code_beautiful

Simple. Elegant. Pythonic.

Beautiful.

Isn’t complex the same as complicated?

No.

Complex is better than complicated.

Many people use the words complex and complicated interchangeably, so let’s start by talking about the difference between the two. They might have similar connotations colloquially, but are not the same in a programming context.

Complex code may be hard to understand, but usually out of necessity because the underlying algorithm itself is sophisticated (and no one has written simpler code that you can use rather than coding the algorithm from scratch). Complicated code is needlessly convoluted, in particular because there is a simpler way to achieve the same solution.

Let’s look at an example. Say we have the following deeply nested list:

data = [[[0, 255, 255], [45, 0, 0]], [[0, 0, 0], [100, 100, 100]]]

As a quick aside, you might think that a list nested this deeply serves no practical purposes, but this is in fact how images are stored in Python — as rows of pixels, where each pixel is a 3-element list consisting of red, green, and blue (RGB) values.

For a project in the course I am currently a TA for, students had to program an operation where they flipped a photo horizontally by reversing the order of pixels in all the rows.

While I was prepping for the project this is the solution I initially came up with:

for row in data:
for i in range(len(row) // 2):
temp = row[i]
row[i] = row[len(row) - 1 - i]
row[len(row) - 1 - i] = temp

At first, I thought this was a pretty nifty solution to reversing a list. That is, until my professor pointed out that I could just do the following:

for row in new_pixel_data:
row.reverse()

The difference is astounding.

One could argue that the second solution is still complex in principle, since reversing a list is a fairly involved task. However, it is exceedingly clear that in comparison to my first manual solution, it is far less complicated and thus much easier to understand.

Note that whether or not your code is complicated largely depends on the context. In the example above, my initial code is complicated because there exists much cleaner code which achieves the same goal. If a simple way to reverse Python lists didn’t exist, then my code would be fine (if still complex) simply by virtue of being the best available option.

A good rule of thumb: before you code something super involved, check if someone’s already done some work to make your life easier.

Check for errors!

Errors should never pass silently.
Unless explicitly silenced.

Interestingly enough, this is a topic often overlooked in introductory programming classes. My own first programming course only briefly touched on catching errors, never explicitly teaching how to do it. It’s an important skill, primarily because it enables your program to give the user more detail in the event of an error (or even keep the program running smoothly).

The simplest way to handle errors in Python is through a try-except block. You write your code as you normally do within the try, and if there is an error, the code starts running the except block:

>>> try:
... print(x)
... except:
... print("You never defined your variable.")
...
You never defined your variable.

You can also catch specific errors:

>>> try:
... 1/0
... except ZeroDivisionError:
... print("Can't divide by 0; sorry m8")
...
Can't divide by 0; sorry m8

Catching errors enables you to continue with a program even if something breaks. For instance, the following code fails with a ZeroDivisionError, and as a result we don’t compute the later expressions in the loop either:

>>> for i in range(3):
... print(1/i)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

But if you add in a try-except block, you get better results:

>>> for i in range(3):
... try:
... print(1/i)
... except ZeroDivisionError:
... print("Can't divide by 0; sorry m8")
...
Can't divide by 0; sorry m8
1.0
0.5

Feels nice, doesn’t it?

Recap and Final Thoughts

Here’s a Pythonic tips sheet for you:

  1. Readability counts. Format and structure your code cleanly.
  2. Beautiful is better than ugly. Avoid redundant solutions.
  3. Complex is better than complicated. It’s okay if your code is necessarily sophisticated, but it’s not okay if it is needlessly convoluted.
  4. Errors should never pass silently. Learn to handle errors — it’s worth your time!

And with that, I wish you the best of luck on your Pythonic adventures.

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – admin@technoblender.com. The content will be deleted within 24 hours.
Aliartificial intelligenceAugcodeimproveinventormachine learningMurtazaPythonsSimpleTechnoblenderTips
Comments (0)
Add Comment