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.
Looking to get started with Python? You need a Raspberry Pi!
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
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!”
This post was originally found on maketecheasier.com