Samples of common python problems and their solution

Revision en7, by damianwolf, 2016-11-17 19:52:27

When it comes to Python, the first things that come to mind are simplicity and the ability to work seamlessly on complex projects. And, why not? Python is a high-level programming language created for the new generation of programmers who want to solve problems and not reinvent the wheel.

Python is an excellent choice for data scientists, web developers, and even game programmers. The wide range of uses enables Python to be one of the best programming languages available. It is also used extensively in teaching beginners on “how to code”. Platforms such as Livecoding.tv are seeing a surge in developers who are interested in broadcasting new projects using Python, especially to beginners.

Python is also ideal for Rapid Application Development because of the ecosystem surrounding the programming language. For example, Django, a Python Web Framework, offers rapid web development. There are also a large number of libraries you can use for Rapid Application Development.

Now, when it comes to Python, there are some common mistakes made by both beginners and experienced developers. If you visit live broadcasts, you can see many developers getting stuck on some of these common problems. These mistakes can only lead to time waste and, therefore, must be avoided. Knowing common pitfalls can make you a better Python developer, and helps you move your code to the next level. Let’s get started with some common Python errors that developers should know about.

Advanced: Python Scope Roles

If you have ever worked with Object Oriented Programming(OOP), you should have a good understanding of how Python Scope Resolution works. Python Scope works with a LEGB framework, where L stands for Local, E for Enclosing function locals, G for Global, and B for Built-in. You can read more about it here.

Python scopes are simple to understand but can be confusing when used with different data types. Let’s look at some examples to clearly understand the picture.

 var_one = 1

=> None   def var_test(): 

..   var_one +=1 

..   print (var_one) 

..   

=> None   var_test()

Traceback (most recent call last):

  File "python", line 1, in <module>

  File "python", line 2, in var_test

UnboundLocalError: local variable 'var_one' referenced before assignment

You might be surprised to see UnboundLocalError as you might think that var_one is already defined. However, it is out of scope when it comes to the var_test(). The only solution is to declare the variable within the function.

Similar kinds of behavior can also be seen when working on Lists. You can read more about them here.

Advanced: Creating modules that are already in Python libraries.

That’s one of the most common mistakes that developers make when naming their functions similar to already available functions in Python’s rich library.

If your code has a crypt function in your code, it is undeniably going to get into conflict with the standard library which provides an interface to the crypt(3) routine. The impacts get worse as it is used to check Unix passwords and acts as a one-way hash function.

To avoid the problem, you need to ensure that modules are named differently. This can easily be used to avoid conflict when importing libraries in your program, keeping app behavior as intended.

Beginner: Not doing proper indentation

Python indentation is different from other programming languages. For example, in Java, if the indentation is not maintained, the program will execute without any issues, but when it comes to Python, proper indentation is a must.

Let’s look at the following code.

def indentation_example():
    print "this will work \n"
    
indentation_example()
                                                       
sh-4.3$ python main.py                                                                            
this will work  

But, if you just miss the indentation inside the method, things will not work as intended.

def indentation_example():
print "this will work \n"
indentation_example()

sh-4.3$ python main.py                                                                            
  File "main.py", line 2                                                                          
    print "this will work \n"                                                                     
        ^                                                                                         
IndentationError: expected an indented block 

The indentation rules cannot be bypassed by using bracers, and hence care needs to be taken at all time. The best solution is to use any of the popular text editor or IDEs for Python such as Sublime Text or Pycharm. If you are curious about the indentation rules or want to see a style guide for Python, read PEP8, Style Guide for Python Code here.

Beginner: Enumeration

Another problem common among new time Python learners is confusing iteration and enumeration over a list. For the beginners it won’t be much of an issue, but for those who have worked with other programming languages such as Java and C++, things can get a little confusing.

For example, most programming languages have simple loop structure to go through a list or array in the below code.

for (int i=0; i<5; i++ ) { System.out.println(“Count is:” + i); }

Output: 0,1,2,3,4

However, Python array iteration can be different. In Python, you can go through each of the array elements without the help of the indices. Let’s take a look at an example.

  arr = [1,2,3,4,5]

=> None   

for each in arr: 

..   print (each) 

..   
 
1

2

3

4

5

Now if you want to use indices, you need to use the built-in enumerate function. This function takes a sequence and starting position as arguments.

arr = [5,6,7,8,9,10]

=> None   

for each in enumerate(arr): 

..   print (each) 

.. 
  
(0, 5)

(1, 6)

(2, 7)

(3, 8)

(4, 9)

(5, 10)

As you can see from the code above, each element is printed as a pair with indices and value as a first and second element. You can read more about enumerate function here.

Beginner:Working with Modules

Modules can be a tricky proposition to work with in the beginning. It’s easy to call methods, but when you are importing your own modules, things can become complicated. Let’s look at some example.

When you define a method, it looks like below.

#amodule.py

def a_module():

    print "5 \n"
  
a_module()

#prints 5 when called

Input: a_module()

Output: 5

Now, when you try to use the method in a different file, importing the amodule will result in an instant out of 5 which is not desirable in many cases.

>>> import amodule

5

If you want to avoid this common mistake, you need to call the method under the if name == ‘__main__’:

#amodule.py

def a_module():

    print "5 \n"

    
if __name__ == '__main__':

    a_module()

Now, when you import the a_module() method without executing it. It will only execute when it is executed explicitly.

>>>import amodule

>>>

Conclusion

Python is undoubtedly the most advanced programming language out there. It comes with a huge list of features which can easily confuse Python developers. This list is in no way exhaustive of all the common errors, but you can get an idea.

When it comes to understanding common developer habits, watching them code live can be a good way to learn. Learning from your own mistakes is one way to learn, but watching others make a mistake and rectify it can be much more valuable.

What do you think about the other common errors when developing with Python? Comment below and let us know.

Tags #python, samples, #coding

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en8 English damianwolf 2016-11-17 19:53:35 0 (published)
en7 English damianwolf 2016-11-17 19:52:27 75
en6 English damianwolf 2016-11-17 19:44:30 16
en5 English damianwolf 2016-11-17 19:43:00 178
en4 English damianwolf 2016-11-17 19:39:55 20
en3 English damianwolf 2016-11-17 19:38:45 70
en2 English damianwolf 2016-11-17 19:32:46 20
en1 English damianwolf 2016-11-17 19:31:20 8467 Initial revision (saved to drafts)