Updated June 9, 2023
Introduction to Tips on Python Programming
I know the statement is ironic, but that’s how Python is. In today’s world, Python is one of the most used languages. It’s not just a language; it’s a way to do things properly, simply, and compactly. Python is one of the most known high-level languages, especially in open source. It sure is a vast Python language. The point is the more you know about Python Programming, the more you will know that there are still things you don’t know.’
Python Programming is a fast, compact language that can be easily rendered into any operating system. Besides, if you look around, you will see that the majority of the things run on Python; you can take examples from Google or YouTube. Some frameworks exclusively support Python, such as Django and Pyramid. There are even micro-frameworks such as Flask and Bottle. Python’s standard library consists of many internet protocols such as HTML, XML, JSON, E-mail Processing, Support for FTP, IMAP, and its Easy-to-use Socket interface. The most common purpose of usage of Python is for scientific and numeric computing. For example, SciPy, Pandas, and Python.
‘I have been around Python for a long time. Long enough to understand the importance of basic and advanced interpretations of the Python language. Still,l there is a time when even people who have worked long enough with Python will forget some of the most basic important stuff in Python Programming. So, I have written this article to give you guys a refresher. Now you know what Python is and how it works, let’s get to know some of the reasons I support Python more than any other language.
Whether you are an Expert or a Beginner, these things will always remind you why Python Programming is still the most flexible, simple, and creative Python language of all time. I have taken my time to explain these examples in detail, so if you still have a hard time understanding them, you can simply Google the titles I have given to these examples. You will easily understand what I am talking about. So, without much further ado, let’s start.
These are a few tricks I have learned over the past couple of years, which I keep saved in a text file. So, whenever I am stuck on any piece of code, I just glimpse these things, and most of my problems are solved many times.
Python Programming Tips/Tricks
So, these are the 10 simple yet most useful tips on Python programming:-
1. Modules
The best thing about Python is that you can create your own modules. For example, I can create my own function and modules and place them together in a separate folder. So what I do is I write down specific codes, which I know I would be used in common in most of my work, then convert them into a module and keep them aside in a separate folder. Doing this saves a lot of time from writing them again and debugging them to check for errors.
Another reason is that you need to keep your program efficient and manageable if they are big in size. To manage this, you can break them into separate files, put multiple functions and definitions into a file and use them by importing them into scripts and programs. Note that these files will have a *.py extension. And once you import them, it will auto-create a *.pyc extension file that will load much quicker than the normal *.py file.
2. True and False
This is also one of the most used methods. If you have ever played games, and by games, I mean high-end Games, you must have noticed that sometimes you have to lower the graphics. But again, sometimes, even you cannot find these options in the game. So, what you normally do is, find the config file in the documents folder and change it.
For example, you change the Vsync = True or False per the situation. These things are used most often in Python. But the one I am trying to explain here is somewhat different but still related to it. True equal 1, and False equals 0 in Python. In short, true means you agree, and false means you disagree. So, you can assign True and False statements using the “=” sign or check the equality using the “==” sign. As simple as that.
3. Python Performance debug
When writing a program, our main goal is to make the program efficient, fast, and compact. But there are times when you simply cannot make the program compact. So at these times, you may not actually want to make the program compact to make it faster. What you can do is, for example, when handling codes in a dictionary, you can try an alternate method of dictating an item. Confused? Let me explain this. You can add an item directly and then check whether the inserted items exist or need updating. So, by doing this, you don’t need to check each and every other item to match with it and then update it, which kind of will make the application slow. Following is a famous example of that:
p = 16
myDiction = {}
for i in range(0, p):
char = 'abcd'[i%4]
if char not in myDict:
myDiction[char] = 0
myDiction[char] += 1
print(myDiction)
The above example is the normal way of writing it. Now here is how it will make the code run faster,
p = 16
myDiction = {}
for I in range(0, p):
char = 'abcd'[i%4]
try:
myDiction[char] += 1
except KeyError:
myDiction[char] = 1
print(myDiction)
4. Py2exe
Another useful tip I can think of is py2exe. Normally, when writing code in any language, it can sometimes be a hassle to compile them into an executable, especially if you are using Windows. But for Python Programming, it’s actually very simple. You can simply download py2exe, which again is open-source software that you can download from sourceforge.net. Using this app, you can simply convert even your modules into Excel, unlike C or C++, which is actually a stress of mind when compiling into Excel.
5. Sets
You will surely love this next tip if you are a maths freak. You may have used sets in your lower classes. Remember something? Yeah, exactly, Unions and stuff. Some people like me don’t like to use automated software sometimes. The reason for that is Security.
Let’s take a simple example of Microsoft Excel. Some people tend to use Excel only to group and create a database. They just need that and good security for that. They are not interested in formatting the text, color, and stuff. So, at those times, I created my own python Programming software stack and created my own database. For some of my security reasons, I prefer Python over MYSql. So, coming back to my point of sets, Sets are extremely useful when creating databases. Especially when you want to find matches, create groups, and perform similar tasks. Following is a simple example of that.
>>> A = {1, 2, 3, 3}
>>> A
set([1, 2, 3])
>>> B = {3, 4, 5, 6, 7}
>>> B
set([3, 4, 5, 6, 7])
>>> A | B
set([1, 2, 3, 4, 5, 6, 7])
>>> A & B
set([3])
>>> A - B
set([1, 2])
>>> B - A
set([4, 5, 6, 7])
>>> A ^ B
set([1, 2, 4, 5, 6, 7])
>>> (A ^ B) == ((A - B) | (B - A))
True
6. Merging Python and Shell Scripts
Now, this is something you can’t do with C or C++. If you are an open-source guy, you would surely use Linux as the main Operating OS or at least a Dual Boot. So, Linux already includes Python. And python is extremely compatible with Linux. This gives us the benefit of compiling and merging them together. You can simply create a script that can work as a normal Unix script and an interpreted Python code simultaneously. When writing a shell script, you need a four-quote character and an empty string to the shell, but you need to do that with a triple-quoted string with a quote character in Python. Remember that the first string in a script can be easily stored as a doc string for a module, but after that, the Python interpreter will simply ignore it.
An example is as follows:
#!/bin/sh
__doc__ = """
Demonstrate how to mix Python + shell script.
"""
import sys
print "Hello World!"
print "This is Python", sys.version
print "This is my argument vector:", sys.argv
print "This is my doc string:", __doc__
sys.exit (0)
7. JSON-esque
Python has a lot of hidden stuff underneath. It only takes a person and his time to discover what magical operators and stuff are hidden inside. One among all the other stuff is the famous JSON-esque. You can create nested dictionaries without explicitly creating sub-dictionaries. They magically come into existence as we reference them.
Example as follows:
users = tree()
users['harold']['username'] = 'hrldcpr'
users['handler']['username'] = 'matthandlersux'
Now you can print the above as JSON with:
print(json.dumps(users))
And it will look like this
{"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}
8. Pip
Pip is something maybe most people know of. But still, it is awesome stuff you need to know if you are starting with Python. Sometimes, you need to inspect a package’s source before installing it. Most of the time, it’s for installing a newer version of some package. So, you can simply install pip and do the following:
pip install --download sqlalchemy_download sqlalchemy
pip install --no-install sqlalchemy
pip install --no-download sqlalchemy
If you want to install the bleeding-edge version of a package, you can directly check it from the GIT repository.
pip install git+https://github.com/simplejson/simplejson.git
pip install svn+svn://svn.zope.org/repos/main/zope.interface/trunk
9. virtualenv
Another important function of Python is Virtualenv. Virtualenv means Virtual Environment. This, now my friends, is a very awesome function of Python. To install virtualenv, you need to install pip first. Basically, to test Python in different conditions, you would normally have to change the global Python environment. But, one of the key benefits of sandboxing your Python environment is that you can easily test one code under different Python versions and package dependencies.
You can do as follows:
easy_install pip
pip install virtualenv
virtualenv python-workspace
cd python-workspace
source ./bin/activate
python
10. Zen of Python
Last but not least, it’s the Zen of Python. Zen of Python is a mini-guide for Python programming. Even if you don’t program Python, reading is still interesting. Just simply go to the Python interpreter and type:
import this
And I won’t be explaining this one because it’s simply amazing to try it out yourself.
And now, we have come to the end of the road. These are just my experiences, but if you find some, do post them so that the world knows how awesome Python is.
First Image Source: pixabay.com
Related Articles
Here are some articles that will help you get more details about Python Programming, so just go through the link.