Multimatics
Insight Hero Background

Insight

Let's Practice with Python Fundamentals (Part 2)

Let's Practice with Python Fundamentals (Part 2)

Friday, 26 April 2024

This article is the second part of previous article that still discussing about python fundamentals. You will know enter a more complex of python fundamentals divided into how to deal with exceptions in python and the introduction of Object-Oriented Programming (OOP).

The Ways to Handle Exceptions in Python

In general, a Python script raises an exception during an execution of a program that disrupts the normal flow of the program instructions. Exception shall be handled immediately or otherwise, Python will terminate and quit. In Python, there are several code lines that can be used to test out whether a block of code is working to avoid errors while running the program or to raise a set exception if a condition is met.

First, use try and except block. Try block will let you test a block of code to search for errors while except can be used to handle the error. Try and except go in hand as in if and else statements. For example:

try:
    print(x)
except:
    print("An exception occurred")

An exception occured

*the try block will generate an exception since x is not defined. The except block will then be executed since there is an exception.

Then, define multiple exceptions by adding multiple excepts in the try except block. This is used to identify the types of error in the code, such as:

try:
    print(x)
except NameError:
    print("Variable x is not defined")
except:
    print("Something else went wrong")

Variable x is not defined

Next, you can use else in exception handling or add an else statement in try except block to make the program executes the block when there are no exceptions to be found.

try:
    print("Hello")
except:
    print("Something went wrong")
else:
    print("Nothing went wrong")

Hello
Nothing went wrong

After that, you can use finally block to execute a block whether there was an exception or not in the previous block.

try:
    print(x)
except:
    print("Something went wrong")
finally:
    print("The 'try except' is finished")

Something went wrong
The 'try except' is finished

*the program will not stop when an exception is raised and will still execute the finally block.

Lastly, a raise statement is used to throw exceptions if a condition is met. For example:

x = "hello"

if not type(x) is int:
    raise TypeError("Only integers are allowed")

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-bc91768a6271> in <module>
      2 
      3 if not type(x) is int:
----> 4 raise TypeError("Only integers are allowed")

TypeError: Only integers are allowed

*keep in mind that you will need to specify your desired type of error.

Learn how to process files and directories is one of the python fundamentals in data science. In Python, there are several built-in modules and functions that could be used for processing files and directories divided into os, os.path, shutil, and pathlib.

Moreover, there are also several common files and directories operations in python that broken down into: open and read files, create a directory, delete files and directories, copy files and directories, and move files and directories.

What is Object-Oriented Programming?

Object-Oriented programming (OOP) is a programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects. In other words, OOP is a method of structuring a program by bundling related properties and behaviors into individual objects.

Firstly, understand the classes. Classes are used to create user-defined data structures. It defines functions called methods that could identify the behaviors and actions that an object created from the class can perform with its data.

Secondly, build instances. While classes are the blueprint, an instance is an object that built from a class which contains a real data. For example, a class is a form, and an instance is a form filled out with information.

Thirdly, define the objects. An object is a unique instance of a data structure defined by its class. An object comprises both data members such as class variables and instance variables and methods.

Practice with Object-Oriented Programming

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

Then, create objects that is an instance of the class by adding two person objects such as:

john = Person("John", 25)
jane = Person("Jane", 23)

Lastly, we can then access the attributes of these objects by using dot notation:

john.name john.agee
'John' 25

Conclusion

From the two parts of Let’s Practice with Python Fundamentals articles, there are some python fundamentals that you could learn, ranging from the simplest such as python function and write code to process files and directories to the more complex one such as how to deal with exceptions and Object-Oriented Programming (OOP). By learning those python fundamentals, it is expected could help anyone who are aspired to dive into the world of data science.

Reference:

Lee, K. D. (2011). Python programming fundamentals. London: Springer.

Lutz, M. (2010). Programming Python: powerful object-oriented programming. " O'Reilly Media, Inc.".

Tutorials Point. Python – Object Oriented. January 29th, 2021. Retrieved From: https://www.tutorialspoint.com/python/python_classes_objects.htm