Posted on Leave a comment

How to Allocate Your Time as a Freelance Developer? The 40/30/30 Rule for Maximal Productivity

Here’s the time allocation for freelance developers:

  • 20% Become a Business Genius: Read business books and complete business courses.
  • 20% Master Your Niche: Read programming books and specialize.
  • 30% Increase Demand for Your Services: Apply for gigs and generate leads into your business. Learn more here.
  • 30% Do Work For Clients: Always overdeliver to feed into the previous step.

By reading business books, you’ll become more and more efficient in building your business and your business will transform over time to the better. By reading programming books, you’ll be able to solve problems for clients much faster. Expert coders can complete gigs faster and produce better quality. These two learning habits will ensure that you maximize the leverage of your time and it’s the best investment you can make.

Now you have the skills—but to earn higher hourly rates, you need to increase demand for your services. As a rule of thumb: double the demand for your services will double your hourly rate. How can you increase demand? Build a loyal client base of business owners who know, like, and trust you. You accomplish this by always giving them more value than they pay for. The most crude way to get clients is to apply for gigs on Upwork and Fiverr. Do it if necessary!

Finally, you need to do the work. But most of the time you should invest in the previous steps to sharpen your saw and build a sustainable business. Doing the work will be easier and more profitable as a result!

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

Closures and Decorators in Python

This tutorial teaches you two advanced Python skills: closures and decorators. Mastering them will make you a better coder today—so, let’s dive right into them!

Closures

Every function in Python is first class, because they can be passed around like any other object. Usually, when a programming language creates a function just like other data types, that programming language supports something called Closures.

A closure is a nested function. It is defined within an outer function.

def outer_hello_fn(): def hello(): print("Hello Finxter!") hello()

Here, we have an outer function called outer_ hello_ fn, it has no input arguments. The function hello is a nested function defined within the outer function. The hello function is a closure.

Try It Yourself:

Exercise: What’s the output of this code snippet? Run the code to test if you’re correct.

When the outer function is called, the hello function within it will be defined and then invoked. Here is the function call and output:

outer_hello_fn()

Output:

Hello Finxter!

hello has been defined within outer_hello_fn, which means if you try and invoke the hello function, it will not work.

hello()

Output:

NameError: name 'hello' is not defined

If you want access to a function that is defined within another function, return the function object itself. Here is how.

def get_hello_fn(): def hello(): print("Hello Finxter!") return hello

The outer function is called get_hello_fn. hello, is an inner function, or closure. Instead of invoking this hello function, simply return the hello function to whoever calls get_hello_fn. For example:

hello_fn = get_hello_fn()

Invoking get_hello_fn stores the return function object in the hello_fn variable. If you explore the contents of this hello_fn variable, you will see that it is a function object.

hello_fn

Output:

<function __main__.get_hello_fn.<locals>.hello>

As you can see in the structure, it is a locally defined function within get_hello_fn, that is, a function defined within another function, that is a closure. Now, this closure can be invoked by using the hello_fn variable.

hello_fn()

Output:

Hello Finxter!

Invoke hello_fn() will print out Hello Finxter! to screen. A closure is something more than just an inner function defined within an outer function. There is more to it. Here is another example:

def hello_by_name(name): def hello(): print("Hello!", name) hello() return hello

Here, the outer function is called hello_by_name, which takes in one input argument, the name of an individual. Within this outer function, there is the hello inner function. It prints to the screen Hello!, and the value of the name.

The name variable is an input argument to the outer function. It is also accessible within the inner hello function. The name variable here can be thought of as a variable that is local to the outer function. Local variables in the outer function can be accessed by closures. Here is an example of passing an argument to the outside function:

greet_hello_fn = hello_by_name("Chris")

The function hello is returned and it is stored in the greet_hello_fn variable.

Executing this prints out Hello! Chris to screen. That is because we invoked the closure from within the outer function. We have a reference to the closure that was defined by the outer function.

greet_hello_fn()

Output:

Hello! Chris

Notice something interesting here. Chris is available in the variable name which is local to the hello_by_name function.

Now, we have already invoked and exited hello_by_name but the value in the name variable is still available to our closure. And this is another important concept about closures in Python. They hold the reference to the local state even after the outer function that has defined the local state has executed and no longer exists. Here is another slightly different example illustrating this concept.

def greet_by_name(name): greeting_msg = "Hi there!" def greeting(): print(greeting_msg, name) return greeting

The outer function, greet_by_name, takes in one input argument, name. Within the outer function, a local variable called greeting_msg is defined which says, “Hi there!”. A closure called greeting is defined within the outer function. It accesses the local variable greeting_msg as well as the input argument name. A reference to this greeting closure is returned from the outer greet_by_name function.

Let’s go ahead and invoke greet_by_name and store the function object that it returns in the greet_fn variable. We will use this function object to greet Ray by name. Go ahead and invoke the greet_fn() by specifying parentheses. And it should say, Hi there! Ray. Observe how the closure has access not just to the name Ray but also to the greeting message, even after we have executed and exited the outer function.

greet_fn = greet_by_name("Ray")
greet_fn()

Output:

Hi there! Ray

Closures carry around information about the local state. Let’s see what happens when the greet_by_name function is deleted, so you no longer have access to the outer function.

del greet_by_name

Now, remember that name and greeting message are both variables that were defined in the outer function. What happens to them? Now if you try to invoke greet by name.

greet_by_name("Ray")

Output:

NameError: name 'greet_by_name' is not defined

What about the greet_fn?

Remember that greet_fn is a reference to our closure. Does this still work?

greet_fn()

Output:

Hi there! Ray

Not only does it work, but it still has access to the local variables that were defined in the outer function. The outer function no longer exists in Python memory, but the local variables are still available along with our closure.

Decorators – Code Modification

Decorators help to add functionality to existing code without having to modify the code itself. Decorators are so-called because they decorate code, they do not modify the code, but they make the code do different things using decoration. Now that we have understood closures, we can work our way step by step to understanding and using decorators.

def print_message(): print("Decorators are cool!")

Here is a simple function that prints a message to screen.

print_message()

Output:

Decorators are cool!

Each time you invoke this function it will always print the same message. I want to use a few characters to decorate the original message, and I do this using the highlight function.

import random def highlight(): annotations = ['-', '*', '+', ':', '^'] annotate = random.choice(annotations) print(annotate * 50) print_message() print(annotate * 50)

The outer function highlight has no input arguments. Within the highlight function, a random choice of annotations is used to decorate the original message. The message will be highlighted with a random choice between the dash, the asterisk, the plus, the colon, and the caret.  The output will have an annotation of 50 characters before and after the message which is inside the print_message function.

Try It Yourself:

Exercise: What’s the output of this code snippet? Run the code to test your understanding!

highlight()

Output:

::::::::::::::::::::::::::::::::::::::::::::::::::
Decorators are cool!
::::::::::::::::::::::::::::::::::::::::::::::::::

Here is another function with a different message, print_another_message.

def print_another_message(): print("Decorators use closures.")

Now if I want to highlight this message as well, the existing highlight function will not work because it has been hardcoded to invoke the print_message function. So how do I change this highlight function so that it is capable of highlighting any message that I want printed out to screen? Remember that functions are first-class citizens in Python, which means whatever print function you have, you can pass it as an input argument to the highlight function. Here is a redefined highlight function, make_highlighted.

def make_highlighted(func): annotations = ['-', '*', '+', ':', '^'] annotate = random.choice(annotations) def highlight(): print(annotate * 50) func() print(annotate * 50) return highlight

The only difference here is that make_highlighted takes in an input argument that is a function. This function is what will print out the message to be displayed. The next change is that within the highlight closure, the function object that was passed in is invoked. That is the function object that will print out the message. Now we have two print functions so far.

print_message()
print_another_message()

And now with the help of  make_highlighted function, any printed message can be highlighted. For example:

highlight_and_print_message = make_highlighted(print_message) highlight_and_print_message()

Output:

++++++++++++++++++++++++++++++++++++++++++++++++++
Decorators are cool!
++++++++++++++++++++++++++++++++++++++++++++++++++

To print a different message and have it highlighted, simply pass a different function object to the make_highlighted function.

highlight_and_print_another_message = make_highlighted(print_another_message) highlight_and_print_another_message()

Output:

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Decorators use closures.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

It is clear that the make_highlighted function is very generic, you can use it to highlight any message that you want printed to screen. The function make_highlighted is a decorator.

Why is it a decorator? Well, it takes in a function object and decorates it and changes it. In this example, it highlights the function with random characters. Decorators are a standard design pattern, and in Python, you can use decorators more easily. Instead of passing in a function object to make_highlighted, accessing the closure, and then invoking the closure, you can simply decorate any function by using @ and placing the decorator before the function to decorate.

@make_highlighted
def print_a_third_message(): print("This is how decorators are used")

The use of the decorator @make_highlighted will automatically pass the function print_a_third_message as an input to make_highlighted and highlight the message.

print_a_third_message()

Output:

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is how decorators are used
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Now you can use the decorator to highlight any messages.

@make_highlighted
def print_any_message(): print("This message is highlighted!")

And now if you invoke print_any_message, you will find that the result that is displayed to screen is highlighted.

print_any_message()

Output:

++++++++++++++++++++++++++++++++++++++++++++++++++
This message is highlighted!
++++++++++++++++++++++++++++++++++++++++++++++++++

Decorators – Customization

Let’s see another example of a Decorator that will do some work. It will do some error checking for us.

Here are two functions that will be the input to our decorator

def square_area(length): return length**2 def square_perimeter(length): return 4 * length

We assume that the value of the radius passed in is positive and correct.

square_area(5)

Output:

25

What if I invoke the square_area and pass in -1?

square_area(-1)

Output:

-4

The input -1 doesn’t make sense as a value for the length. The function should have thrown an error or told us in some way that negative values of length are not valid. Now, if you were to perform an error check for each of these functions, we would have to do it individually. We would have to have an if statement within the area function as well as the perimeter function. Instead of that, let’s write a decorator that will perform this error checking for us. The decorator safe_calculate takes in one input argument that is a function object.

def safe_calculate(func): def calculate(length): if length <= 0: raise ValueError("Length cannot be negative or zero") return func(length) return calculate

This is the function object that will perform the calculation. Within the safe_calculate outer function, the inner function called calculate is the closure. calculate takes in one input argument, the length. It checks to see whether length is less than or equal to 0. If yes, it throws an error. And the way it throws an error is by simply calling a raise ValueError, “Length cannot be negative or zero”. Once we raise this error, Python will stop the execution. But if length is positive, it will invoke func and pass in length as an input argument. The safe_calculate is our decorator, which takes as its input a function object and returns a closure that will perform the safe calculation.

square_area_safe = safe_calculate(square_area)

Let’s test it first:

square_area_safe(5)

This is safe and I get the result here on the screen.

25

Invoking it with a negative number will raise an error

square_area_safe(-1)

Output:

ValueError: Length cannot be negative or zero

Let’s decorate the perimeter function as well with the safe_calculate.

square_perimeter_safe = safe_calculate(square_perimeter) square_perimeter(10)

Output:

40

But if you were to call square_perimeter_safe with a negative value for length well, that is a ValueError.

square_perimeter_safe(-10)

Output:

ValueError: Length cannot be negative or zero

Now that you have a decorator, you should decorate your functions rather than use the way that we have been using so far.

@safe_calculate
def square_area(length): return length**2 @safe_calculate
def square_perimeter(length): return 4 * length

Now, the next time square_area or the square_perimeter is called, the safety check will be performed.

square_perimeter(3)

Output:

12

If you try to calculate the perimeter for a negative value of the length, you will get a ValueError. The safe_calculate function that we set up earlier has a limitation, and you will see what it in a future example.

square_perimeter(-3)

Output:

ValueError: Length cannot be negative or zero

What happens when you have more than one input? Here is a function that calculates the area of a rectangle.

@safe_calculate
def rectangle_area(length, width): return length * width

Within our safe_calculate function, we had invoked the func object which performs the calculation with just one input argument, with just the variable length. This is going to cause a problem when we use the safe_calculate decorator for the rectangle_area function.

Once I have decorated this function, I’m going to invoke it with 4, 5.

rectangle_area(4, 5)

Output:

TypeError: calculate() takes 1 positional argument but 2 were given

The problem is with the way we had defined the closure inside the safe_calculate function.

The calculate closure takes in just one input argument. If a function has multiple input arguments, then safe_calculate cannot be used. A redefined safe_calculate_all function is shown below:

def safe_calculate_all(func): def calculate(*args): for arg in args: if arg <= 0: raise ValueError("Argument cannot be negative or zero") return func(*args) return calculate. 

It takes in one input argument that is the function object that is to be decorated. The main change is in the input arguments that are passed into the calculate closure. The function calculate now takes in variable length arguments, *args.  The function iterates over all of the arguments that were passed in, and checks to see whether the argument is less than or equal to 0. If any of the arguments are less than or equal to 0, a ValueError will be raised. Remember, *args will unpack the original arguments so that the elements of the tuple are passed in individually to the function object, func. You can now use this safe_calculate_all decorator with functions that have any number of arguments.

@safe_calculate_all
def rectangle_area(length, width): return length * width
rectangle_area(10, 3)

Output:

30

Let’s try invoking the same function, but this time one of the arguments is negative. Width is negative and that gives me a ValueError, thanks to our safe_calculate_all decorator.

rectangle_area(10, -3)

When you invoke this function, it will check all arguments.

ValueError: Argument cannot be negative or zero

It doesn’t matter which argument is negative, you still get the ValueError. Here the length is negative:

rectangle_area(-10, 3)

Output:

ValueError: Argument cannot be negative or zero

Chaining Decorators

You can have a function decorated using multiple decorators. And these decorators will be chained together.

Here are two decorators, one prints asterisks and the other plus signs

def asterisk_highlight(func): def highlight(): print("*" * 50) func() print("*" * 50) return highlight def plus_highlight(func): def highlight(): print("+" * 50) func() print("+" * 50) return highlight

The print_message_one is decorated with the asterisk_highlight.

@asterisk_highlight
def print_message_one(): print("Decorators are cool!") print_message_one()

Output:

**************************************************
Decorators are cool!
**************************************************

Now let’s define another print function, but this time we will decorate it using two decorators, the plus_highlight and the asterisk_highlight.

@plus_highlight
@asterisk_highlight
def print_message_one(): print("Decorators are cool!")

What you see here is an example of chaining decorators together. But how are they chained? Which decoration comes first, the asterisk_highlight, or the plus_highlight? Whichever decorator is the closest to the function definition is what is executed first, and then the decorator which is further away from the function definition. This means that the message will be first highlighted with the asterisk, then the plus.

print_message_one()

Output:

++++++++++++++++++++++++++++++++++++++++++++++++++
**************************************************
Decorators are cool!
**************************************************
++++++++++++++++++++++++++++++++++++++++++++++++++

If you change the order of the decorators, the decorations order will change as well.

@asterisk_highlight
@plus_highlight
def print_message_one(): print("Decorators are cool!") 

You will have the same function print_message_one, but the decorator that is closest to the function definition is the plus_highlight and then the asterisk_highlight.

print_message_one()

Output:

**************************************************
++++++++++++++++++++++++++++++++++++++++++++++++++
Decorators are cool!
++++++++++++++++++++++++++++++++++++++++++++++++++
**************************************************

Use of kwargs in Decorators

In this example we are using kwargs to display different messages for a decorator that times the execution of a function

def timeit(func): def timed(*args, **kw): if 'start_timeit_desc' in kw: print(kw.get('start_timeit_desc')) ts = time.time() result = func(*args, **kw) te = time.time() if 'end_timeit_desc' in kw: print('Running time for {} is {} ms'.format(kw.get('end_timeit_desc'), (te - ts) * 1000)) return result return timed 

The timeit decorator is used for the test function.  Three parameters are passed to the function test: a, b and, **kwargs. The parameters a and b are handled in the decorator with *args as we have seen before.  The **kwargs parameter is used to pass descriptions for the function.  These parameters are start_timeit_desc and end_timeit_desc.  These two parameters are checked inside the timed closure and will display the messages that are in them.

@timeit
def test(a,b, **kwargs): return a * b result = test(10,20, start_timeit_desc = "Start of test(10,20)...", end_timeit_desc = "End of test(10,20)")
print("result of test(10,20) = " + str(result))
Output:
Start of test(10,20)...
Running time for End of test(10,20) is 0.0 ms
result of test(10,20) = 200
Posted on Leave a comment

How to Write Multiple Statements on a Single Line in Python?

Problem: Given multiple Python statements. How to write them as a Python One-Liner?

Example: Consider the following example of four statements in a block with uniform indentation:

a = 1
b = 2
c = a + b
print(c)

Each of the four statements is written in a separate line in a code editor—this is the normal procedure. However, what if you want to one-linerize those:

How to write all four statements in a single line of code?

Solution: The answer is simple if all statements have a uniform indentation and there’s no nested block. In this case, you can use the semicolon as a separator between the statements:

a = 1; b = 2; c = a + b; print(c)

Let’s do some practice testing to learn and improve your Python skills:

Exercise: one-linerize the given code! Run the code and check if the one-liner does the same as the original code!

Indented Block

While this works beautifully, if all statements are not indented—does it still work if you have an indentation block that starts with the colon : symbol after if, elif, else, for, while, or try/except statements?

Here’s an example of such a block:

for i in range(10): c = i ** 2 print (c)

You try the following one-liner using the semicolon as a separator between the two statements in the block

for i in range(10): c = i ** 2; print(c) '''
0
1
4
9
16
25
36
49
64
81 '''

This works beautifully and Python understands what you are trying to do. However, if you have nested indentation blocks, this doesn’t work anymore.

Consider the following example:

for i in range(3): for j in range(3): print(i, j)

If you write this in a single line, Python throws a syntax error:

While you can discuss if this makes sense or not—given that the syntax is not ambiguous here—it doesn’t change the fact: nested block cannot be one-linerized in a straightforward way. But this doesn’t prevent us from doing it, right?

Nested Indentation Blocks

Read the following article to learn how to compress multiple lines of code into a single 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(...)".

This method is very powerful and it allows you to compress any complicated multi-line script in a single line of Python code!

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

How to Make an Integer Larger Than Any Other Integer in Python?

This article discusses a situation where you are required to implement an integer object which, when compared using the greater than operator >, to any other existing integer value in the program, will always return True

Before diving into the possible solutions, we must take note of the following:

Python 2 consists of plain integers and long integers. However, in Python 3, plain and long integers have been merged, and integer in python 3 is the same as long in python 2. Therefore an integer value has no maximum and minimum limits in python 3.

value1=9223372036854775807
print("value1=",value1)
print(type(value1)) value2=value1+1
print("value2=",value2)
print(type(value2))

Output in Python 2:

value1= 9223372036854775807
<type 'int'>
value2= 9223372036854775808L
<type 'long'> 

Output in Python 3:

value1= 9223372036854775807 <class 'int'> value2= 9223372036854775808 <class 'int'> 

Note:

In a 64 bit environment, the sys.maxint constant returns the maximum possible plain integer value in python2 which is “9223372036854775807”. Anything higher than this value will be automatically converted to a long type. However, the sys.maxint constant has been removed in python3 since there is no longer a limit to the value of integers. In Python 3 sys.maxsize can be used as an integer larger than any other practical list or string index in a program. The value returned by the sys.maxsize constant depends on the system/platform it is run upon. This means that for a 32-bit platform the value would be 2**31 – 1 = 2147483647, while in a 64-bit platform the value would be 2**63 – 1=9223372036854775807. 

Now let us explore how we can use the greatest integer value in our program:

Method 1: Using a Custom Class 

Everything in python is an “Object”. Also, integers in python3 have no limits. Thus it is safe to say that integers in python are objects with no maximum and minimum limits. Therefore a probable workaround for our problem statement is to create a custom class and return an object that would be greater than any other object in the program.  

import functools
import sys @functools.total_ordering
class AlwaysGreater(object): def __le__(self, other): return False class MaximumInteger(AlwaysGreater, int): def __repr__(self): return 'MaximumInteger()' obj=MaximumInteger()
print(isinstance(obj,int))
print("1. Is obj greater than sys.maxsize?",obj > sys.maxsize)
print("2. Sorting list: [100,0,obj,922337036854775808,sys.maxsize] in ascending order: ")
print(sorted([100,0,obj,9223372036854775808,sys.maxsize]))

Output:

True
1. Is obj greater than sys.maxsize? True 2. Sorting list: [100,0,obj,922337036854775808,sys.maxsize] in ascending order: [0, 100, 9223372036854775807, 9223372036854775808, MaximumInteger()]

Method 2: Using Python Infinity

Positive Infinity in python is an undefined number which is greater than any other value in the program. To represent any number in a program that is higher than all other numbers in the program we can use the python Infinity.

The following code represents the above concept:

import sys
value=float('Inf')
print("1. Is value greater sys.maxsize? :",value>sys.maxsize)
print("2. Sorting list: [100,0,value,922337036854775808,sys.maxsize] in ascending order: ")
print(sorted([100,0,value,9223372036854775808,sys.maxsize]))

Output:

1. Is value greater sys.maxsize? : True 2. Sorting list: [100,0,value,922337036854775808,sys.maxsize] in ascending order: [0, 100, 9223372036854775807, 9223372036854775808, inf]

Disclaimer: As of now there is no way of representing python infinity as an integer value. However, since python float values can be used to represent an infinite integer. Hence int(float(‘Inf’)) will lead to OverflowError: cannot convert float infinity to integer.

You can read more about python infinity here.

Method 3: Using infinity.Infinity 

Another work around for obtaining the largest integer value is using Konsta Vesterinen’s all-in-one infinity value for Python which can be compared to any object. The only issue with this method is it does not inherit from int. To overcome this problem we can create a subclass and then make it inherit from int as given below:

from infinity import Infinity
import sys class IntInfinity(Infinity, int): pass print(isinstance(IntInfinity(), int))
obj = IntInfinity()
print("1. Is obj greater than sys.maxsize?", obj > sys.maxsize)
print("2. Sorting list: [100,0,obj,922337036854775808,sys.maxsize] in ascending order: ")
print(sorted([100, 0,obj, 9223372036854775808, sys.maxsize]))

Output:

True
1. Is obj greater than sys.maxsize? True
2. Sorting list: [100,0,obj,922337036854775808,sys.maxsize] in ascending order:
[0, 100, 2147483647, 9223372036854775808, inf]

Conclusion

It is important to note that integers in python are unbounded. Even the values of sys.maxsize depend upon the platform they are being executed upon as mentioned earlier. This means that sys.maxsize + 1 > sys.maxsize. The proposed methods are probable workarounds for making an integer larger than any other integer in the program. 

I hope you found this blog article useful and it helped you. Stay tuned for future updates.

Posted on Leave a comment

Python One Line Replace

Problem: You use Python in a terminal and you want to replace a string 'example' in a text file file.txt:

xxxxx example xxxxx

Your goal is to accomplish the following text:

xxxxx replaced_example xxxxx

In particular, you want to open the file, replace the text, and rewrite the result into the file—all in a single line of Python code!

Can a Python one-liner accomplish this?

Answer: Yes! You can compress any Python script into a single line. For computer science nerds: the single line of Python code is Turing complete.

Let’s see how you can accomplish this task as a Python one-liner!

Method 1: Print to Standard Input

The first method is best if you want to replace all occurrences of "example" with "replaced_example" and print the result to the standard input.

python -c "print(open('file.txt').read().replace('example','replaced_example'))"

The replace method replaces all occurrences of the first argument with the second argument. It returns the new string. You can now print the result to the stdin or write it back to a file.

Method 2: Print to File

The second method is best if you want to replace all occurrences of "example" with "replaced_example" and write the result to a new file "file2.txt".

python -c "print(open('file.txt').read().replace('example','replaced_example'), file=open('file2.txt', 'w'))"

The replace method replaces all occurrences of the first argument with the second argument. It returns the new string. You can now print the result to the file with means of the file argument of the print function.

Method 3: exec()

You can always convert a multi-liner into a one-liner using the exec() function. Say, you have the following multiline script to replace all occurrences of a string in a file:

with open('file.txt', 'r') as f: s = f.read().replace('example', 'replaced_example')
with open('file.txt', 'w') as f: f.write(s)

You first open the file in read mode reading all its contents and creating the new string with replaced occurrences of the string 'example'. After that, you open the file in writing mode to overwrite its contents.

You use the exec() function to one-linerize this script:

exec("with open('file.txt', 'r') as f:\n s = f.read().replace('example', 'replaced_example')\nwith open('file.txt', 'w') as f:\n f.write(s)")

All you did is to replace the new lines with the new line character \n. This resulting script is a not-so-concise one-liner to replace all contents of a given file!

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

5 Evergreen Ways to Get Clients as a Freelancer

  • Create more Fiverr gigs and wait.
  • Apply for Upwork gigs proactively.
  • Contact business owners via email and offer your valuable services AFTER providing them some value.
  • Use content marketing to build a community and sell your services to them.
  • Create your scalable advertising funnel (e.g., Facebook Ads, Google Ads, Pinterest Ads).

To create your thriving business as a software developer online, consider purchasing my in-depth program “How to Become a Python Freelancer”!

Posted on Leave a comment

Python One Line Regex Match

Summary: To match a pattern in a given text using only a single line of Python code, use the one-liner import re; print(re.findall(pattern, text)) that imports the regular expression library re and prints the result of the findall() function to the shell.

Problem: Given a string and a regular expression pattern. Match the string for the regex pattern—in a single line of Python code!

Example: Consider the following example that matches the pattern 'F.*r' against the string 'Learn Python with Finxter'.

import re
s = 'Learn Python with Finxter'
p = 'F.*r'
# Found Match of p in s: 'Finxter'

Let’s dive into the different ways of writing this into a single line of Python code!

Exercise: Run the code. What’s the output of each method? Why does the output differ?

Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.

Method 1: findall()

The re.findall(pattern, string, flags=0) method returns a list of string matches. Read more in our blog tutorial.

# Method 1: findall()
import re; print(re.findall('F.*r', 'Learn Python with Finxter'))
# ['Finxter']

There’s no better way of importing the re library and calling the re.findall() function in a single line of code—you must use the semicolon A;B to separate the statements A and B.

The findall() function finds all occurrences of the pattern in the string.

Method 2: search()

The re.search(pattern, string, flags=0) method returns a match object of the first match. Read more in our blog tutorial.

# Method 2: search()
import re; print(re.search('F.*r', 'Learn Python with Finxter'))
# <re.Match object; span=(18, 25), match='Finxter'>

The search() function finds the first match of the pattern in the string and returns a matching object

Method 3: match()

The re.match(pattern, string, flags=0) method returns a match object if the regex matches at the beginning of the string. Read more in our blog tutorial.

# Method 3: match()
import re; print(re.match('.*F.*r', 'Learn Python with Finxter'))
# <re.Match object; span=(0, 25), match='Learn Python with Finxter'>

The match() function finds the match of the pattern at the beginning of the string and returns a matching object. In this case, the whole string matches, so the match object encloses the whole string.

Method 4: fullmatch()

The re.fullmatch(pattern, string, flags=0) method returns a match object if the regex matches the whole string. Read more in our blog tutorial.

# Method 4: fullmatch()
import re; print(re.fullmatch('.*F.*r.*', 'Learn Python with Finxter'))
#<re.Match object; span=(0, 25), match='Learn Python with Finxter'>

The fullmatch() function attempts to match the whole string and returns a matching object if successful. In this case, the whole string matches, so the match object encloses the whole string.

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

Lost Your Sight? How to Code as a Blind or Visually-Impaired Python Developer

I’m a developer who is blind. I’ve been blind since very shortly after birth. I’ve never gone through losing my sight. I wanted to see if my perspective lined up with that of others who are blind, but have lost their sight later on in life. Here is what I found out:

I reached out to parts of the blindness community in my network to see if anyone wanted to sit down and talk to me about their experiences. Six people replied to my query for interviews. I interviewed three of them for this article, and I plan on talking to the others after this writing.

I run an email group where other people who are blind hang out called Pythonvis. Anyone else can join. I sent one query there. Another group I hang out on is called Program-l. That group is broader in scope. Both groups cater to the unique needs of those of us who are looking for both programming help and help using the tools necessary to use our computers.

Blind Developer Survey — Stories

Before he lost his sight, Jeff Thompson learned to program while in college, using punch cards. He went on to have a career in the insurance industry. It wasn’t until much older that he lost his sight. Jeff is a member of Pythonvis and runs a weekly Python coaching session on a site called Out-of-site.

Taylor Arndt studies Computer Science at Western Michigan University in the United States.

Vaibhav Saraf is a software developer from India who lost his sight a little over a year ago.

All three told me that they went through a period where they were despondent about being unable to use their computer, but reached out and learned that they had a way out.

How They Use Their Computer

All three developers use software called screen readers. Screen readers speak what the user types into the computer and read what they want to know about the code they write.

Interestingly, the original IBM screen reader software was invented by Jim Thatcher, who was not blind, but was influenced by his blind thesis advisor. Ted Henter, who lost his sight in a car accident, invented the most popular screen reading software, JAWS, after he lost his site and went on to co-found FreedomScientific (https://www.freedomscientific.com/), which has since become part of the Vispero group of companies. They also all use NVDA, which was created by two blind developers.

NVDA is mostly written in Python and is open-source. One of the reasons I am learning Python is to contribute to that project.

Programming Tools

Jeff uses EdSharp, written in C# by Jamal Mazrui, himself a blind software developer, who works for Amazon.

Taylor and I use Visual Studio Code, which has very strong support for those of us who use screen readers.

Vaibhav uses Eclipse, which IBM contributed much code to enhance its ability to work with screen reading software.

[Resources] How They Learned Python

When I asked how they learned Python, they pointed me to resources, such as:

  • Bookshare, a site that houses many books on both fiction and non-fiction subjects, including Python development.
  • Professors and team leads who provided them with material in HTML or PDF tagged so that it is able to communicate with screen reading software through accessibility tags similar to HTML, which communicates information about the structure of the documents, such as which elements are headings, tables, form fields, and so on.
  • FreeCodeCamp.org which is a non-profit group that teaches full-stack web development, which has recently branched out into a section on Python.
  • W3Schools, which also has a Python curriculum.
  • The official Python tutorial
  • Various other free resources on the web, some books, others forums.

All of the above have in common that they are written in a form easy to consume by screen readers: HTML, DAISY, or EPub.

How They Communicate On Projects

All three said that email is something that is easy to use with screen reading software. They also all use Skype, Microsoft Teams, Zoom, or other communication software. All of these packages work with screen reading software.

Taylor and Vaibhav use Microsoft Word, so any specifications or instructions written as Word documents that have adequate text descriptions can serve as specifications for projects. Taylor and Vaibhav told me that wen professors or team members present course materials live that when they point to something on the board or when screen sharing that it helps to say the name of the thing they are pointing too, rather than “this,” or “Click this.”

It also helps to give directions on where to find something or perform an action to help build a mental model of the thing they are describing. At this point, screen reader users can share screens as presenters in communication software, but screen readers cannot communicate to the user the screens shared by others who are presenters. One way to off-set this disadvantage is to get the material before the presentation so they can read it over and become familiar with it.

How They Understand Program Structure

All three told me that they use their screen reader’s ability to communicate the number of tab characters appear at the beginnings of lines coupled with the colon characters at the beginnings of conditional expressions, loops, classes, and methods to gain a mental model of the code they work with. As we talked about this, Vaibhav said that he depends on his memory a great deal to understand code flow.

Screen readers can read a line at a time, a word at a time, and a character at a time, and if a developer is able to obtain a Braille display, they can read and follow indentation by using their fingers to feel the dots.

Another helpful tool to gain the understanding of program structure is the previews in Eclipse and Visual Studio Code that list symbols in outline form.

These conveniences for people who are sighted are essential for screen reader users in gaining efficiency, because they cannot glance down through a screen all at once and gain a quick overview of what the code or reading material may communicate. EdSharp also has a way to jump among symbols.

What It’s Like Working With Other Team Members

All three said that once those around them become familiar with their disability that they have no issues communicating and working efficiently with others.

They said that others are generally very willing to adapt their working style.

All three say that they are able to pull their own weight as equal contributors to projects. When it comes to working on open-source projects or any that involve using Git and sites like GitHub, command line Git works well with screen readers, because it uses pure text and screen readers and command line environments are good friends.

Advice For Would-Be Programmers

I asked all three what advice they would give to anyone who is blind who would like to go into programming. Points mentioned were:

  • This is something you can do if you really want to. You can reach out to forums such as Quora, Stack Exchange, Reddit, etc. and find others in your situation. There are email groups, such as Python-vis, Blind Programming, and other lists that specialize in one language or another where blind people hang out.
  • You need to learn to use your screen reader to the fullest extent possible and to do all you can to make yourself as efficient as possible using the keyboard and the tools at your disposal.
  • Take advantage of the communities around your chosen screen reader.
  • You may need to use alternative tools or methods to do your job more efficiently. Speak up when you need to do this.
  • Keep looking for more efficient ways to accomplish tasks.
  • There is enough reading material on the web to enable you to get good at Python.
  • Don’t get hung up because someone gives you material you cannot read or understand. Find material on the same subject from somewhere else.
  • You will often find yourself in a situation in which you cannot read something or use some aspect of a piece of software. When reporting bugs, stick to the facts, be tactful, keep your emotions out of the conversation. Most people want to help, once they understand where you are coming from.
  • You will need to work harder than the people around you and be patient while they come to grips with your disability. This is a given.
  • Rely on your network of supporters, your faith, meditation, or whatever helps you gain positive energy.
  • There will always be well-meaning people in your life who will tell you that you cannot do this. Smile and do it anyway.

To that I say Amen.

About the Author

Jim Homme is a former professional musician, father of three, husband, and a 32-year veteran in Information Technology. He loves to read and play chess. He leads a team of accessibility testers at Bender Consulting Services. He is the owner of jimhomme.com, where he writes about Python and related technologies.

Posted on Leave a comment

Python Infinity

Infinite “∞” is a term derived from the Latin word infinitas which means “without an end” or “boundless”. Similarly, infinity in python is an undefined value that can either be positive or negative. It comes in handy for measuring and optimizing complex algorithms. 

The positive infinity is used to denote the greatest of all values while the negative infinity is used to denote the least of all values.

Until now there is no way to represent infinity as an integer. However, in python float values can be used to represent infinite integer values. 

Let’s explore the ways Infinity can be used in python:

Method 1: Using float(inf) and float(-inf)

Infinity can be a positive or negative value and can be represented by float(inf) and float(-inf) respectively. 

The following code demonstrates the implementation of positive and negative infinity:

infinity_positive = float('Inf')
number = 9999999999999999999999999
if number > infinity_positive: print("number is greater than Infinity!")
else: print("Positive Infinity is the greatest! Even greater than",number) infinity_negative = float('-Inf') if -number < infinity_negative: print("number is lesser than Negative Infinity!") else: print("Negative Infinity is the least! Even smaller than",-number)

Output:

Positive Infinity is the greatest! Even greater than 9999999999999999999999999 Negative Infinity is the least! Even smaller than -9999999999999999999999999

Method 2: Using the “math” Module

Python’s math module can also be used to implement infinity. In Python 3.5 and higher math.inf is a predefined constant that is used to return positive infinity while -math.inf constant returns negative infinity. It returns a floating value.

The following code demonstrates the implementation of infinity using the math module:

import math
infinity_positive = math.inf
number = 9999999999999999999999999
# Positive Infinity
if number > infinity_positive: print("number is greater than Infinity!")
else: print("Positive Infinity is the greatest! Even greater than",number)
# Negative Infinity
infinity_negative = -math.inf
if -number < infinity_negative: print("number is lesser than Negative Infinity!")
else: print("Negative Infinity is the least! Even smaller than",-number)

Output:

Positive Infinity is the greatest! Even greater than 9999999999999999999999999 Negative Infinity is the least! Even smaller than -9999999999999999999999999

Method 3: Using the “decimal” module

Another way of implementing infinity is by using Python’s decimal module. Decimal(‘Infinity’) returns positive infinity while Decimal(‘-Infinity’) returns negative infinity.

The following code demonstrates the implementation of infinity using the math module:

from decimal import Decimal
infinity_positive = Decimal('Infinity')
number = 9999999999999999999999999 # Positive Infinity
if number > infinity_positive: print("number is greater than Infinity!")
else: print("Positive Infinity is the greatest! Even greater than",number) # Negative Infinity
infinity_negative = Decimal('-Infinity')
if -number < infinity_negative: print("number is lesser than Negative Infinity!")
else: print("Negative Infinity is the least! Even smaller than",-number)

Output:

Positive Infinity is the greatest! Even greater than 9999999999999999999999999 Negative Infinity is the least! Even smaller than -9999999999999999999999999

Method 4: Using the “Numpy” library

Another popular way of implementing Infinity in python is by using Python’s famous Numpy library. Numpy has its own definitions for infinite values. np.inf returns positive infinity while -np.inf returns negative infinity.

The following code demonstrates the implementation of infinity using the math module:

import numpy as np
infinity_positive = np.inf
number = 9999999999999999999999999
# Positive Infinity
if number > infinity_positive: print("number is greater than Infinity!")
else: print("Positive Infinity is the greatest! Even greater than",number)
# Negative Infinity
infinity_negative = -np.inf
if -number < infinity_negative: print("number is lesser than Negative Infinity!")
else: print("Negative Infinity is the least! Even smaller than",-number)

Output:

Positive Infinity is the greatest! Even greater than 9999999999999999999999999 Negative Infinity is the least! Even smaller than -9999999999999999999999999

Infinity Arithmetic

Generally, most arithmetic operations performed on infinity values result in generation of other infinite values. The following example illustrates this concept :

value = float('inf')
print('Result of Addition : ',value + 15)
print('Result of Subtraction : ',value - 15)
print('Result of Multiplication : ',value * 15)
print('Result of Division : ',value / 15)
#special scenario
print('Multiplication by Zero: ',value * 0)

Output:

Result of Addition: inf
Result of Subtraction: inf
Result of Multiplication: inf
Result of Division: inf
Multiplication by Zero: nan

Note:

  • Division by zero raises a ZeroDivisionError exception instead of yielding a resultant value.
  • Arithmetic operations on NaN always give NaN. There is no “negative NaN”.

Python Infinity Check

The isinf() method of the math module is used to check for infinite values in python. The following example demonstrates this concept :

import numpy as np
import math
num1 = np.inf
num2 = -np.inf
num3 = 25
print("Is num1 an infinite number?: ",math.isinf(num1))
print("Is num3 an infinite number?: ",math.isinf(num2))
print("Is num2 an infinite number?: ",math.isinf(num3)) 

Creating Arrays with Infinity values

The following example demonstrates how an array of infinity values can be created:

import numpy as np
# To create a numpy array with all values initialized to infinity
array_infinity = np.full(5, np.inf)
print('Infinite Array: ',array_infinity) 

Output:

Infinite Array: [ inf inf inf inf inf]

Test your knowledge based on the above explanations:

What will be the output of the following snippets?

Answers: Run the code to get the answers!

Conclusion

Infinity is majorly used in complex algorithmic designs and optimization problems. One such example is the Shortest Path Algorithm where the current distance values have to be compared with the best or the least distance values.

I hope you found this blog article useful and it helps you to get started with the fundamentals of Python Infinity!

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

5 Freelance Developer Tricks to Build a Sustainable Business

Do you want to thrive as a self-employed Python freelancer controlling your own time, income, and work schedule? Check out our Python freelancer resources:

Finxter Python Freelancer Course:
https://blog.finxter.com/become-python-freelancer-course/

Finxter Python Freelancer Webinar:
https://blog.finxter.com/webinar-freelancer/

Book: Leaving the Rat Race with Python (Pre-Release):
https://blog.finxter.com/book-six-figure-freelance-developer/