9 Python programming skills that distinguish a beginner from an experienced

Translation of the article prepared in advance of the start of the course “Python Developer”.


Python is a fantastic language. Its syntax is so simple that you don’t even have to look for an extra semicolon in your code. I would even say that Python is one of the best languages ​​for a newbie.

You start with an extensive set of libraries and add more and more to them as you gain experience in programming.

After a while, you may feel that you are stuck when it turns out that you wrote too much code for one simple operation. In fact, this is not as bad as you might think. Understanding the logic of what you are working on is much more important than the number of lines. Short code is better, but if the logic is broken, your code will not work as intended. But with experience and a creative approach to work, your code will become shorter and better.

Beginner or experienced?

So, what distinguishes a beginner from an experienced programmer when it comes to programming in Python?

In this article, I would like to focus on the following issues:

  • Problem solving and the art of asking questions
  • Understanding why code works (or not)
  • Work with strings
  • Work with lists
  • Using loops
  • Using functions (and proper terminology)
  • Object oriented programming
  • Respect for PEP

Problem solving and the art of asking questions

As a programmer, I’ll say that if you don’t have enough experience in solving problems, it will be difficult for you to start writing excellent code. If you have problems with solving problems, it will probably not be easy for you to find the best solutions to your problems. Programming is not just writing code. The problem-solving skill is the skill you will need to crawl out of the novice category.

Asking questions about programming is also very important. If you just ask someone to solve the problem for you, without trying anything, you are doing the wrong thing. This is not easy, but if you do not try to solve problems yourself, you will not get any benefit from someone else’s solution to your problem.

If you want to know how I formulate programming questions, here separate article about this.

Problem xy

“I need to get the last three characters in a string.”
“No, it doesn `t need! You need to get the file extension. ”

Problem XY is a very funny thing. You have a problem X, and when you call support, you ask about a problem Y, the solution of which, in your opinion, will solve the problem X. [1]

The case described above illustrates this situation well. If you want to get the file extension, then you can assume that you need the last 3 characters of the line.

What it might look like:

def extract_ext(filename):
    return filename[-3:]
print (extract_ext('photo_of_sasquatch.png'))
>>> png

Perfectly! Well, now try with photo_of_lochness.jpeg

The user could ask about the extension from the very beginning. Problem Y is the last three characters. Problem X is an extension.

def extract_ext(filename):
    return filename.split('.')[-1]
print (extract_ext('photo_of_sasquatch.png'))
print (extract_ext('photo_of_lochness.jpeg'))
>>> png
>>> jpeg

That’s all!

You can also use the standard library os.path.splitext().
You can familiarize yourself with it here.

Understanding why code works (or not)

When you’re new, you can grind a small piece of code for several days. And when this code suddenly starts working, you will feel relief and move on to the next part. And this is the worst thing you can do. Silently accepting that the code just works and not understanding why it works is probably even more dangerous than not understanding why the code doesn’t work in principle.

Not understanding why your code doesn’t work happens all the time. When you eliminate all the errors and finally find out why the solution did not work, it is very important to think about why it did not work and what ultimately made the code work correctly. You will carry this knowledge through all your programs.

For example, if you have an error indenting from the beginning of a line in code with several blocks, you can start moving blocks randomly, and then form when the program finally starts.
Remember that in most IDEs you can roll loops and if’S. So you can easily see which unit works for you and which does not.


ATOM with folded if-else constructs on the right

Another cool way to visually see how your code works is to www.pythontutor.comwhere you can see what is happening in your program line by line.


Code execution in pythontutors

Work with strings

The current section is not entirely about lines. It’s more about digging into the great Python libraries. In Python, we learn early that a string can be thought of as a list of characters. You can access a character in a string by index.

word = 'supergreat'
print (f'{word[0]}') 
>>> s
print (f'{word[0:5]}')
>>> super

An inquiring mind learns about what it offers str()but you can just keep writing without ever looking at the documentation str(). To call the function documentation you can write help(str) or dir(str). When you do this, you can find methods whose existence was not even suspected. You might have looked in the documentation and you know that strings have a method endswith(), for example, and you can apply it somewhere.


Here is an example of code that does the same thing in two different ways. The first option uses splitwhich we recently talked about. And in the second – endswith()which you could find in the documentation.

Most programmers will never read all the documentation and learn everything. An important part of a programmer’s job is knowing where to look for information on how to solve a problem.

Work with lists

Lists are a great and versatile thing.
For example, here we mix integer values ​​and strings:

my_list = ['a' , 'b' , 'n' , 'x' , 1 , 2 , 3, 'a' , 'n' , 'b']
for item in my_list:
    print (f'current item: {item}, Type: {type(item)}')

See how we mixed them. If we try to sort the list, we get an error.

print (my_list.sort())

What if we need to separate letters from numbers? The first way is to solve the problem using a loop in which we will check each element of the list. A beginner will get to know cycles early, because loops are an important part in programming.

The code may look something like this:

my_list = ['a' , 'b' , 'n' , 'x' , 1 , 2 , 3 , 'a' , 33.3 , 'n' , 'b']
number_list = []
string_list = []
for item in my_list:
    print (f'current item: {item}, Type: {type(item)}')
    if not isinstance(item,str):
        number_list.append(item)
    else:
        string_list.append(item)
my_list = string_list

This is the right approach, but a little cumbersome. The code works, but you can make it so that the problem is solved by the same method, but in one line!

If you want to be happier, learn how list expressions work in Python. Here is the same problem, but solved with an understanding of how lists work:

my_list = [letter for letter in my_list if isinstance(letter,str)]

That’s all!

And this is not the end. you can use filterto get the same result.

def get_numbers(input_char):
    if not isinstance(input_char,str):
        return True
    return False

my_list = [1,2,3,'a','b','c']
check_list = filter(get_numbers, my_list)
for items in check_list:
    print(items)

As you probably already understood, there are many ways to solve the same problem. You must be aware that it will work best specifically for you and your team.

Bonus

  • Flip a list (or line):

names = ['First' , 'Middle' , 'Last']
print(names[::-1])
>>> ['Last', 'Middle', 'First']

  • Combining list items:

names = ['First' , 'Middle' , 'Last']
full_name = ' '.join(names)
print(f'Full Name:n{full_name}')
>>> First Middle Last

Using loops

Have you met with similar code?

greek_gods = ['Zeus' , 'Hera' , 'Poseidon' , 'Apollo' , 'Bob']
for index in range(0,len(greek_gods)):
    print (f'at index {index} , we have : {greek_gods[index]}')

You will probably learn this construct from other languages, but this is far from Python’s approach. In Python you will use:

for name in greek_gods:
    print (f'Greek God: {name}')

You will quickly notice that there is no index. What if you want to operate on an index? In Python you can use enumerate. This is a great way to access everything you need!

for index, name in enumerate(greek_gods):
    print (f'at index {index} , we have : {name}')

Using functions (and proper terminology)

When I work on animation, I always say that if you do the same thing 5 times, then you need to think about whether you need a program? Sometimes, having spent two weeks developing a tool, you can save six weeks of work. When you write code and understand that you are doing the same action several times, you need to think about whether to code this code into a procedure or function. The function will return some value, and the procedure will simply execute the code. In the first example, you see the procedure, and in the second, the function.

It sounds confusing. Here is an illustration reflecting the principle of operation:

Pay attention to the difference between print and return. It might seem that they work the same way, but if you look at the output, you will see that the function will simply return the passed name.

The following terms that should be clearly separated are arguments and parameters. Parameters are what are defined in the procedure or function (highlighted in red in the figure), and what you pass to the procedure or function are arguments (highlighted in green).

Here are some examples.

Example 1

def print_list(input_list):
    for each in input_list:
        print(f'{each}')
    print() #just to separate output
greek_gods = ['Zeus' , 'Hera' , 'Poseidon' , 'Apollo' , 'Bob']
grocery_list = ['Apples' , 'Milk' , 'Bread']
print_list(greek_gods)
print_list(grocery_list)
print_list(['a' , 'b' , 'c'])

Instead of writing the cycle three times, I will write it once in the procedure and call it when I need it. And in the second example, you can see how the function returns an inverted list.

Example 2

def reverse_list(list_input):
    return list_input[::-1]
my_list = ['a', 'b' , 'c']
print (reverse_list(my_list))
>>> ['c', 'b', 'a']

Object oriented programming

Python is an object-oriented language, and there is a lot of power in objects. Think of an object as a drawing — if you use a drawing, you create an instance of it. So you can create as many instances as you want and do not ruin anything in the original drawing when you use them.

Object-oriented programming (OOP) is a huge topic, so this section does not contain everything you need to know about it, but we will talk about a few simple examples that will help you in your work.

If you have read about OOP before, you are probably tired of studying, but here it is again. Let’s start with the class definition. Student. He will have a name (name) and a list of disciplines (subject_list):

class Student():
    def __init__(self,name):
        self._name = name
        self._subject_list = []

Here __init__ Is a class constructor. It defines the core of the class. You will see later how the methods are added. Methods are procedures or functions belonging to a class that can be called when using the class inside the program.
If you want to create a student, you will create the following variable:

student1 = Student('Martin Aaberge')

If you need more students, you will use the same class and create a new object.

student2 = Student('Ninja Henderson')

AND student1, and student2 will be class instances Student. They have the same scheme, but they have nothing more in common. At the moment, we can do little with students, but we have added a list of disciplines. To populate this list, we will create a separate method. You can call methods to interact with class instances.

Let’s update the class:

class Student():
    def __init__(self,name):
        self._name = name
        self._subject_list = []
    def add_subject(self, subject_name):
        self._subject_list.append(subject_name)
    def get_student_data(self):
        print (f'Student: {self._name} is assigned to:')
        for subject in self._subject_list:
            print (f'{subject}')
        print()

Now this class can be used to create students, edit and get information about them.

#create students:
student1 = Student('Martin Aaberge')
student2 = Student('Heidi Hummelvold')
#add subjects to student1
student1.add_subject('psychology_101')
student1.add_subject('it_security_101')
#add subject to student2
student2.add_subject('leadership_101')
#print current data on students
student1.get_student_data()
student2.get_student_data()

Typically, classes are stored in separate files and imported into code. In our example, we created a class Student in file student.py and imported it into our file main.py. (In this case, both files are in the same folder).

from student import Student
student1 = Student('Martin')
student1.add_subject('biomechanics_2020')
student1.get_student_data()

Respect pep

You may often see people write Python code and don’t think about PEP at all. Perhaps I myself do this sometimes. When you work in a development environment, it is very important to follow the standards, if not the PEP standards, then at least the standards of your company.

PEP is a recommendation set for your code. Here is the link to PEP-8. Great reading. Read it at least once to understand what it is about. The classic example is snake_case. Variables in Python are written in snake_case, i.e. the words in the variable name are separated using underscores. Even at universities, they sometimes learn incorrectly, so don’t be discouraged, and just start writing by the rules.

That’s right:

chocolate_cake = 'yummy'

And here it is – no:

chocolateCake = 'Yummy'

Conclusion

Being a novice is amazing. Your path will not be easy, but your learning curve will be steep and give you a new experience! Stopping being a newbie can be difficult. Sometimes it’s hard to understand what you need to focus on. What will be the next step?

Maybe this article will push you in the right direction, or maybe for you it was just a bunch of random chatter that you already know. If you are not sure where to go next, do not be afraid to ask. Make sure you follow the advice of those who are more experienced than you. Be open to different opinions and find out what is right for you. If you are not ready to use certain ways of writing code, write in a way that is convenient for you until you learn new and better ones.

Sources:

[1] XY problem, en.wikipedia.org/wiki/XY_problem


Free lesson: Introduction to AutoTests


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *