Functions, Data Structures and Exception Handling In Python.

FUNCTIONS IN PYTHON

What are Functions?

Functions at the basic level are a set of instructions that take an input and return an output. An example is the “print” function. The print function is used to print a value or argument to the screen. The value is printed to the screen and is initially passed to the print function as an argument. It is also of importance to note that a Function is a modular piece of code that can be used repeatedly.

How to declare a function?

You declare a Function using the “def” keyword followed by the name and task to complete. Optional parameters can also be added after the function name within a pair of parenthesis.

Variable scopes

Scoping is a concept in Python that allows for you as a Developer to have greater control over elements in your code, which reduces the chances of accidental or unwanted damages. There are four types of scopes in Python. They are Local, enclosing, global and built-in. Together, they are referred to as LEGB. The importance of scopes is to protect the variable used in your code so it does not get changed by other parts of the code.

1)Local scope: This refers to a variable declared inside a function meaning the variable is local.

2)Enclosing scope: This refers to a function inside another function otherwise known as a nested function.

3)Global scope: This is when a variable is declared outside of a function meaning it can be accessed from anywhere.

4)Built-in scope: You use them when writing code. They are referred to as “reverse keywords”, such as print and def. It covers all languages of the Python programming language meaning you can access it from the innermost scope or outermost scope in the function class.

DATA STRUCTURES

Data structures are designed with the purpose of working with more complex information than small bits of data, such a collection of data like a comprehensive list of people, countries or companies. The import of a data structure is that it allows you to arrange and organize your data to perform or carry out operations on them permanently. There are four types of data structures. These are lists, tuples, dictionary and set. They are all non-primitive data structures and each data structure can be designed to solve a particular problem or optimize a current solution to make it more permanent.

LISTS

Lists are a sequence of one or more different or similar data types. It is essentially a dynamic array that can hold any datatype. You can create a list by typing for example my_list1 equated to the numbers 1, 2, 3, and 4 separated by commas in a bracket. A list can also contain various data types. When it comes to list, it is based on the index of an item. You can also create a nested list i.e a list inside a list.

How to print out a list?

To print out a list, there are a couple of different ways to do it. Firstly, you can use the star sign(*) [my_list1 = *] and secondly you can use the print function to output your list. Then click on Run.

How to add new items to your list?

The first option is use the insert function [my_list1.insert]. What it looks for is the index of where to insert to. The LEN function can be used to get the length of my_list1 and put what the next value should be. The second option is to use the append function. Here you don’t have to specify the index or where the items should be placed, you can just append your value. The third option is extend which will extend your list as well.

How to remove an item from your list?

1)Pop function: You can use the pop function to remove an item from your list then specify the index or location of which item i want to remove.

2)Delete or del keyword: For example, my_list1 = [0];. Always make sure to specify the index you want to delete.

You can also iterate through a list. You can iterate through the values and get access to large amounts of data.

TUPLES

Tuples are used as data structures and help to create solid, well performing code. To declare a tuple, you declare a simple variable, give it a name of your choice, and then type equals to and then the tuple itself within parenthesis. You can also declare a tuple without the parenthesis but it is best to use a parenthesis. Tuples are also based on index so you can use the same methods used for list to get access to items in a tuple. A Tuple can accept a mix of data types ranging from integers, string or boolean all at once. The one key difference of a tuple over a list is that tuple values are what we call immutable.

SETS

Set is another form of Data Structure which can help with storing certain types of data in different types of format. To declare a set, you start by declaring a simple variable and then use curly braces to define the set itself. The value then goes inside the curly braces. To add to your set, you use the add function. For example: set_a.add(6). To remove or delete an item from your set, you use the remove or discard function. You can also use the “union join” to join two sets together, merging them as one. Another operation is the “intersection”, using the intersection will get back all the items in set1 and set2. Yet another operation is the “set difference” which gives back all the elements that are in set1 and not in set2. The last operation to be mentioned here is “symmetrical difference” which gets back all elements that are present in set1 or set2 but not in both sets. Set is a collection with no duplicates but it is also a collection of unaltered items. It is not a sequence and as such does not contain an ordered index of elements.

DICTIONARIES

A Dictionary in Python in many ways is similar to how an actual dictionary works. When using a normal dictionary, you have to look up the first letter of the word you want to locate and then use the alphabetical ordering system to find it. That is the same way a Python Dictionary is. They are optimized to retrieve values. They do not access values based on index position but rather on keys. This key is then assigned a specific value called key-value pair. This makes them faster and more flexible in operation. The importance of using a dictionary over a list is that it is much more faster than using a traditional list. To find an item in a list, you need to keep reviewing the list until you locate the item but in a dictionary, you can go straight to the item you need by using its key-value pair. You can also replace one item with another in a dictionary, you just need to use the key to reference it while using the assignment operator to assign the value. You can delete using the del function. You can also iterate through a dictionary using three different methods which are standard iteration method, the items function or the values function.

ARGS AND KWARGS

Args can be used to pass in any amount of non-keyword variables and kwargs or keyword args can be used to pass in any amount of keyword arguments. Using these has the advantage that you could pass in any amount of non-keyword variables and keyword arguments.

Errors

Errors are repulsive coding and they happen for many reasons. There are two types of errors in Python which are syntax error and exceptions. Syntax errors are caused by human error while exceptions are known errors that need to be handled. Syntax errors are usually caused by the developer while coding. It could be as a result of misspelling or typographical error in code. This type of errors however have minimal effects or impacts because most IDE’s like VSCode will warn the developer and give them clues to fix them. You must note though that the more you learn and practice, the less you will deal with this type of errors because you will become better at creating and analyzing your code.

Exceptions are errors that happen during code execution and can easily go unnoticed by the developer but exceptions need to be handled. For example, your code can be syntactically correct but if it attempts to run something like five divided by zero which mathematically does not make sense, the exception ZeroDivisionError exception is thrown.

Exception Handling

You handle exceptions using the the try and except statements. You simply type try with a colon on the first line and except with a colon on the second line. You add the code you want to run within the try statement and in the except statement, you add your own error message, it could be “something went wrong”, then click on Run. The try error will try and execute the code that you added inside it. If an exception occurs, it will trigger the except line and execute the code in the except statement. Using this method of handling your exceptions makes the exception statement more specific and not like cryptic messages.

File handling

As a Developer, you will definitely work with large amounts of data and that is why file handling is important. File handling makes working with large amounts of data easier. It includes opening, reading and writing files among other operations. In Python, there are two file handling functions, open and close.

Open function accepts two arguments. The first is the file name and or the file location and the second argument is the mode. The mode indicates what action is required such as reading, writing or creating. It also specifies the type of format you want the file output to be in whether text or binary. The close function on the other hand is used for closing the open file connection.

How to specify the type of file handling in Python?

In Python, the default format for file handling is text. So just passing in any mode for reading or writing a file will automatically set it to a text format. To set or change the file handling to binary, you need to pass the letter b along with either the read or write option.

Reading files

Python offers several built-in functions that makes reading your files easier. The three methods are read, readline and readlines. The read method returns the entire content of the file as a string that will contain all the characters. An integer can also be passed to return only the specified number of characters in the file.

The second method is readline. The readline function returns a single line as a string. For example, if you have a line with three line of texts that says first line, second line and third line. The readline function will return only the first line of text i.e first line as an output. It is used to output a specific line of text. The readline function can also include an integer argument for returning a specified number of characters on a single line. For example, if you pass an integer of 15, your output will be the first 15 characters of the first line.

The third method is the readlines function. The readlines method reads the entire content of the file and then returns it in an ordered list which provides a way for you to iterate over the list or pick out specific lines based on a condition.

In this article, we learnt about functions, variable scopes, data structures, lists, tuples, sets, dictionaries, errors, exceptions and how to handle files. These are all very essential in impacting your journey to working with Python. I do hope then that you make the most of this article and practice as you learn.

Olamide Ayeni

Share
Published by
Olamide Ayeni

Recent Posts

Building A Message Board App With Django

Introduction In this article, we shall use a database for the first time to build…

6 days ago

Building A Two Paged Web Application Using Django

Introduction In this article, we will build a pages app that has a homepage and…

2 weeks ago

Creating Your First App In Django

When you say you want to use Django, it means you want to build a…

3 weeks ago

Creating Your First Project In Django?

Introduction Django is a high level Python framework that encourages rapid development and clean, pragmatic…

4 weeks ago

Django Setup For Windows

Django Setup To work with Django, we have to install Django first. Now when you…

4 weeks ago

Why Choose Django When There Are Other Frameworks For Python?

Why choose Django when you have other frameworks for Python? Django, Django, Django. When it…

1 month ago