Although it’s pushed well past the 30-year mark since its release, Python remains one of the most relevant high-level programming languages in existence. Many developers will opt to use this language to make applications that can easily be maintained and require minimal hand-holding to work in a number of operating systems and distributions of Linux.
One of the greatest benefits of Python is its ability to snake (pun completely intended) around a lot of conventions found in other languages with little effort on behalf of the programmer, letting you compose incredibly simple little “quips” to get the job done. Here are a few examples!
- 1. Swap Variables Around
- 2. Do a Quick Napkin Factorial
- 3. Initialize and Declare Multiple Variables
- 4. Open and Read a File
- 5. Write to a File
- 6. Create a Ranged List of Numbers
- 7. Display All Users (In Linux/Unix/BSD)
- 8. Generate a Random Password
- 9. Find Instances of Anything Within Text
- 10. Convert Hexadecimal Expressions to Plaintext
- Frequently Asked Questions
1. Swap Variables Around
Because you don’t have to deal with tedious things like addresses in memory, swapping your variables for each other can be done in one simple line:
x, y = y, x
Just separate each variable with a comma, and swap them around!
This is what the concept would look like in a snippet:
x = 1 y = 4 x, y = y, x print(x,y)
Running this in console should output “4 1”.
2. Do a Quick Napkin Factorial
Python’s math tools allow for some very creative code to perform otherwise complex calculations. For example, what’s the quickest way to find the number of ways a number of objects can be arranged? Do a factorial. With the
reduce() call, you can quickly come up with the answer!
reduce(lambda a, b: a * b, range(1, x+1)
This call will calculate the factorial of any number you previously define in “x.”
Don’t forget that
reduce() is a component of Python’s functools library. This is what the code looks like in a snippet:
from functools import reduce x = 12 print(reduce(lambda a, b: a * b, range(1, x+1)))
Your console should output 479001600 from this particular calculation. Go ahead and make “x” whatever you want!
3. Initialize and Declare Multiple Variables
Python’s syntax rules allow you to do pretty wild things. For instance, initialize and declare as many variables as you want in one single go. This as opposed to doing so line-by-line.
x, y, z = 16, 78, 195
Print these out and you’ll end up with “16 78 195.” The neat thing is that you don’t even have to restrict yourself to declaring one type of variable within a line. Replace the “y” declaration with a string like “Hi” and it’ll be just fine!
4. Open and Read a File
Python requires you to iterate through a file line-by-line as you would in many other languages. Even so, it gives you the ability to implement the entirety of the function of both opening and reading the file into one single line of code:
[line.strip() for line in open('file.txt')]
Now, if I want to just display the text of my own default bash configuration file, this is what I’d write:
[print(line.strip()) for line in open('/home/miguel/.bashrc')]
5. Write to a File
Just like with reading a file, the process of writing to one is pretty straightforward in this nifty language.
with open("file.txt",'a',newline='\n') as f: f.write("This is a new line in a file")
The with statement within Python lets you avoid the hassle of having to close the file handle. Hence it won’t conflict with other applications that would attempt to access it while yours is open.
You can now use the one-liner you learned for reading a file to check whether that line was added correctly!
[print(line.strip()) for line in open('file.txt')]
6. Create a Ranged List of Numbers
Similarly to how other scripting languages like LUA work, Python lets you spawn pre-populated lists as long as the operations lead to a predictable result. In this snippet, we create a list of 10 integers ranging from 0 to 9:
lst = [i for i in range(0,10)]
Printing this list will yield a comma-separated list of numbers with the parameters we discussed earlier.
7. Display All Users (In Linux/Unix/BSD)
Ever wonder how many user names there actually are in your particular Linux installation? Python has a great way of doing this in a single line by opening your “/etc/passwd” file. All we have to do in this case is trim out everything from the first colon (“:”) in each line onwards.
print('\n'.join(line.split(":",1) for line in open("/etc/passwd")))
If you haven’t sniffed around in that file, you may be surprised to find that there are many more users created by your system than the one you log in with and the root user.
User lists are normally this long because the system creates its own forms of authentication based on services you run.
8. Generate a Random Password
Like any self-respecting language, Python lets you randomize things, but it can’t help but take things a step further and let you do so to generate a password in one single line. It is admittedly a very long one..
pwd = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 %^*(-_=+)'; print(''.join([pwd[random.randint(0,len(pwd)-1)] for i in range(32)]))
This particular snippet will generate a 32-character password that allows for spaces. Adjust to your liking. If you don’t want a space in the password for whatever reason, remove the space within the string declaration. Don’t forget to import the “random” library or else your code won’t work!
9. Find Instances of Anything Within Text
If you’re reading a longer file and you’re trying to find how many instances of a particular expression exist within it, there’s a little zinger for that:
import re; len(re.findall('d','The dumb lazy cat doesn\'t know how to hunt birds.'))
In this particular example, we’re trying to find how many times the letter “d” appears in the string following it. By printing the output, the console lets us know there are 3 instances of the letter. You can do this with entire words and search within a file.
10. Convert Hexadecimal Expressions to Plaintext
With a little bit of iterative magic, it’s possible to convert hexadecimal code into plain text in one simple expression:
print(''.join(chr(int(''.join(i), 16)) for i in zip(*[iter('576f772c2049276d2077726974696e6720696e2068657861646563696d616c21')]*2)))
The large pile of gibberish within iter() is a hexadecimal expression that this code converts to read out to, “Wow, I’m writing in hexadecimal!”
Frequently Asked Questions
How difficult is Python compared to other languages?
While it does have some flaws particular to some coding styles, Python offers a much more beginner-friendly atmosphere than other languages due to its flexibility with variable types. It’s an interpreted language, so it doesn’t need you to deal with the tedium of allocating memory by hand and ensuring that it’s freed when no longer in use.
Is Python stable?
Python’s developers are strongly against the idea of invalidating old code with new releases, and have been historically very careful to ensure backwards compatibility with much older code. In 2005, the Python community had to deal with a difficult issue as
reduce() and a number of other functions were removed from the standard library and had to be imported from another one as of Python 3000. In general, these things are announced and if your code stops running properly, the console provides helpful information that lets you find out why and make adjustments accordingly.
What's the best development environment for Python?
If you want to use an integrated development environment for Python, there are a few options for you that work across operating systems:
- PyCharm – Use this if you are serious about dedicating yourself to Python. This IDE specializes only in Python and contains a significant number of tools and libraries that can help you code fluidly.
- Visual Studio Code – If you’re looking to branch out eventually and learn other languages, VSCode (known in Linux sometimes as Code – OSS and in Arch Linux as the “code” package) provides a powerhouse of features as well as an integrated compiler for a great variety of languages.
- Vim – it allows for very rapid complex text editing from inside any terminal emulator. It has a high learning curve but should be in every programmer’s arsenal.
Image credit: Pixabay All screenshots by Miguel Leiva-Gomez
Our latest tutorials delivered straight to your inbox