Categories
Tips

11 Tips And Tricks To Write Better Python Code

Here are 11 tips and tricks that will help you write better Python code and become a better programmer:

1. Iterate with enumerate instead or range(len(x))

In Python, we generally use a for loop to iterate over an iterable object. A for loop in Python uses collection based iteration i.e. Python assigns the next item from an iterable to the loop variable on every iteration. The usual usecase of a for loop is as follows:

values = ["a", "b", "c"]

for value in values:
  print(value)

# a
# b
# c

Now, if in addition to the value, you want to print the index as well, you can do it like this:

index = 0

for value in values:
  print(index, value)
  index += 1

# 0 a
# 1 b
# 2 c

or another common way to do this is by using range(len(x)):

for index in range(len(values)):
  value = values[index]
  print(index, value)

# 0 a
# 1 b
# 2 c

However, there is an easier and more pythonic way to iterate over iterable objects by using enumerate(). It is used in a for loop almost the same way as you use the usual way, but instead of putting the iterable object directly after in in the for loop, or putting using it as range(len(values)) , you put it inside the parentheses of enumerate() as shown below:

for count, value in enumerate(values):
  print(count, value)

# 0 a
# 1 b
# 2 c

We can also define a start argument for enumerate() as shown below :

for count, value in enumerate(values, start=1):
  print(count, value)

# 1 a
# 2 b
# 3 c

The enumerate() function gives back two variables:

  • the count of the current iteration
  • the value of the item at the current iteration

Just like the loop variables in a for loop, the loop variables can be named anything, for instance, we can call then index and value and they’ll still work. enumerate() is more efficient than a for loop as it saves you from the hassle to remember to access the value inside the loop and use it correctly and then also remember to advance the value of the loop variable, it is all handled automatically by Python.

2. Use list comprehension instead of raw for loops

List comprehension is an easier and elegant way to define an create lists based on the existing lists. They are just a single line of code consisting of brackets containing the expression that is repeatedly executed at each iteration. Hence, they are more time and space efficient than loops and transform iterative statements in a single line of code.

The usual syntax of a list comprehension looks like this:

newList = [ expression(element) for element in oldList if condition ] 

Here’s an example of list comprehension in code:

# Using list comprehension to iterate through loop
List = [character for character in 'HackerNoon']
 
# Displaying list
print(List)

# Output
# ['H', 'a', 'c', 'k', 'e', 'r', 'N', 'o', 'o', 'n']

3. Sort complex iterables with sorted()

The Python sorted() function sorts the elements of an iterable object in a specific order (ascending or descending) and returns them as a sorted list. It can be used to sort a sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator.

The syntax of the sorted() function is as follows:

sorted(iterable, key=None, reverse=False)

sorted() function takes at max three parameters:

  • iterable: It could be any iterator
  • key: It is an optional argument that serves as a key for sort comparison.
  • reverse: It is also an optional argument that is used to specify a reversed sorted list as the output

4. Store unique values with Sets

A Python Set stores a single copy of the duplicate values into it. Hence, it can be used to check for unique values in a list. For example:

list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 

set_res = set(list_inp) 
print("The unique elements of the input list using set():\n") 
list_res = (list(set_res))
 
for item in list_res: 
    print(item)

So the output of the above program would look like this:

The unique elements of the input list using set():

25
75
100
20
12

5. Save memory with Generators

The basic function of the generator is to evaluate the elements on demand. It is very similar to the syntax for list comprehension, where instead of square brackets, we use parentheses.

Let’s consider an example where we want to print the square of all the even numbers in a list:

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:", myList)
mygen = (element ** 2 for element in myList if element % 2 == 0)
print("Elements obtained from the generator are:")
for ele in mygen:
    print(ele)

The output of the above code would look like this:

The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements obtained from the generator are:
4
16
36
64
100

Having said that their syntax is quite similar to list comprehension, you must be wondering how it is different from list or set comprehension. Unlike list or set comprehension, generator comprehension does not initialize any objects. As a result, you may utilize generator comprehension instead of list or set comprehension to lower the program’s memory requirements.

6. Define default values in Dictionaries with .get() and .setdefault()

.setdefault() method allows to set dict[key]=default if key is not already in dict.

The syntax of .setdefault() looks like following:

dict.setdefault(key, default=None)

Here’s an example code snippet to understand how to use .setdefault():

a_dictionary = {"a": 1, "b": 2, "d": 4}
a_dictionary.setdefault("c", 3)

print(a_dictionary)

The output of the above code would look like:

{'a': 1, 'b': 2, 'd': 4, 'c': 3}

The same thing can also be achieved by using .get() method by passing a default value for the key, as you can see below:

a_dictionary = {"a": 1, "b": 2, "d": 4}
print(a_dictionary.get("c", 3))

print(a_dictionary)

The output of the above code would look like following:

3
{'a': 1, 'b': 2, 'd': 4}

7. Count hashable objects with collections.Counter

The Collections module supports high-performance container datatypes (in addition to the built-in types list, dict, and tuple) and contains a variety of useful data structures for storing information in memory.

A counter is a container that keeps track of the number of times equal values are added.

It may be used to implement the same algorithms that other languages employ bag or multiset data structures to implement.

Import collections makes the stuff in collections available as:

import collections

Since we are only going to use the Counter, we can simply do this:

from collections import Counter

It can be used as follows:

import collections

c = collections.Counter('abcdaab')

for letter in 'abcde':
    print '%s : %d' % (letter, c[letter])

The output of the above code would look like this:

a : 3
b : 2
c : 1
d : 1
e : 0

8. Format strings with f-Strings (Python 3.6+)

f-strings, also called as “formatted string literals“, are a new and more pythonic way to format strings, supported by Python 3.6+. They are a faster, more readable, more concise, and a less error prone way of string formatting in Python.

As the name “f-string” says, they are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values at the runtime and then formatted using the __format__ protocol.

f-strings can be used as following:

name = "Eric"
age = 74
print(f"Hello, {name}. You are {age}.")

# 'Hello, Eric. You are 74.'

9. Concatenate strings with .join()

In Python, we can use the .join() method to concatenate a list of strings into a single string. The usual syntax for this method looks like below:

'String to insert'.join([List of strings])

It can be used in multiple ways — if you use the empty string ““, [List of strings] is simply concatenated, and if you use a comma, a comma-delimited string is created. When the newline character \n is used, a newline is appended after each string. See the example below:

l = ['aaa', 'bbb', 'ccc']

s = ''.join(l)
print(s)
# aaabbbccc

s = ','.join(l)
print(s)
# aaa,bbb,ccc

s = '-'.join(l)
print(s)
# aaa-bbb-ccc

s = '\n'.join(l)
print(s)
# aaa
# bbb
# ccc

10. Merge dictionaries with {**d1, **d2} (Python 3.5+)

The easiest way to merge dictionaries is by using the unpacking operator (**). The syntax for this method looks like this:

{**dict1, **dict2, **dict3}

Here’s an example to understand this method better:

d1 = {'k1': 1, 'k2': 2}
d2 = {'k3': 3, 'k4': 4}

print({**d1, **d2})
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}

11. Simplify if-statements with if x in list

Assume we have a list with the primary colours red, green, and blue. And somewhere in our code, we have a new variable with a colour, so c = red. Then we’ll see if this is one of our primary colours. Of course, we might check this against each item on our list as follows:

colors = ["red", "green", "blue"]

c = "red"

# cumbersome and error-prone
if c == "red" or c == "green" or c == "blue":
    print("is main color")

However, this may become quite time consuming, and we can easily make mistakes, such as if we have a typo here for red. It is more simpler and far preferable to just use the expression if x in list:

colors = ["red", "green", "blue"]

c = "red"

# better:
if c in colors:
    print("is main color")

Conclusion

Python is a widely used programming language and by using the above tips and tricks, you can become a better Python programmer.

I hope this article was helpful. Keep reading!

Categories
News and Resources Tips

Developer Certification Programs to help boost your career

You are finally ready to pursue your career as a developer. Well, a big fat congratulations to you! It’s high time your homework begins! Whatever you choose to become, it does require a sincere commitment of time, effort, and resources (e.g. developer certification programs). You will need to make some hard choices such as which programming language to kick off with (find out which are the top programming languages communities to look out for), or what development area to focus. Keep in mind that on average developers are involved in five sectors concurrently. However, on top of programming and coding skills you will also need to work on your project management skills. You also may need to dive into the Agile Manifesto

Can you guess how many software developers are there in the world? According to the most recent Global Developer Population report,  in the beginning of 2019 there were just under 19 million active software developers. Out of these, 13M are software professionals.

We have used our current methodology to produce estimates of the global developer population for the past four half-year periods. Each estimate was produced independently of the others. This reveals an increase in the developer population of 4.2M developers since mid 2017, or an annual growth that hovers around 20%.
We have used our current methodology to produce estimates of the global developer population for the past four half-year periods. This reveals an increase in the developer population of 4.2M developers since mid 2017, or an annual growth that hovers around 20%. This growth rate seems to be accelerating, although it is based on just a few periods.

Day in day out, the population is growing at over 20% annually. This means you need to stand out from the competition. Now before we proceed any further, we need to understand the value of developer certifications. Why are they important? Why is there so much hype on gaining certificates and investment done in training? The added value is pretty much substantial. And merits can be bifurcated into two categories: What value certificates bring to individuals? How they affect decisions made by organizations?

Value to individuals

  1. Professional credibility: This describes your future relationship between co-workers and supervisors. You demonstrate the fact that you have developed certain skills that need to be possessed to succeed. Also, you are willing to put all the time and effort that needs to get certified. 
  2. Personal Satisfaction: There are times when we feel like an expert. After several years of knowledge, we step into the workspace with confidence and end up asserting ourselves.
  3. Salary: An individual with more IT certifications has the potential to make much more than those with just one certification. Additional certifications are not a bad thing after all. 

Overall professional growth and career advancement require you to learn present and upcoming technologies and enhance the skills you currently possess. 

Value to organizations 

  1. Job requirements: With the continuous advancement in technology, there’s a need to have subject matter experts on new topics. 
  2. Filling skill gaps: According to many software development companies, skill gaps are can be put a strain and the best way through these, is extensive training. Of course, there is no denying the fact that certified employees can lead to greater productivity. They can increased workforce morale, as well as knowledge shared across the entire department.  
  3. Retention – Job satisfaction results in greater staff retention. Employees who feel fulfilled and satisfied from inside are less likely to pursue other employment.

It’s Time to make the right choice – Answer the following questions

  • What do I want to accomplish? 
  • What am I interested in? 
  • Have I done my homework yet? 
  • What resources should I consider using? 
  • What’s next? 

Further below you will find certain software developer certification programs that can surely aid you in boosting your career.

1. Microsoft (MTA): This certification, in particular, is crucial for high school and college students around. Right from web development to software development, mobile, gaming, and more, the program offers it all! It depends upon you whether you achieve certification on a single track or several. 

2. Microsoft Azure: I am pretty sure you must have come across this certification. After all it is one of the most highly recognizable in the IT industry. This certification in particular also has the potential to carry a considerable cachet. Furthermore, with Azure, you’ll build, manage, and deploy scalable, highly available, and performant web applications.

3. Oracle (OCP, OCM, OCE): Unlike others, Oracle offers numerous Oracle Java Certifications at several levels such as Associate professionals (OCP), Master (OCM), Expert (OCE). The professional-level certification typically requires you to have an OCP Java Certification for a programmer. Otherwise, you must have a Sun certified Oracle Java Certification for programmer credential as a prerequisite. Exams taken here are all multiple choice and some include scenario-based questions as well. Also, there is the option of Oracle certified professional MySQL course, for developers who write applications for MySQL database servers. Fortunately, this slot has no prerequisites but Oracle itself does recommend you take the MySQL for developer certification. This exam is single-level and focuses on practitioner-level skills in all aspects of developing MySQL applications: architecture, syntax, design, modification and the list goes on.  

4. Amazon Web Services (AWS): Amazon Web Series provides scalable cloud computing for creating web applications. Being an AWS certified developer means the associate level is for developers who design and run applications on the AWS platform. Also, here the credentials come with no prerequisites but that doesn’t mean you should take it lightly. You must take a multiple-choice exam on AWS fundamental, plus designing, developing, and deploying cloud-based solutions, security, and debugging.

5.  Salesforce: With the rise in Salesforce development companies, organizations are searching for professionals with this certification. Initially developed as one of the original providers of enterprise customer relationship management (CRM). It now focuses on many facets of enterprise cloud computing and applications. The company’s entry-level certification identifies developers capable to design as well as build custom applications and analytics using the Force.com platform. Salesforce recommends that you take the Building Applications with Force.com and Visualforce training courses to prepare for the exam. To achieve certification, you must pass an exam that covers application design, the Force.com platform, data modelling, user interface, logic, data management, reporting, and analysis. Next, you can move on to the Salesforce.com Certified Advanced Developer certification. This focuses on skills required to use Apex and Visualforce to build custom applications, create test plans and perform tests, and manage the development lifecycle and environments. The organization’s Developer certification is a prerequisite. 

6. Scrum: Another interesting developer certification course you must consider is in the Scrum alliance. For those new to the Agile Manifesto , Scrum.org  is a member-based organization. It promotes the use of Scrum through education, advocacy, and networking/collaboration. The entry-level Scrum Alliance certified Scrum Developer (CSD) certification targets developers who understand Scrum principles and have knowledge of specialized Agile engineering skills.  

7. Project Management: Last but certainly not least, the Project Management Institute. An organization that offers numerous software development related certifications including the PMI Agile Certified Practitioner (PMI – ACP). The cert recognizes developers with knowledge of agile project management principles, practices, tools, and techniques. All you require having is: 

  • 2000 hours of general project experience working on project teams, or an active PMP or pgMP certification
  • 1500 hours working on Agile project teams or with methodologies
  • 21 contact hours in agile practices

The exam covers agile tools, techniques, knowledge, and skills. PMI has a strong relationship with academia. You’ll find that many colleges and universities offering courses on its certifications include the PMI-ACP.

What other courses have you taken or are considering taking? Have you attended any physical courses lately?

Charles Richard, is a Business Analyst at TatvaSoft UK. Besides his profession, Charles likes to share some new and trending technical aspects. To know more about his leading software development company in London, please visit www.tatvasoft.co.uk

Categories
Tips

5 Challenges for a Freelance Developer

Thinking about becoming a Freelance Developer? Freelancing can provide overall freedom for you to decide your working hours and salary. Let’s go over some common challenges, pros, cons and trade-offs you may encounter choosing this career path. Hopefully, my experience will help you make an informed decision.

Challenge #1: Steady Income

A strong point in favour of a regular job is a steady income. As a freelance developer, you have to face reality. While there is no real cap to how much you can make, there will be peaks and troughs in your monthly income. 

High and low seasons won’t necessarily follow each other in fixed intervals. In other words, be prepared for long periods of low income especially during your first couple of years.

Pro Tips

Aside from the services you may provide, do your best to generate passive residual income. Maybe consider an app that sells revenue, unobtrusive ads on your website or even a channel on a streaming website. There are many options to choose from nowadays.

Save as much as you can when you are in the high season! Conduct yourself in a frugal manner and eventually, you’ll figure out how much you can add in your expenses without dipping into your savings. You can always use an app to help you manage your finances!

If you still live with your parents, do not rush to move out. Save as much as you can (and make sure to help your parents with the bills). When your savings and your base income are healthy enough, then plan accordingly to find your own space. As a freelance developer, you’ll have steady expenses but not a steady income. Getting involved in the finances of your home will give you firsthand knowledge of how things work. Even if you are fortunate enough and there is no need for you to assist in the household expenses, still offer to handle some of the bills, as this will be part of your learning process.

Challenge #2: Time Management

It’s in the name, Free-lancing! You are your own boss and you have total control over your time. This is a huge pitfall when it comes to freelancing. Indeed you can start your workday after 10 am but watch out. You may not be as productive as you’re hoping to be. Unexpected things come up. Your computer may break, your internet service may stop working and a number of other things could go wrong.

As developers, we pretty much get paid to figure things out and make them simpler and more accessible to everyone else. There are times when no matter how much planning you put into it, the beautifully crafted algorithm will not work and it doesn’t have to be a syntax error. It might be something far more insidious than that. For instance, back in 2006, I was working on an HTML project and wanted to track the checkboxes that were not checked by the user once a form was sent. It took me days to realize that unchecked checkboxes are simply not posted when the form is submitted. As simple it may sound, this was one of those things that you learn from a painful and time-consuming experience.

Pro Tips

Discipline is key for proper time management. Learn how to say “NO” when you have to. You love solving problems and helping people, I get that. However, don’t forget that your freelancing career is only as serious as you take it and your clients can sense that from a mile away. 

Set a working schedule for yourself and stick to it. It might not be easy but it will be totally worth it. If you have a strong reason to miss work, at least make sure you have some wiggle room to make up for that time. 

One tip to always keep in mind: Watch out for the holiday season. If you choose so, holidays may not limit your capacity to work but will probably limit your clients’ availability to answer your phone calls or emails, should you need anything from them.

*** Time Management is closely connected to productivity but we’ll cover that further in challenge #4

Challenge #3: Deliverables

Developers are responsible for solving problems. Many times very simple problems but others very complex ones. Your capacity to deliver such solutions will determine how successful you may be. Clients will do their best to communicate their needs to you. More often than not they will fail at getting their point across. Pay attention to every detail,- the context of the problem, the scope of the problem- and try to connect the dots between what they say, what they mean and what you understand.

Clients will do their best to communicate their needs to you. More often than not they will fail at getting their point across. Pay attention to every detail,- the context of the problem, the scope of the problem- and try to connect the dots between what they say, what they mean and what you understand.

Pro Tips

Be honest with your clients. If you can’t deliver a solution, let them know. You are not required to know everything. Mutual trust is something built over time and if you feel that -while you are not an expert in a subject- you may conquer the learning curve to deliver the solution, communicate it to your clients.

Communication is key. If a client hasn’t heard from you in weeks they may think that you have abandoned them. You do not need to email or contact them every day, but often enough to keep them up to date with the ongoing process of the contracted work.

Challenge #4: Being Productive as a Freelance Developer

This happens to be one of the toughest things to keep up with as a Freelance Developer.  It depends a lot on overcoming the previously mentioned challenges. Many times your productivity will peak when you need it the least (low season for example) and fail you when you need it the most.

In reality, this is a challenge for everyone, even people with steady full-time jobs. It puts extra weight and stress on a Freelance Developer because you’ll need to handle everything on your own, even more so at the beginning. You need to be your own boss, accountant, assistant, supervisor, public relations expert, customer support, and so many more. Say NO to yourself when you want to say YES, can be soul tempering as much as it can be disappointing, but it is critical.

Pro Tips

The road to a productive day is an exploratory journey. Know yourself, balance how much you demand and how much you reward yourself, do your best to be the boss you wish you had but also the employee you wish to have. Don’t forget to exercise, eat well, sleep and keep an eye on your health as your body and mind are the most important tools for you to provide your services. 

We tend to use our computers for everything we do: work, watch series and movies, play or stream games, catch up with friends and family, read and anything else possible., etc. I did it for a long time until I got my hands on an old console and noticed how much more productive I got. Separate these things. When your computer is your go-to for everything, you’ll want to play when it’s time to work and vice-versa. There’s nothing wrong with playing video games in an old console, reading an old book or switching to an old e-reader. Don’t let the trends make you waste money and time you don’t have. Every cent and every minute counts.

Challenge #5: Keeping up with the Industry

A new Javascript framework is born every day. Keeping up has to do with learning new things as it has to do with discerning which things are worth learning. Depending on your choice of stack or target for software development this can be very complicated and time-consuming.

Desktop, Web or Mobile, each have their own set of programming languages, database choices, architectures, distribution systems, update cycles and so much more.

Pro Tips

Choose a single target first and mature in it. Try to be a shark, a horse or an eagle, never a duck, yes the duck can fly, swim and run but never as good as the ones mentioned above. Master one domain before adding a second one. Trends can be very misleading, so be careful. Just because everyone loves or hates the “new” thing, that doesn’t mean you should do too. 

Be critical, read, compare, test, research and make informed decisions – at the end of this article, you’ll find some indicative useful links of sites and tools for that.  You’ll find an outstanding feeling of realization and meaning when you take your algorithms and carefully improve them, remember there’s nothing wrong with making mistakes. In reality, this is a core part of a healthy learning process. However small the step forward it may seem, it’s still a step forward. Code bases and apps are improved in tiny percentages in different areas which add up to a much larger percentage of improvement. 7% Faster on the client-side, 12% faster on the server-side, 16% faster and better-indexed queries switching png icons for SVG’s, removing unused assets and before you know it, your website, web-based or mobile app can be much faster and deliver a much better overall experience.

Conclusions from the Life of a Freelance Developer

As a freelance developer your path can be very rewarding and fulfilling as long as you always do your best. Even if getting the job done might not be enough sometimes, you will still have the certainty that you gave it your 100%. This will soon add up to your advantage.

The beautiful process of learning a new skill and putting it into practice, giving life to an idea, watching it unfold is pure science. This will provide you with a real and palpable sense of achievement and purpose. You start with a simple “hello world” in your first programming language and as you progress it gets more difficult but more interesting as well. Trial and error, you learn, you grow, you overcome or fail. Do it every day, code a little and become more competent.

The dynamics between the known, the unknown and the threshold you cross to narrow that gap is what’s so engaging about the freelance developer lifestyle. Conquer yourself as you conquer new skills.

Useful sites for reading and researching:

Useful sites and tools for testing & benchmarking:

Short Bio: Darwin Santos is a Web Developer from the Dominican Republic and has been a member of the Developer Economics Community since 2017. He specializes in web-based ERP/CRM hybrids and health care systems. He has been working with web technologies since the early 2000s. Several of his deployments have been running for years and are constantly improved and updated. He is also very experienced in database design, data normalization and data migration, with several successful migrations of 20+ years worth of data under his belt. He prefers functional and procedural programming over OOP.

LinkedIn: https://www.linkedin.com/in/darwin-santos-3a5b4066/