When you decide to learn a programming language, you’ll have to research what language best suits your project. One of the things you may consider—especially if this is your first programming language — is how easy the language is to learn and use.
All programming languages are different. Some are difficult to learn, but once you know the basics, you can write solid code. On the other hand, some programming languages are easy to learn at first, but mastering them and writing solid code may not be as simple.
Python is one of the programming languages that are easy to learn and start coding in but producing solid, potent Python code requires a lot of practice.
Writing good Python code or, as it is called in the community, “Pythonic” code isn’t difficult; in fact, you can just follow this set of rules. Pythonic code is just a description of a code that’s easy to read, follow and understand. If you follow these rules, you’ll be considered fluent in Python.
In order to be fluent in Python you’ll need to use idioms — to write Pythonic code. The only way to do that is to practice.
The rules of Pythonic code aren’t complex and if you don’t know any other programming languages, you’ll find them perfectly sensible. (Some people have trouble when they come from another language and have to adapt to how the Python community does things.) Of course, these rules are really just to help make your code easy to read, follow and understand. They aren’t set in stone, so play around with them.
1. General Writing Style
Let’s kick things off with how to write commands in Python. When we write commands in Python, PEP8 suggests cutting your physical lines after 79 characters to make them more legible. Say you want to write a list of strings; instead of writing everything as a very long line, you can write each item in a new line.
someList = [ "this list has very very long strings",
"to make it more readable, each string will be",
"in a new line."]
You can do the same with strings. If you have a long string, you can use parentheses around your string to contain it and make it more readable.
longStr = (
"this sting is very very long"
"to make it more readable, each sting will be"
"in a new line."
)
The 79 characters per physical line of code is not a hard and fast rule; you can extend it to 88 or even 100 characters based on your code, and what you think will be most appropriate for your project. However, the Python standard library requires limiting lines to 79 characters if you’re writing coding commands and 72 in case of docstrings or comments.
2. Using Variable Tricks
Python offers many options that allow you to write up simple commands containing variable assignment operations. Perhaps the most useful variable trick in Python is variables unpacking. Unpacking is simply an efficient and short way to assign values to variables, such as variable value swapping.
x, y = y, x
Or unpack tuples, for example:
a, (b, c) = 10, (20, 30)
You can even do extended unpacking, for example:
v, *end = [10, 20, 30]
# gives v= 1, end = [2, 3]
v, *middle, z= [1, 2, 3, 4]
# gives v= 1, middle = [2, 3], z= 4
Unpacking is not the only trick you can use with variables. There’s also a Pythonic way to deal with ignored variables or variables that have a specific job. After that, they aren’t needed and naming them isn’t a worthwhile task. In the extended unpacking example, say I don’t need the last item of the list, I can then avoid naming it and use __
.
v, *middle, z= [1, 2, 3, 4]
# gives v= 1, middle = [2, 3]
The reason I recommend using __
instead of just _
(which we often see in Python books) is that the single underscore refers to the gettext()
function, which we use at the interactive prompt to store the value of the last command. So using the __
is just a way to avoid confusion and be consistent.
3. Dealing With Lists
Lists are a big part of Python, so various list techniques make your code more Pythonic. Let’s start with list initialization. In Python, you can initiate a list or create a list with nested lists in a simple way using the * operator.
listOfNones = [None] * 6
# gives [None, None, None, None, None, None]
listOfFives = [[5]] *5
# gives [[5], [5], [5], [5], [5]]
There are also Pythonic ways to filter a list. Let’s say you want to go through a list and delete some items based on some condition. You can’t use the remove method to delete the items because that can cause really subtle errors. You also can’t iterate the list twice because that would be inefficient. You can instead use list comprehension or generators to achieve the same results more efficiently and Pythonically.
# comprehensions create a new list
filtered_list = [item for item in sequence if item != x]
# to avoid generating a new object, use generators
filtered_list = (item for item in sequence if item != x)
4. Having Fun With Functions
Everything in Python is an object, including functions. Functions are an efficient way to package a part of the code that you can use repeatedly throughout your current or future codes. In Python, there are four different ways to pass arguments to a function.
How to Pass Arguments to a Function in Python
- Positional Arguments: These arguments are parts of the function’s meaning. They appear in the order in which they were written in the original function definition. For example, send_email(title, recipient, body).
- Keyword Arguments: Otherwise known as kwargs, these come in handy when dealing with a function that has many arguments. In that case, kwargs can be used with default values. For example, send_message(message, recipient, cc=None).
- Arbitrary Arguments Tuple: If your function needs an undefined number of arguments, you can use the *args construct to pass a tuple of arguments to the function. For example, def calc_ave(*nums). The nums will be a tuple with as many values as the user wants.
- Arbitrary Keyword Argument Dictionary: Similar to the arbitrary argument tuple, if a function requires an undetermined number of named arguments, you can use the **kwargs construct.
The last two techniques are very powerful, so be careful when using them and only do so when you find it necessary. If there is a better way to write the function without those methods, refrain from using them.
Another way to write more Pythonic functions is to have only one return statement. As your functions grow bigger, you may find yourself using multiple return statements within it. That said, having multiple returns will only make your functions difficult to read and modify.
5. Follow the Zen of Python
Finally, if you want to learn how to write good Python code or Pythonic code, all you need to do is follow the Zen of Python. The Zen of Python is a simple guide for writing Python code, also known as PEP 20. You can read the Zen of Python by simply running import this command.
>>> import this
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!
If you want to see concrete examples of using the Zen of Python, check out these slides.
You can learn the syntax of Python — you can know how to write things in Python and what’s considered correct or incorrect syntax — but knowing that won’t make you fluent in Python.
I like to think of programming languages the same way I do spoken languages. Some sound difficult to learn and perfect while others seem more manageable. That perception depends on various factors. If you want to learn English the degree of difficulty will depend on your native language and your ability to learn a new language. Then, even If you manage to learn the basics of English vocabulary and grammar, that doesn’t make you fluent in English. To be considered fluent in English, you need to be able to communicate effectively with others. In other words, you need to become proficient in English idioms.
Programming languages in general (and Python, in particular) are the same way. You can learn the syntax of Python — you can know how to write things in Python and what’s considered correct or incorrect syntax — but knowing that won’t make you fluent in Python.
In order to be fluent in Python you’ll need to use idioms — to write Pythonic code. The only way to do that is to practice.