Techno Blender
Digitally Yours.

3 Underappreciated Skills to Make You a Next-Level Python Programmer | by Murtaza Ali | Aug, 2022

0 68


Say hello to graphics, visualization, and funky data structures.

Photo by Minator Yang on Unsplash

You call yourself a Python programmer, and yet you’re probably unaware of the programming language’s amusing, openly available secret.

Do yourself a favor and start there. Open up your favorite terminal, launch the Python interpreter, and enter in the following: import this .

Upon hitting enter, you’ll be greeted with the following, eloquent poem.

“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!”

I’ll save an in-depth analysis of this literary gem for another article, emphasizing just one, major point: Python is designed to be a simple, concise, and elegant language.

Despite Python’s growing popularity, most new proselytes of the language tend to display the same standard set of skills: looping, defining functions, building objects — you know, the usual array (pun intended) of programming basics. Some folks might even use a list comprehension here and there.

While these skills are undeniably important, limiting oneself to them is a glaring mistake. Why? It fails to take advantage of a crucial fact: Python’s simplicity allows programmers to achieve incredible tasks with fairly straightforward code, building eventual tools and programs which would require far more headache in other languages.

In pursuit of that goal, here are three Python skills you might consider learning.

Python’s Graphical Turtle Library

Python’s Turtle library is probably one of the most underrated, underused graphical modules within the whole language. People are obsessed with more advanced tools like PyGame and Tkinter, which have far steeper learning curves. By contrast, Turtle is simple enough that many introductory programming classes use it to introduce Python to people who’ve never coded before.

At its core, Turtle is very simple. You simply have your mouse (the “turtle”), and you provide it with basic commands, telling it to move in the direction you want to draw a particular shape. As you move further along in your drawing, you can emphasize borders and fill in shapes with colors, much like in higher-level software such as Adobe Illustrator.

That’s all Turtle is, at the end of the day: using code to draw and paint.

To illustrate its simplicity, here’s a snippet of code that draws a square:

import turtle as t
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.done()

Or, more condensed:

import turtle as t
for _ in range(4):
t.forward(100)
t.right(90)
t.done()
Image By Author

Here’s a quick breakdown of the code:

  • The forward command tells the Turtle object to move 100 pixels forward.
  • The right command tells the Turtle object to turn 90 degrees to the right
  • The done command lets Python know we’re done drawing, which keeps the pop-up window containing the drawing from closing automatically.

Even with this quick example, we can already start to see how the basic building blocks of Turtle can be expanded to make more in-depth programs. For example, a square is not that far off from a “board” of sorts, useful for programming famous games like Connect-4 or 2048. Just do a little math and draw a few lines, and you’re on your way.

Accordingly, one of Turtle’s large advantages is that it allows you to program enjoyable, pretty games and graphics with only introductory knowledge. In other words, you need not be a JavaScript expert to blow people away with your inventions. In the first programming class I ever took, students were using Turtle to make involved, playable games just weeks after they saw Python for the first time.

If you’re willing to put in a little effort, so can you.

Visualization in Altair

As the world becomes increasingly data-centered, techniques for its processing and analysis are moving to the forefront of desired skills. The core goal of data science can be put to effective use by anyone (especially computer programs): displaying meaningful insights from data.

One of the least complex yet most effective ways to do this is through visualization. Within the Python Programming Language, two of the most commonly taught visualization modules are Matplotlib and Seaborn.

There is good reason for this: these two modules are straightforward in syntax, and thus easy to learn. This makes them ideal tools for quick visualization tasks intended at basic exploratory data analysis. For example, generating a line chart in Seaborn is simple:

import matplotlib.pyplot as plt
import seaborn as sns
sns.lineplot([1, 2, 3, 4], [1, 2, 3, 4])
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('An Exciting Line Chart')
Image By Author

However, their simplicity comes at a price. One of the primary principles of data visualization is expressiveness, roughly measured as how much of the relevant information from the data is encoded into the visualization. Because most of the plots you can make with Matplotlib and Seaborn are predetermined, your expressiveness is rather limited.

Enter Altair. Built on top of the famous JavaScript visualization library Vega-Lite, Altair provides the ability to generate a wide range of beautiful visualizations in Python code [1]. The learning curve is admittedly a step up from Matplotlib, but it’s still far easier than picking up JavaScript.

Altair provides a declarative grammar — while the code can get increasingly messy with more complex visualizations, the advantage is that it can always be broken back down the the same building blocks. For instance, here’s how you would generate the line chart from above:

import pandas as pd
import altair as alt
source = pd.DataFrame({'X': [0, 1, 2, 3, 4], 'Y': [0, 1, 2, 3, 4]})
alt.Chart(source).mark_line().encode(
x=alt.X('X', scale=alt.Scale(domain=[0, 4]), title='X-Axis'),
y=alt.Y('Y', scale=alt.Scale(domain=[0, 4]), title='Y-Axis')
).properties(
title='An Exciting Line Chart'
)
Image by Author

Altair’s power (i.e. expressiveness) lies in the huge number of custom options users can tinker with; what I’ve shown above is merely a tiny peek.

I’ve personally used Altair many times over the years to design and program novel visualizations that I imagined in my head. While there are still of course limitations, it’s a huge step up from Matplotlib and Seaborn. Furthermore, if you’re ever confused, the Altair community is incredibly responsive and helpful.

So next time you need to code a line chart, perhaps give Altair a shot.

Quirky Control and Data Structures

While of course offering the same standard loops and structures as all other programming languages, Python also boasts a number of more unique structures that can be both fun and useful. Let’s take a look at two interesting ones.

The For-Else Loop

Python, unlike most languages, allows you to use the conditional else keyword in conjunction with a for loop. Using this special syntax, you’d write a normal loop, followed by an else statement. Python uses the following execution rule: the else statement is executed if and only if the loop is not terminated by a break statement.

This is easier to see via example:

# No break, so we enter else statement
>>> for element in ['a', 'b', 'c']:
... if element == 'x':
... break
... else:
... print("THERE WAS A BREAK")
...
THERE WAS A BREAK
# Break, so we do not enter else statement
>>> for element in ['a', 'x', 'b', 'c']:
... if element == 'x':
... break
... else:
... print("THERE WAS A BREAK")
...
>>>

Since the first code snippet never breaks out of the for loop, Python knows to enter the else conditional; similarly, it knows not to do so in the second case.

The for-else loop is a fairly special use case, but it might be helpful the next time you want to perform some action determined by whether all elements of an array meet a certain condition.

The Dictionary Comprehension

Most Python programmers have heard of list comprehensions [2]; here, I’d like to discuss their lesser-known cousin — the dictionary comprehension.

Dictionaries [3] are undoubtedly one of the most useful features of Python, but they can be a bit of a pain to define at times. Enter dictionary comprehensions.

For example, let’s say you have a list of names, and you’d like to make a dictionary where the keys are the names themselves, and the values are the lengths of the names. Here’s how you might traditionally do so:

>>> names = ['Alice', 'Bo', 'Malika']
>>> traditional_dict = dict()
>>> for name in names:
... traditional_dict[name] = len(name)
...
>>> traditional_dict
{'Alice': 5, 'Bo': 2, 'Malika': 6}

Dictionary comprehensions simplify the code:

>>> names = ['Alice', 'Bo', 'Malika']
>>> comprehension_dict = {name: len(name) for name in names}
>>> comprehension_dict
{'Alice': 5, 'Bo': 2, 'Malika': 6}

Much cleaner.

Dictionary comprehensions work similarly to list comprehensions, effectively eliminating for loops in straightforward use cases.

Python is designed to be simple and concise, and it accordingly contains a number of data and control structures meant at promoting that goal. The for-else loop and dictionary comprehension are just two of my personal favorites.

I suggest you do a little digging to find your own.

Recap and Final Thoughts

As Python continues to rise in popularity, it will become increasingly more important for individual programmers to learn currently underappreciated skills. By mastering them, you’ll get the most out of your code (not to mention your resume).

Here’s a cheat sheet for future reference:

  1. Games and drawings aren’t just fun, they’re an in-demand product. Invest some time in learning Turtle.
  2. Data visualization is a valuable skill. Become great at it with Altair.
  3. Don’t limit yourself to the basics. Master new data and control structures.

Best of luck in your Pythonic adventures.

References

[1] https://altair-viz.github.io/gallery/index.html
[2] https://towardsdatascience.com/whats-in-a-list-comprehension-c5d36b62f5
[3] https://towardsdatascience.com/whats-in-a-dictionary-87f9b139cc03


Say hello to graphics, visualization, and funky data structures.

Photo by Minator Yang on Unsplash

You call yourself a Python programmer, and yet you’re probably unaware of the programming language’s amusing, openly available secret.

Do yourself a favor and start there. Open up your favorite terminal, launch the Python interpreter, and enter in the following: import this .

Upon hitting enter, you’ll be greeted with the following, eloquent poem.

“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!”

I’ll save an in-depth analysis of this literary gem for another article, emphasizing just one, major point: Python is designed to be a simple, concise, and elegant language.

Despite Python’s growing popularity, most new proselytes of the language tend to display the same standard set of skills: looping, defining functions, building objects — you know, the usual array (pun intended) of programming basics. Some folks might even use a list comprehension here and there.

While these skills are undeniably important, limiting oneself to them is a glaring mistake. Why? It fails to take advantage of a crucial fact: Python’s simplicity allows programmers to achieve incredible tasks with fairly straightforward code, building eventual tools and programs which would require far more headache in other languages.

In pursuit of that goal, here are three Python skills you might consider learning.

Python’s Graphical Turtle Library

Python’s Turtle library is probably one of the most underrated, underused graphical modules within the whole language. People are obsessed with more advanced tools like PyGame and Tkinter, which have far steeper learning curves. By contrast, Turtle is simple enough that many introductory programming classes use it to introduce Python to people who’ve never coded before.

At its core, Turtle is very simple. You simply have your mouse (the “turtle”), and you provide it with basic commands, telling it to move in the direction you want to draw a particular shape. As you move further along in your drawing, you can emphasize borders and fill in shapes with colors, much like in higher-level software such as Adobe Illustrator.

That’s all Turtle is, at the end of the day: using code to draw and paint.

To illustrate its simplicity, here’s a snippet of code that draws a square:

import turtle as t
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.done()

Or, more condensed:

import turtle as t
for _ in range(4):
t.forward(100)
t.right(90)
t.done()
Image By Author

Here’s a quick breakdown of the code:

  • The forward command tells the Turtle object to move 100 pixels forward.
  • The right command tells the Turtle object to turn 90 degrees to the right
  • The done command lets Python know we’re done drawing, which keeps the pop-up window containing the drawing from closing automatically.

Even with this quick example, we can already start to see how the basic building blocks of Turtle can be expanded to make more in-depth programs. For example, a square is not that far off from a “board” of sorts, useful for programming famous games like Connect-4 or 2048. Just do a little math and draw a few lines, and you’re on your way.

Accordingly, one of Turtle’s large advantages is that it allows you to program enjoyable, pretty games and graphics with only introductory knowledge. In other words, you need not be a JavaScript expert to blow people away with your inventions. In the first programming class I ever took, students were using Turtle to make involved, playable games just weeks after they saw Python for the first time.

If you’re willing to put in a little effort, so can you.

Visualization in Altair

As the world becomes increasingly data-centered, techniques for its processing and analysis are moving to the forefront of desired skills. The core goal of data science can be put to effective use by anyone (especially computer programs): displaying meaningful insights from data.

One of the least complex yet most effective ways to do this is through visualization. Within the Python Programming Language, two of the most commonly taught visualization modules are Matplotlib and Seaborn.

There is good reason for this: these two modules are straightforward in syntax, and thus easy to learn. This makes them ideal tools for quick visualization tasks intended at basic exploratory data analysis. For example, generating a line chart in Seaborn is simple:

import matplotlib.pyplot as plt
import seaborn as sns
sns.lineplot([1, 2, 3, 4], [1, 2, 3, 4])
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('An Exciting Line Chart')
Image By Author

However, their simplicity comes at a price. One of the primary principles of data visualization is expressiveness, roughly measured as how much of the relevant information from the data is encoded into the visualization. Because most of the plots you can make with Matplotlib and Seaborn are predetermined, your expressiveness is rather limited.

Enter Altair. Built on top of the famous JavaScript visualization library Vega-Lite, Altair provides the ability to generate a wide range of beautiful visualizations in Python code [1]. The learning curve is admittedly a step up from Matplotlib, but it’s still far easier than picking up JavaScript.

Altair provides a declarative grammar — while the code can get increasingly messy with more complex visualizations, the advantage is that it can always be broken back down the the same building blocks. For instance, here’s how you would generate the line chart from above:

import pandas as pd
import altair as alt
source = pd.DataFrame({'X': [0, 1, 2, 3, 4], 'Y': [0, 1, 2, 3, 4]})
alt.Chart(source).mark_line().encode(
x=alt.X('X', scale=alt.Scale(domain=[0, 4]), title='X-Axis'),
y=alt.Y('Y', scale=alt.Scale(domain=[0, 4]), title='Y-Axis')
).properties(
title='An Exciting Line Chart'
)
Image by Author

Altair’s power (i.e. expressiveness) lies in the huge number of custom options users can tinker with; what I’ve shown above is merely a tiny peek.

I’ve personally used Altair many times over the years to design and program novel visualizations that I imagined in my head. While there are still of course limitations, it’s a huge step up from Matplotlib and Seaborn. Furthermore, if you’re ever confused, the Altair community is incredibly responsive and helpful.

So next time you need to code a line chart, perhaps give Altair a shot.

Quirky Control and Data Structures

While of course offering the same standard loops and structures as all other programming languages, Python also boasts a number of more unique structures that can be both fun and useful. Let’s take a look at two interesting ones.

The For-Else Loop

Python, unlike most languages, allows you to use the conditional else keyword in conjunction with a for loop. Using this special syntax, you’d write a normal loop, followed by an else statement. Python uses the following execution rule: the else statement is executed if and only if the loop is not terminated by a break statement.

This is easier to see via example:

# No break, so we enter else statement
>>> for element in ['a', 'b', 'c']:
... if element == 'x':
... break
... else:
... print("THERE WAS A BREAK")
...
THERE WAS A BREAK
# Break, so we do not enter else statement
>>> for element in ['a', 'x', 'b', 'c']:
... if element == 'x':
... break
... else:
... print("THERE WAS A BREAK")
...
>>>

Since the first code snippet never breaks out of the for loop, Python knows to enter the else conditional; similarly, it knows not to do so in the second case.

The for-else loop is a fairly special use case, but it might be helpful the next time you want to perform some action determined by whether all elements of an array meet a certain condition.

The Dictionary Comprehension

Most Python programmers have heard of list comprehensions [2]; here, I’d like to discuss their lesser-known cousin — the dictionary comprehension.

Dictionaries [3] are undoubtedly one of the most useful features of Python, but they can be a bit of a pain to define at times. Enter dictionary comprehensions.

For example, let’s say you have a list of names, and you’d like to make a dictionary where the keys are the names themselves, and the values are the lengths of the names. Here’s how you might traditionally do so:

>>> names = ['Alice', 'Bo', 'Malika']
>>> traditional_dict = dict()
>>> for name in names:
... traditional_dict[name] = len(name)
...
>>> traditional_dict
{'Alice': 5, 'Bo': 2, 'Malika': 6}

Dictionary comprehensions simplify the code:

>>> names = ['Alice', 'Bo', 'Malika']
>>> comprehension_dict = {name: len(name) for name in names}
>>> comprehension_dict
{'Alice': 5, 'Bo': 2, 'Malika': 6}

Much cleaner.

Dictionary comprehensions work similarly to list comprehensions, effectively eliminating for loops in straightforward use cases.

Python is designed to be simple and concise, and it accordingly contains a number of data and control structures meant at promoting that goal. The for-else loop and dictionary comprehension are just two of my personal favorites.

I suggest you do a little digging to find your own.

Recap and Final Thoughts

As Python continues to rise in popularity, it will become increasingly more important for individual programmers to learn currently underappreciated skills. By mastering them, you’ll get the most out of your code (not to mention your resume).

Here’s a cheat sheet for future reference:

  1. Games and drawings aren’t just fun, they’re an in-demand product. Invest some time in learning Turtle.
  2. Data visualization is a valuable skill. Become great at it with Altair.
  3. Don’t limit yourself to the basics. Master new data and control structures.

Best of luck in your Pythonic adventures.

References

[1] https://altair-viz.github.io/gallery/index.html
[2] https://towardsdatascience.com/whats-in-a-list-comprehension-c5d36b62f5
[3] https://towardsdatascience.com/whats-in-a-dictionary-87f9b139cc03

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 – [email protected]. The content will be deleted within 24 hours.
Leave a comment