Python for Absolute Beginners: Start Your Coding Journey Today!

Programming is both an exciting and rewarding profession and if you’re interested in building a career out of it, python programming could be a perfect start.

Python is one of the most popular programming languages. It is relatively easy to learn than most programming languages. Because it is beginner-friendly, it has become one of the preferred options for beginners.

In an annual developer survey conducted by StackOverflow in 2022, python was identified as one of the most popular programminglanguages.

Its versatility makes it a top choice for a wide range of applications, including web development, data science, and machine learning.

So, if you’re new to programming or learning Python as a second language, this guide will get you up to speed in no time.

You will learn:

  • The basics of Python programming
  • Data types and operators in Python
  • Program control flows
  • Functions, classes, modules and exceptions

What’s the essence of programming

Programming is a way of giving instructions to the computer to perform tasks.

Let’s say that you want to search for a file on your computer or want to send email messages to your customers. Doing this manually could be hard, but by writing a simple program in Python, you can instruct the computer to perform these tasks for you.

But then, you have to communicate with the computer in the language that it understands.

This language is called a programming language.

There are many programming languages available today, but Python stands out as a simple, elegant, powerful and multipurpose programming language that you can use for a wide range of programming tasks.

Python Programming language

Python is a general-purpose programming language. It was originally designed by Guido Van Rossum in the 1980s but released in 1991. It was named after his favourite show, Monty Python’s Flying Circus. By implication, python has nothing to do with reptiles often shown on textbook covers.

Python is an open-source programming language and is managed by Python Software Foundation (PSF). As an open-source programming language, you can access, modify, and distribute it, even for commercial purposes.

Python is an interpreted language, which means that you do not need to compile your programs before running them. Instead, the Python interpreter reads and executes your code, translating them into machine codes.

Python is also an object-oriented programming language, meaning you can organize your programs in classes and objects. Hence, you can write programs that are not only reusable but easy to maintain and update.

Why Python?

Python is used in diverse fields of study and industries for problem-solving and creating innovative software solutions.  So many projects have been successfully implemented with Python in the areas of sciences, education, health care, hospitality and entertainment.

Surely, there are lots of other programming languages with outstanding features, but Python stands out in the following ways.

Simple and easy to learn

One of the significant objectives of Python as a language is readability and ease of expressing concepts in fewer lines of code. The syntax is concise, clear and easy to read.

Programs written with Python are considerably shorter than the equivalents in programming languages such as Java and C++.

Python is not only easy to read but to learn. This makes it an ideal programming language for beginners.

Also, experienced programmers in other languages can easily pick it up and start writing programs with it.

The simplicity of learning Python explains why it is being used to teach children the principles of programming.

Versatility

One of the reasons behind the popularity of Python is that it is versatile. It can be used for a wide range of projects including web development, data visualization and analysis, game development and much more.

Many top companies across the world are either using Python or implementing a part of their application using Python. Companies like Google, Dropbox, Uber, Netflix, Bitly, Instagram and Youtube have used or are still using Python in their technology stacks.

Also, Python scripts can easily be integrated with applications written in other programming languages like Java, C/C++ and .NET languages, making it an excellent tool to glue together large software components.

Online Community

Python has a vast and supportive online community with lots of experienced developers willing to help as you journey into programming and beyond. There are also tons of educational resources available in the form of online documentation, forums, mailing lists, conferences around the world and even this blog.

These communities provide you with opportunities to connect with other programmers, facilitating the exchange of ideas and knowledge.

Efficiency

Productivity is of the essence to any programmer.  With Python, you can write more programs in a lesser period compared to most other programming languages.

In other words, it helps you do more with less time.

This not only makes you more efficient but also more productive.

As an interpreted language, you get an immediate result whenever you make changes in the program. There is no need for compilation and recompilation that is obtainable in compiled languages.

This explains why Python is used for rapid application development and as a tool for prototyping.

Extensive libraries

Python has vast libraries and third-party tools that can make things easier. Apart from the numerous standard libraries that come with Python, there are also myriads of powerful and tested third-party tools freely available at your disposal.

These are pre-written codes that solve a particular problem. With these libraries, you don’t have to reinvent the wheel as you can easily integrate these libraries into your program.

Some of the popular libraries in Python include Panda for data analysis, matplotlib for visualization, Sci-kit learn for machine learning and much more.

Installing Python

Python is free and can be downloaded from its official website. There are different Python releases for different operating systems, so be sure to download the latest stable version for your operating system.

Download and run the Python installer for your operating system. For Windows, download the .exe file; for Mac, download the .pkg file.

Follow the prompts to install Python on your system, making sure to check the option to add Python to your system path during installation.

On a successful installation of Python, typing the word python in your terminal or console will start the interactive session.

This will display the version of Python installed on your device followed by the chevron symbol (>>>) or three arrows indicating a line of input.

However, if it’s not installed on your device, you will get an error message indicating “command not found”.

While the interactive session running, you can give commands to Python and get the results immediately from the terminal.

This interactive session is also known as REPL, which stands for read, evaluate, print, and loop.

With REPL you can interact with the Python interpreter.

You can directly type Python codes and have them run immediately.

Lines that start with triple arrows are for inputs while lines without arrows are for outputs from the interpreter.

You can write some codes to perform some simple calculations and immediately after you hit the enter key, the interpreter will run the codes and display the result in the terminal.

Interactive prompt

To exit the interactive session, simply type CTRL Z.

Writing programs with the IDEs

The IDEs provide a convenient way to write programs and most of the code you will ever write will be done using this tool. Unlike the interactive session, any code that you’ve written disappears when you exit the session, IDEs allow you to save your programs in files

IDE stands for Integrated Development Environment. It is a graphical user interface that allows programmers to write, edit, run and debug and debug programs in one place.

There are so many IDEs you can use for programming in Python including Sublime Text, PyCharm, Visual Studio Code and even the IDLE that is shipped with Python Interpreter.

However, Visual Studio Code stands out as one of the most popular and widely used IDEs by developers. It runs on Windows, Linux and macOS.

You can get this software from the Visual Studio website for free.

Simply, download and install it on your computer.

Once you have installed Visual Studio Code, create a new file by choosing the “File” -> “New File” option.

IDE

Write your Python code in the editor provided by the IDE and save the file with a .py extension to indicate that it is a Python script or file.

Use the “Run” option to run your Python code in the IDE.

Python Syntax

Programming languages, just like natural languages (English, French, Swahili, Spanish, etc) are governed by grammatical rules or syntax.

Without adhering to these rules, it’s impossible to make meaningful statements in any language.

Just like grammar in natural languages, syntax is the rules that govern how you write programs in a programming language.

Interestingly, the syntax for Python is simple and this explains why it is beginner friendly.

Now, let’s look at the important syntax to keep in mind.

Comments

Comments are an important part of any programming language, including Python. They allow developers to leave notes and explanations within their code.

In Python, comments can be written using the hash symbol (#). Comments are not executable and are ignored by the interpreter.

To write a single-line comment in Python, simply type a hash symbol (#) followed by the comment text.

For example:

#my first program
#This is a single-line comment

To write a multiline comment in Python, you can use triple quotes (“””) to enclose the comment text.

For example:

"""
This is a multi-line comment
"""

Indentations and white spaces

In Python, indentations and white spaces are used to organize and improve the readability of codes. One of the most distinctive features of Python is its use of indentations to define code blocks rather than curly braces or other symbols as seen in other programming languages.

#Spaces and indentations
for num in [1,2,3,4,5]:
    print(num)

Data types

Data can be classified by type according to the kind of operations that can be performed on them or the values that they hold. Understanding data types and how to use them is essential for writing efficient Python programs.

Below is a categorization of data types in Python:

  • Numeric
  • Strings
  • Booleans
  • Sequences

Numeric

Numeric data types include integers, floats and complex numbers. Integers are whole numbers, while floating-point numbers have decimal places. Complex numbers are numbers with real and imaginary parts.

The table below provides examples of numeric types in Python.

Integers 1,2,5,10, -100
Float 1.05, -99.5, 0.005
Complex 2 – 1j, 4 – 6j

Strings

Strings are used to represent textual data in Python. They are enclosed in quotation marks (either single, double or triple) and can contain letters, numbers, and symbols.

The following are examples of strings:

'orange'
"There are 3 oranges in the box."
'1234'

Booleans

The Boolean data type is used to represent logical values. The boolean data type has only two possible values, which are True and False.

Keep in mind that the T and F for the True and False are in capital letters, while the rest of the letters are in lower cases.

Sequences

Sequences are also known as collections. In Python, data types in the sequence include:

  • Lists
  • Tuples
  • Dictionaries
  • Sets
  • Files

In addition to these basic data types, Python also supports more advanced data types, such as arrays, classes, and objects.

Variables in Python

Variables are used to associate a name with a value. To declare a variable in Python, a name is provided followed by an assignment operator ‘=’ and the value.

The name is provided at the left and separated by an assignment operator, followed by the value at the right.

number =  5

In the above example, a variable named number is assigned to the value 5.

By assigning a value to a variable, you can refer to a given value through the name of the variable.

result =  num + 4
print(result)

Output:

9

Here, the variable number is used to refer to the value of 4, which is associated with the variable.

Though, in some programming languages, it’s normal to define a variable and assign its value later in the program. In Python, you must assign a variable immediately.

Also, variables are not declared to have a type, as they are in many other languages; they are simply assigned a value.

Also, variables in Python are just names. They are not tied to specific data types.

This means that you a name can at some point be associated with an integer type and along the program be associated with a string. When a variable is assigned a new value, it overrides the previous value associated with it.

Choosing a variable name

The choice of a variable name plays an important role in the readability and maintainability of your program. You can name your variable anything you wish but always strive to use descriptive names.

Here are key things to keep in mind when choosing a variable name:

  • Variable names can contain letters, numbers and underscore characters.
  • Variable names are case-sensitive.
  • They cannot start with a number.
  • They cannot contain special characters like./*.
  • Also, they cannot contain spaces.
  • Reserved words cannot be used as variable names.

Note: Keywords or reserved words are words with special meaning to compilers or interpreters in any programming language.

The figure below contains the list of keywords in Python.
reserved keywords in python

Identifiers

An identifier is a name given to a variable, function, class or module. It is made up of a combination of letters (upper or lower cases), digits and even underscores.

Here are the naming rules for identifiers.

  1. An identifier can be composed of lowercase letters, uppercase letters, and digits.
  2. An identifier cannot start with a digit (0-9)
  3. A keyword cannot be used as an identifier
  4. Special characters or symbols like %, @, _$, and/or cannot be used as an identifier or contained in an identifier, with the exception of the underscore (_).

Also, keep in mind names in Python are case sensitive, which means that identifier names ‘abc’ are not the same as ‘Abc’.

print() function

This function is used to print or display texts on the console. It displays string values enclosed in parentheses on the console.

print('hello')
print([1,2,3,4,5])

Output:

hello
[1, 2, 3, 4, 5]

The print() function can accept a variable number of arguments and display them displays them as a string separated by white space.

For example:

print("greet", "me", "!")

output:

greet me !

The print function by default results in a new line.

print("apple")

print("orange")

print("mango")

Output:

Apple
Orange
Mango

If you wish not to have a newline you can change it through the end argument.

For example:

print("apple", end=" ")
print("orange", end=" ")
print("mango", end=" ")

Output:

apple orange mango

Input() function

This is used to accept input from users. It prompts the user to supply a text and by pressing the enter key you indicate that they have finished supplying the input.

For example:

name = input()
print("your name is", name)

It takes an optional argument in the form of a string, as a way of informing the user of the required information to supply.

name = input("What is your name: ")
print("your name is", name)

Operators in python

These are symbols, characters or words that are used to perform different kinds of operations in Python, including arithmetic or even logical operations. Here are the different types of operators in Python.

  • Arithmetic
  • Assignment
  • Relational
  • Logical
  • Bitwise
  • Identity
  • Membership

Arithmetic operators

Arithmetic operators are common in many programs. These operators are used to perform arithmetic operations or calculations. Here are Python’s arithmetic operators.

  • Addition+
  • Subtraction-
  • Multiplication*
  • Division/
  • Integer division//
  • Modulus%
  • Exponentiation**
  • Unary minus-
  • Unary plus+

In the following example, arithmetic operators are used in performing mathematical operations.

#common arithmetic operations

num1 = 12
num2 = 3

#addition
result =  num1 + num2
print(result)

#subtraction
result =  num1 - num2
print(result)

#multiplication
result =  num1 * num2
print(result)

#division
result =  num1 / num2
print(result)

#integer division
result =  num1 // num2
print(result)

#exponentiation
result =  2**3
print(result)

Output:

15
9
36
4.0
4
8

Relational operators

These operators, also known as comparison operators are used to compare for equality among values to determine the truth or falsity of some expressions.

These are used for comparing values. They are often used in It is usually used in decision-making in control statements such as the if statements and while statements.

Relational operators include:

  • Greater than>
  • Less than<
  • Greater than or equal to>=
  • Less than or equal to<=
  • Equal==
  • Not Equal!=

In the following examples, relational operators are used to compare values.

#relational operations

num1 = 12
num2 = 3

#greater than
result =  num1 > num2
print(result)

#less than
result =  num1 < num2
print(result)

#greater or equal to
result =  num1 >= num2
print(result)

#less or equal to
result =  num1 <= num2
print(result)

#equality
result =  num1 == num2
print(result)

#not equality
result =  num1 != num2
print(result)

Output:

True
False
True
False
False
True

There are other operators including the logical, bitwise, identity and membership

Control flow statements

Control statements are an essential part of programming in Python. They allow you to alter or control the flow of a program based on specific conditions.

Ordinarily, programs execute from top to bottom and from left to right. If you wish to write programs that do not execute in this linear way, control flow statements are used.

Control statements make it possible to write intelligent programs. With these statements, you can skip, stop, and repeat statements if certain conditions are met.

There are three types of control statements in Python and they include:

  1. Conditional statements
  2. Looping statements
  3. Jump statements

Conditional statements

Conditional statements are used to execute a specific block of code based on whether a given condition is true or false.

These statements enable you to execute programs in a nonlinear manner. The most common conditional statement in Python is the if statement.

If statements

An if statement is used to execute a block of code only if a specific condition is true. It is made of three components and they include:

  • Test
  • Blocks of code to execute
  • An alternative course of action to take

The test is a boolean expression that either evaluates to True or False. If the test evaluates to True the code blocks under it will be executed. If the test is False, the code inside the if statement is skipped.
The following program uses the if statement and the modulus operator to check if a number is an even number. It prints “an even number” if the number is an even number, and does nothing if it is not an even number.

num = 4
#if statement
if num % 2 == 0:
    print('an even number')
[code]

Output:

[code]
an even number

Elif statements

If statements can also be combined with else and elif statements to create more complex branching logic. The elif statement is short for “else if” and allows you to specify additional conditions to check if the previous conditions are false.

Here is an example:

num = 3
if num % 2 == 0:
    print('an even number')
elif num % 2 != 0:
    print('an odd number')

Output:

an odd number

Elif statements follow each other, providing further conditions that are not captured in the earlier ones.

#multiple elif statements
if num % 2 == 0:
    print('an even number')
elif num % 3 == 0:
    print('divisible by 3')
elif num % 4 != 0:
    print('divisible by 4')

Else statement

The else statement is used to provide a default block of code to execute if all of the previous conditions are false.

For example:

if num % 2 == 0:
    print('an even number')
elif num % 3 == 0:
    print('divisible by 3')
elif num % 4 != 0:
    print('divisible by 4')
else:
    print('not divisible by 2, 3 and 4')

Nested if statements

You can nest if statements by including an if statement within the body of another if statement. For example:

#nested if statements
if num > 0:
    if num % 2 == 0:
        print('even number')

Here the level of indentation determines which lines of codes are in the same block.

Looping statements

Looping statements are used to execute a block of code repeatedly.

There are two commonly used looping statements in Python and they include:

  1. For loop
  2. While loop

For loop

A for loop is used to iterate over a sequence of values (such as a list or a string) and execute the indented block of code for each value in the sequence.

The basic syntax of a for loop in Python is as follows:

for variable in sequence:
#execute this block of code

The variable following the for keyword is associated with the first item in a sequence. The code block is executed, and then the variable is associated with the next item in the sequence until the end of the sequence is reached. The sequence can be a list, tuple, string, or any other iterable object in Python.

For example:

fruits = ['apple', 'orange', 'pineapple', 'strawberry', 'grape']
for fruit in fruits:
    print(fruit)

Output:

apple
orange
pineapple
strawberry
grape

In this example, we have a list of numbers, and we use a for loop to iterate over each number in the list and print it to the console.

You can also use the built-in range() function to generate a sequence of numbers to iterate over.
Here’s an example:

for num in range(5):
    print(num)

Output:

0
1
2
3
4

While loop

The while loop allows you to repeatedly execute a block of code as long as a certain condition is true. While loop begins with a test. If the test evaluates to True, the block of codes under it is executed.

The test and execution process goes on and on until the test evaluates to False. The process is repeated like this as long as the test keeps evaluating to True.

The while loop consists of the while keyword, followed by a conditional test and a colon. The next line is an indented block of code. This block of code only executes if the test condition is True.

The syntax of a while loop in Python is:

while condition:
statement(s)

Here, the condition is an expression which is evaluated before each iteration of the loop. If the condition is true, the statements inside the loop are executed. This continues until the condition becomes False, at which point the loop is exited and the program continues to execute the code that follows the loop.

For example, the following code uses a while loop to print the numbers from 0 to 9:

count = 0

while count < 10:
    print(count)
    count += 1

Output:

0
1
2
3
4
5
6
7
8
9

In the above example, the condition is count < 10, and the statements inside the loop simply print the value of count and then increment it by 1. The loop will continue executing until count is no longer less than 10.

Jump statements

Jump statements are used to alter the normal flow of a program. The most common jump statements in Python are:

Break

The break statement is used to terminate the execution of a loop prematurely. It is typically used inside a for or while loop to exit the loop before the loop has finished iterating through all of its elements.

When the break statement is encountered within a loop, the loop is immediately exited and control is transferred to the statement immediately following the loop.

This means that any remaining iterations of the loop are skipped, and the program continues executing from the next statement outside of the loop.

Here’s an example of using the break statement in a while loop to terminate the loop when a certain condition is met:

for num in range(10):
    if num > 5:
        break
    print(num)

Output:

0
1
2
3
4
5

In this example, the loop will print the values of num from 0 to 5, but when count reaches 5, the break statement is executed and the loop is terminated.

Continue

The continue statement is used within loops to skip the current iteration of the loop and move on to the next iteration. When the continue statement is encountered, the loop will immediately jump to the next iteration.

Here is an example of using the continue statement within a for loop:

for num in range(10):
    if num == 5:
        continue
    print(num)

Output:

0
1
2
3
4
6
7
8
9

In this example, the for loop iterates over the range of numbers from 0 to 9. When the value of i is equal to 5, the continue statement is executed, and the loop immediately moves on to the next iteration, without executing the print statement. As a result, the output of this code will be:

pass

The pass statement is a null operation. It simply does nothing and is often used as a placeholder for code that has not been implemented yet or for code that will be implemented later.

The syntax of the pass is very simple. It can be used on its own or as part of a control flow statement like an if statement or a loop.

Here is an example of using pass in an if statement:

for num in range(10):
    pass

Strings

A string is a collection of characters enclosed inside matching single or double quotation marks. Strings are immutable, which means that once they are created, their contents cannot be changed.

Creating a String

To create a string in Python, simply enclose a sequence of characters in quotes.

For example:

country = 'Algeria'
sentence = 'How are you?'

It is important to note that in Python, single and double quotes can be used interchangeably to create a string, as long as they match.

Operations on strings

You can perform different kinds of operations on strings including:

  • Concatenation
  • Repetitions
  • Indexing
  • Slicing
  • Looping

Concatenation

Concatenation is the process of combining two or more strings together. This is done using the ‘+’ operator.
For example:

#concatenation of strings
str1 = 'ice'
str2 = 'cream'

result = str1 + str2
print(result)

Output:

icecream

Repetitions

If you want to repeat a given piece of string over and over again, you use the multiplication operator *. For numbers, this operator performs multiplication, but with strings, it performs repetitions.
For example:

#repetition of strings
greeting = 'hello!'
result = greeting * 3
print(result)

Output:

hello!hello!hello!

Indexing

You can access individual characters in a string using indexing. The first character in a string has an index of 0, the second character has an index of 1, and so on.

For example:

#indexing in strings
fruit = 'apple'
print(fruit[0])
print(fruit[1])
print(fruit[2])
print(fruit[3])
print(fruit[4])

Output:

a
p
p
l
e

Slicing

While indexing fetches the character in a given position or index, slicing is used to fetch or extract a range of characters from a string.

Slicing a string is done by specifying the start and end index of the substring separated by a colon (:) inside square brackets.

For example:

#slicing a string
result = fruit[1:3]
print(result)

Output:

pp

Looping a string

Since strings are sequences of characters, you can loop through the characters making it up using the form or the while loop:

for char in 'apple':
    print(char)

Output:

a
p
p
l
e

Built-in functions

Python has a rich set of built-in functions that can be used to manipulate and process strings. Some commonly used built-in functions for strings in Python are:

  • Len()
  • Str()
  • Ord()
  • Slice()

len()

This function is used to determine the number of characters in a string, which is also known as the length of the string.

For example:

fruit = 'grape'
print(len(fruit))

Output:

5

str()

The str() function is used to represent objects of other types as strings. For instance, if you want to convert a number to a string, you can provide the number as an argument to this function, and get the string representation.

#using str() function to convert integer to string
num = 1200
result = str(num)
print(num)

Output:

1200

ord()

Every character is represented in Unicode using a value known as a code point. With the ord() function, you can determine the Unicode code point of any given character as shown below:

#using ord to get Unicode code points
print(ord('h'))
print(ord('p'))
print(ord('.'))

Output:

104
112
46

slice()

The slice() function is used to create a slice object, which then can be applied to a string to extract or fetch certain characters in the string.

For example:

#slice function
fruit = 'grape'
part = slice(0,2)
result = fruit[part]
print(result)

Output:

gr

Built-in methods string methods

Python has a variety of built-in methods that can be used to manipulate and modify strings. Some commonly used string methods in Python include:

  • capitalize()
  • upper()
  • lower()
  • strip()
  • split()

In the example below, these methods are used to manipulate strings in various ways.

#built-in methods for strings
name = 'john'
print(name.capitalize())
print(name.upper())
sentence = 'how are you doing?'
print(sentence.split())

Output:

John
JOHN
['how', 'are', 'you', 'doing?']

Escape character

Escape characters in Python are special characters that are used to represent non-printable characters or to create special characters within string literals.

An escape character allows you to use characters that are hard to represent in a string.

They are represented by a backslash (\) followed by a character or a sequence of characters. When Python encounters an escape character, it interprets it as a special character rather than as part of the string.

Here are some examples of commonly used escape characters in Python:

  • \n- newline character
  • \t- tab character
  • \\- backslash character
  • \”- double quote character
  • \’- single quote character
  • \b- backspace character
  • \r- carriage return character
  • \f- formfeed character

Here is an example of using escape characters in a string:

#escape characters example
str1 = 'hello \tthere'
print(str1)

str2 = 'hello \nthere'
print(str2)

str3 = 'This is a string with a newline character\nand a tab character\tin it.'
print(str3)

Output:

hello   there
hello 
there
This is a string with a newline character
and a tab character     in it.

However, you can make the compiler ignore escape characters by placing an r before the beginning quotation mark of a string to make it a raw string.

str1 = r'hello \nthere'
print(str1)

Output:

hello \nthere

A raw string completely ignores all escape characters and prints any backslash that appears in the string.

Lists

This is the most versatile data type in Python. A list is created by enclosing data items in a square bracket, with each item separated by a comma.

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

An empty list is represented by a pair of square brackets with nothing in-between:

L = [ ]

It’s mutable and can be used to store heterogeneous data items. This means that you can store items of different data types such as numbers, strings and even lists or other data types in the same list.

L = ['age', 2.34, True, 250]

Lists can also be nested to form a matrix:

#using list to form a matrix
L = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]

Indexing

Items on the list are accessed by their index. The first item has an index of 0, followed by 1 and the last item has an index of n-1, where n is the number of items in the list.

#indexing in lists
colours = ['orange', 'purple', 'green', 'red', 'brown']
print(colours[0])
print(colours[1])
print(colours[2])
print(colours[3])
print(colours[4])

Output:

orange
purple
green
red
brown

An index could be positive or negative. For negative indexes, the first item in a list has an index of -1 and -2 for the second item, while the last item has an index of -n, where n is the number of items in the list.

#negative indexes
print(colours[-1])
print(colours[-2])
print(colours[-3])

Output:

brown
red
green

Slicing

This is a way of extracting or fetching all or a portion of the items in a list. You can extract or fetch all or a range of items in a list using the syntax below:

List[start : end]

This will return all the items starting from the item with the index start and stopping but excluding the item with the index end.

#slicing a list
result = colours[1:4]
print(result)

Output:

['purple', 'green', 'red']

Also, you might want to perform a slice on a list, but instead of fetching all the items in a given range, you can skip or omit some.

Take a look at this list:

L = [1,2,3,4,5,6,7,8,9,10]

To slice from index 4 all the way to the last item with index 9, the syntax is:

L[4:10]

Output:

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

If you want to skip the next item after a selected index or select the second item, then you will include a step value as shown below:

L[4:10:2]

Output:

[5, 7, 9]

Adding elements to the list

To add to an empty list or a list with an already existing item. The following methods are used to add items to a list:

  • append
  • insert

append() method

The append method inserts or adds a given item as the last item in a list. In the list below, the append method is used to add a new item to it. This new item now becomes the last item on the list.

L = []
L.append(1)
print(L)
L.append(2)
print(L)
L.append(4)
print(L)

Output:

[1]
[1, 2]
[1, 2, 4]

insert() method

Instead of having to add items to a list as the last items, you can use the insert method to add items at whatever position you wish.

The insert() method allows you to add items to a list in any position. However, this method requires that you provide the index where the item will be added to the list.

colours = ['orange', 'apple', 'grape']
colours.insert(1, 'strawberry')
print(colours)

Output:

['orange', 'strawberry', 'apple', 'grape']

In the above example, the item “strawberry” was added to the list at the index of 1.

Removing elements from a list

There are two ways to remove items from the list and they include the pop() and remove() methods.

pop() method

The pop method is used to remove items. If you want to remove the last item in a list, you can use the pop() method without providing any argument to it as shown below:

colours = ['orange', 'strawberry', 'apple', 'grape']
colour = colours.pop()

print(colours)
print(colour)

Output:

['orange', 'strawberry', 'apple']
grape

However, if you want to remove an item in a given position, you can provide the index as the argument to the pop method.

#pop method with argument
colours = ['orange', 'strawberry', 'apple', 'grape']
colour = colours.pop(2)

print(colours)
print(colour)

Output:

['orange', 'strawberry', 'grape']
apple

Remove() method

The remove() method is used to remove the first occurrence of a given item in a list. The method requires an argument corresponding to the item in which you want to remove its first occurrence.

For example:

colours = ['orange', 'strawberry', 'apple', 'grape']
colours.remove('apple')
print(colours)

Output:

['orange', 'strawberry', 'grape']

Sorting a list

The sort() method is used to sort the items in a list. With this method, you can sort the items in a list in ascending or descending order.

#sorting a list
colours = ['orange', 'strawberry', 'apple', 'grape']
colours.sort()
print(colours)

Output:

['apple', 'grape', 'orange', 'strawberry']

The sort() method has a parameter reverse which by default is set to False. This way, items are sorted in ascending order.

You can as well sort the items in descending order using the sort method. But, you have to set reverse to True. Changing the reverse to True makes the sorting to be in descending order.

colours.sort(reverse=True)
print(colours)

Output:

['strawberry', 'orange', 'grape', 'apple']

reverse() Method

The reverse() method is used to reverse or flip the positions of items in a list. This way, the first item becomes the last and the last item becomes the first.

#reversing a list
colours = ['orange', 'strawberry', 'apple', 'grape']
colours.reverse()
print(colours)

Output:

['grape', 'apple', 'strawberry', 'orange']

Concatenation

Concatenation is a way of combing or joining two or more lists together using the concatenation operator +.

#concatenation of lists
L1 = [1,2,3,4]
L2 = [6,7,5]
result = L1 + L2
print(result)

Output:

[1, 2, 3, 4, 6, 7, 5]

List comprehension

List comprehension provides a mechanism to create a new list out of another list using a single line of code. You might wish to create a list containing the squares of the numbers in another list.

Example:

#list comprehension example
nums = [1,2,3,4,5]
squares = [num**2 for num in nums]
print(squares)

Output:

[1, 4, 9, 16, 25]

Tuple

Tuples are another popular data type in Python. It is similar to the list except that it is immutable. You create a tuple by using parenthesis with elements separated by commas. Though, parenthesis is optional.

Because it is immutable, once created, you cannot add, remove or modify the items in it.

tup = (1,2,3,4,5)

An empty tuple is created with an empty parenthesis while a tuple with a single item is created by leaving a trailing comma after the item in the parenthesis.

For example:

#empty tuple
tup = ()
#tuple with single item
tup = (1,)

Packing and unpacking of tuples

Packing is a way of combining multiple values or items into a single unit. For instance, you can create a tuple is by assigning a name to values that are separated by commas.

For example:

#packing tuples
tup = 1,2,3,4,5
print(tup)

Output:

(1, 2, 3, 4, 5)

Unpacking is a way of fetching the items in a tuple and assigning the values to variables. When you assign the individual values in a tuple to variables, you are unpacking the tuple.

For example:

a,b,c = 1,2,3

print(a)
print(b)
print(c)

Output:

1
2
3

Operations on tuples

You can perform most of the operations of a list on a tuple. However, operations involving the modification of the items is forbidden in tuples.

Trying to modify a tuple will cause a TypeError, as tuple objects do not support item assignment

You can perform operations like indexing and slicing on tuples as shown in the example below:

#indexing a tuple
tup = (1,2,3,4,5)
result = tup[2]
print(result)

#slicing a tuple
result = tup[1:3]
print(result)

Output:

3
(2, 3)

Immutability of Tuples

Tuples are immutable types and as such cannot be updated or modified. Trying to change or update the values of a tuple will result in an error.

For example:

updating a tuple

Dictionary

A dictionary in Python is a collection of items comprising key-value pairs separated by commas and enclosed in a curly brace. Each key is paired with a value using a colon. The key is on the left and the value by the right.

subjects = {1:'chemistry'}

To define an empty dictionary, simply provide empty curly braces.

#an empty dictionary
subjects = {}

Accessing values in a dictionary

You can access a value in a dictionary through its key. To do this, you either, use the slice operator [] or the get method of the dictionary.

For example:

#accessing items in a dictionary
subjects = {1:'chemistry', 2:'history', 3:'government', 4:'geography', 5:'mathematics' }
#using slicing operator
subject = subjects[1]
print(subject)

#using get method
subject = subjects.get(3)
print(subject)

Output:

chemistry
government

Trying to access a value through a key that doesn’t exist in the dictionary will result in a key error.

dictionaries in python

Updating the values in a dictionary

Dictionaries are mutable and so, you can update or modify them. To do this, you can use the slice operator along with the corresponding key to modify or update the individual values in a dictionary.

#updating items in a dictionary
subjects[1] = 'agriculture'
print(subjects)

Output:

{1: 'agriculture', 2: 'history', 3: 'government', 4: 'geography', 5: 'mathematics'}

Adding a new item to a dictionary

You can add a new item to a dictionary by assigning value to a non-exiting key in the dictionary.

So, you can add a new item by assigning the key 5, which is not present in the dictionary to a value.

#adding a new item to dictionary
subjects = {1: 'agriculture', 2: 'history', 3: 'government', 4: 'geography'}
subjects[5] = 'mathematics'
print(subjects)

Output:

{1: 'agriculture', 2: 'history', 3: 'government', 4: 'geography', 5: 'mathematics'}

Deleting items in a dictionary

The del keyword is used to delete a dictionary or a specific item in a dictionary.

For example:

#deleting an item in a dictionary
del subjects[5]
print(subjects)

#deleting the entire dictionary
del subjects
# print(subjects)

Output:

{1: 'agriculture', 2: 'history', 3: 'government', 4: 'geography'}

Looping a dictionary

A dictionary is a sequence of items and just like every other sequence, you can loop through the items in it. In the example below, the for loop is used to loop through the items in a dictionary.

#looping a dictionary
subjects = {1: 'agriculture', 2: 'history', 3: 'government', 4: 'geography', 5: 'mathematics'}

#looping through the keys
for subject in subjects:
    print(subject)

#looping through the items
for subject in subjects.items():
    print(subject)

#looping through the values
for subject in subjects.values():
    print(subject)

#looping through the keys
for subject in subjects.keys():
    print(subject)

Output:

1
2
3
4
5
#looping through the items
(1, 'agriculture')
(2, 'history')
(3, 'government')
(4, 'geography')
(5, 'mathematics')
#looping through the values
agriculture
history
government
geography
mathematics
#looping through the keys
1
2
3
4
5

Sets

Sets are an important data structure in Python that allows you to store collections of unique items. A set is an unordered collection of elements that can be of any data type, including numbers, strings, and other objects.

To create a set in Python, you can use the set() function or use curly braces {} with comma-separated values inside.

For example:

nums = {1,2,3,4,5}

Note that if you use curly braces to create an empty set, it will create an empty dictionary instead. Therefore, it is recommended to use the set() function when creating an empty set.

#creating an empty set
nums = set()

Adding items to a set

To add an item to a set, you can use the add() method.

For example:

#adding items to a set
nums = set()
nums.add(1)
print(nums)

Output:

{1}

Note that if you try to add a duplicate item to a set, it will not be added, since sets only store unique elements.

Removing items from a Set

To remove an item from a set, you can use the remove() method. This method requires that you provide the item that you want to remove as an argument.

#removing items from a set
nums = {1,2,3,4,5}
nums.remove(3)
print(nums)

Output:

{1, 2, 4, 5}

If you try to remove an item that is not in the set, a KeyError will be raised.

Operations on sets

Sets in Python support various operations, including union, intersection, difference, and symmetric difference.

Let’s explore each of these operations:

Union

The union of two sets is the set of all unique elements in either set. The result of a union operation on sets is a set containing all the elements in both sets, but without duplicates.

You can use the union() method or the | operator to perform a union operation.

#union
S1 = {1,2,3,4,5}
S2 = {3,4,5,6,7,8}

result = S1.union(S2)
print(result)

#same thing as 

result = S1 | S2
print(result)

Output:

{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}

Intersection

The intersection of two sets is the set of all elements that are common to both sets. You can use the intersection() method or the & operator to operate an intersection.

#intersection
S1 = {1,2,3,4,5}
S2 = {3,4,5,6,7,8}

result = S1.intersection(S2)
print(result)

#same thing as 

result = S1 & S2
print(result)

Output:

{3, 4, 5}
{3, 4, 5}

Difference

The difference between two sets is the set of all elements in a given set that are not in the other set. You can use the difference() method or the – operator to perform a difference operation.

#difference
S1 = {1,2,3,4,5}
S2 = {3,4,5,6,7,8}

result = S1.difference(S2)
print(result)

#same thing as 

result = S1 - S2
print(result)

result = S2.difference(S1)
print(result)

#same thing as 

result = S2 - S1
print(result)

Output:

{1, 2}
{1, 2}
{8, 6, 7}
{8, 6, 7}

Symmetric Difference

The symmetric difference between two sets is the set of all elements that are in either of the sets, but not in both. You can use the symmetric_difference() method or the ^ operator to perform a symmetric difference operation.

#symmetric difference
S1 = {1,2,3,4,5}
S2 = {3,4,5,6,7,8}

result = S1.symmetric_difference(S2)
print(result)

#same thing as 

result = S1 ^ S2
print(result)

Output:

{1, 2, 6, 7, 8}

Functions

Functions are a fundamental concept in programming, allowing you to reuse pieces of code. A function is a group or chunks of codes that perform a given action.

Creating a Function

To create a function in Python, you use the def keyword followed by the function name and any parameters that the function takes.

For example:

#function definition
def func():
    print('hello')

Calling a Function

To call a function in Python, you simply write the function name followed by any arguments in parentheses.

For example:

#calling function
func()

Output:

hello

This will call the greet function and the following output will be generated.

Creating a function with parameters

In the above example, the function greet was defined without parameters. There was nothing in the parenthesis during the function definition.

However, if you want to create a function that accepts inputs or data from the calling method, then you have to provide parameters.

For example:

#creating a function with parameters
def greeting(name):
    print('Hello' + ' ' + name + '!')

#calling a function with parameters
greeting('Bob')

Output:

Hello Bob!

To call this function, you have to provide the name of the function including the arguments as shown below:

Returning Values

Functions can also return values using the return keyword. This makes it possible to pass data between functions or use the result of a function in other parts of your program. To return a value from a function, you use the return keyword followed by the value to return.

For example:

#return statement
def greeting(name):
    result = 'Hello' + ' ' + name + '!'
    return result

message = greeting('Bob')
print(message)

Output:

Hello Bob!

The return statement returns a value in a function.

When there is no return statement in a function, the function returns None.

Default Parameters

You can also define default values for parameters in a function, allowing you to call the function with fewer arguments. This is particularly useful when you have a default value to use if the calling method fails to provide any.

To define a default parameter, you simply assign a value to the parameter in the function definition.

For example:

#default parameters
def func(name='Bob'):
    result = 'Hello' + ' ' + name + '!'
    print(result)

#calling with an argument
func('Mary')

#calling with argument
func()

Output:

Hello Mary!
Hello Bob!

This creates a function named greet that takes a single parameter name with a default value of “everyone”. If you call this function without providing an argument, it will use the default value.

Variable Number of Arguments

In some cases, you may want to define a function that can take a variable number of arguments. This is particularly useful when you don’t know how many arguments to be supplied to the function.

To do this, you use the *args syntax to define a tuple of arguments, or the **kwargs syntax to define a dictionary of keyword arguments.

For example:

def func(*args):
    for arg in args:
        print(arg)

func('orange', 'purple', 'brown', 'red')

#**kwargs
def func(**kwargs):
    for value in kwargs:
        print(kwargs[value])

func(sex='male', age=9)

Output:

orange
purple
brown
red
male
9

Modules

In Python, a module is simply a file containing Python definitions and statements. Modules allow programmers to organize their code into reusable components.

Instead of writing the same code over and over again,  you can create a module once and use it over and over. This not only saves you time but also makes the code easier to maintain and debug.

Python comes with a standard library comprising modules files with different functions and classes that allow you to perform different kinds of operations.

Creating a module

A module can be created by simply creating a new file with a .py extension and writing Python statements in the file.

For example,

Open your text editor and create a new file. Save the file with the name mod and an extension of .py. This extension signifies that the file is a Python script or module.

You can then create functions that perform addition, subtraction, multiplication and division inside the file.

Having done this, you’ve successfully created a module in Python.

#a module that performs mathematical calculations

#addition
def add(a,b):
    result =  a + b
    return result

#subtraction
def minus(a,b):
    result =  a - b
    return result

#multiplication
def multiply(a,b):
    result =  a * b
    return result

#division
def divide(a,b):
    result =  a / b
    return result

Importing a module

To access or use the definitions in a module, you’re required to import them. To import a module, you use the keyword import followed by the name of the module that you want to import.

#importing modules
import mod

Ways to import a module?

Python provides several ways to import and use modules in your programs. Here are some of the most common ways:

Importing the whole module

This is done using the import keyword followed by the name of the module that you want to use.

This method imports the whole module and makes all its definitions and statements available in the current program.

import mod
result =  mod.add(5,7)
print(result)

Output:

12

Importing specific names from a module

If you don’t want to import all the definitions and statements in a module, you can selectively select the ones you want to use.

You can import specific names from a module using the syntax below:

#importing specific names from module
from mod import multiply
from mod import divide

result = multiply(10, 4)
print(result)

result = divide(10, 4)
print(result)

Output:

40
2.5

This method imports only specific names from the module and makes them available in the current program. This can be useful if you only need a few functions or variables from a large module.

Files

In anything you do with computers, you must surely work with files in one way or the other.

A lot of times we store information in files with the hope of using them in the future or to make it easy to access or share the information whenever we wish.

With Python, you can easily create, modify or even delete any piece of the file. Whatever it is that you want to do, whether it checking the number of words in a file or extracting certain information from a spreadsheet, you can easily do so using Python.

Now, let’s see how you can create and manipulate files in Python.

open () function

The open() function is essentially used in almost every operation involving files and file management in Python.

The open() function is used to create a file object that allows you to read, write or modify the contents of any given file.

This function requires arguments such as the file name and the path of the file and the access mode.

The syntax is shown below:

File = open(path+filename, mode)

The path is the location of the file you want to access or manipulate, while the mode specifies the kind of operations to be performed on the file.

This creates a file object and with the file object created, you can read, write or append to a file.

For instance, to read an already existing file, you can use the ‘r’ or read-only mode.

file = open('data.txt', 'r')

If you only want to read the content of a file, you can create a file object without specifying the mode as the mode is set by default to read-only mode.

So, you can as well write:

file = open('data.txt')

Below are the commonly used access modes for accessing or manipulating files in Python.

  • r –  read only
  • rb – read-only in binary format.
  • w – write only. Overwrites file contents if it exists
  • wb – write only in binary. Overwrites file contents if it exists
  • a – opens a file in the append mode. It doesn’t allow reading.
  • ab – opens a file in the append mode in binary format.
  • a+ opens a file in append mode and supports reading the file.

Reading files

You can read or fetch the content of an already existing file using the read-only mode as shown below:

file = open('data.txt')

With the file object created, you can then proceed to read the entire contents of the file.

read() method

If you want to read the entire contents of the file at a time, you use the read() method as shown below:

#reading file contents
result = file.read()
print(result)
file.close()

Readlines() method

Instead of reading the entire content of a file, if you want to get a list of all the lines in the file, you can use the readlines() method.

For example:

#reading file contents with readlines
file = open('data.txt')
result = file.readlines()
print(result)

readline() method

This method fetches the lines in a file one at a time. It is particularly useful if you want to loop through the contents of a file and print or perform a specific action for each loop interval.

result = file.readline()

Writing to a file

To write to a file, you create the file object using the write access mode (w). You then use the write method to store the contents of the file.

By opening a file in a write access mode, you are either trying to write contents to a brand new file or overwrite the contents of an already existing file.

For example:

#writing to a file
file = open('data.txt', 'w')
for num in range(1,6):
    content = f'line {num}\n'
    file.write(content)

Appending to a file

Opening a file using the write access mode removes the previous content of the file and inserts new content into the file. If you wish to include the new content in the file without wiping the previous contents, then you have to use the append access mode.

For example:

#appending file contents to a file
file = open('data.txt', 'a')
content =  'appended line'
file.write(content)

Copy files

The copy() method of the shutil module is used for copying files. This method accepts two arguments. The first one is the source or path file that you want to copy, and the second argument is the destination directory.

#copy files
import shutil
shutil.copy('data.txt', 'newfolder/data1.txt')

Move files

The move() method of the shutil module is to move a file from one place to another.

This method accepts two arguments. The first one is the source or path file that you want to move, and the second argument is the destination directory.

shutil.move('data.txt', 'newfolder')

Rename file

You can rename a file using the os.rename() method. You can even do bulk renaming of files by looping through all the files in a given directory and performing a rename operation on them.

For now, let’s see how to rename a file using the rename() method of the os module.

os.rename('data.txt', 'data2.txt')

Delete file

You can use the remove() method of the os module to permanently delete a file or directory.

For example:

os.remove('data2.txt')

OOP in Python

The concept of Object-oriented programming is essentially about reusing codes. Python is an object-oriented language that supports OOP concepts, making it an ideal language for developing complex applications.

The basic idea of OOP is to create objects that have their own data and behaviour. These objects are created from classes, which are like templates or blueprints for objects.

Classes can have attributes and methods that define the behaviour and data of objects. Attributes are variables that hold data, and methods are functions that operate on that data.

Classes and objects in Python

In Python, we create classes using the class keyword. For example, let’s create a class called Car that has two attributes, name and age:

class Car:
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

In the above example, a class named Car was defined with two attributes, name and age. Also, a special method called __init__, was also defined. This method is known as a constructor and is called when a new object of the class is created.

This method initializes the attributes of the object with the values passed as arguments. The self keyword refers to the instance of the class that is being created.

To create a new object of the Car class, you simply call the class like a function, by passing in the required arguments:

#creating an object of a class
car = Car('Tesla', 'White')
#accessing the attributes
print(car.name)
print(car.colour)

Output:

Tesla
White

In the above example, car is an object of the class Car, with the name “Tesla” and the colour “White”.

Class Methods

A method is a function defined inside of a class. Unlike regular functions, methods are defined with the first parameter being self. The self here corresponds to the object of the class upon which the method is being accessed.

Methods are often used to access or modify the attributes defined in a class.

Now, let’s define a method that provides information about the car object.

#adding methods to a class
class Car:
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

    def car_info(self):
        info = self.colour + ' ' + self.name
        return info

To access a method, you use the dot notation of the object as shown below:

car = Car('Tesla', 'White')
car_details = car.car_info()
print(car_details)

Output:

White Tesla

Inheritance

Object-oriented programming is essentially about code reuse and one of its core concepts of it is inheritance.

Basically, inheritance is a concept of OOP that allows for the creation of new classes based on another one. It is an approach to programming a class known as the child class derived from another one, known as the parent class.

The child class inherits the attributes and methods of the parent class and can extend or override it.

This way, you don’t have to repeat the codes in the parent class in the child class.

Let’s create a parent-class Car and a child-class SportsCar. The child class or subclass will inherit all the attributes of the parent class.

For example:

#inheritance
class Car:
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

    def car_info(self):
        info = self.colour + ' ' + self.name
        return info

class SportsCar(Car):
    def __init__(self, name, colour, type):
        self.type = type
        Car.__init__(self, name, colour)

    def car_type(self):
        return self.type

sports = SportsCar('Red', 'Chevvy', 'sports car')
#accessing methods in the parent class
print(sports.car_info())

#accessing method of the class
print(sports.car_type())

Output:

Chevvy Red
sports car

In the above example, the child class SportsCar inherited the attributes and methods of the parent class Car. Hence, you can access the attributes of the Car and SportsCar from sport, which is an object of the SportsCar.

Composition

This is another concept of object-oriented programming where you can create an object by combining objects with other classes.

Just as you could build a car by assembling components such as the engine, body, gear, batteries and so on, you can also apply the same principle in programming through composition.

To demonstrate this concept, the following example is a program consisting of classes in which the objects serve as components for a class named Car.

#composition
class Engine():
    def __init__(self, horse_power, plugs, liters):
        self.horse_power = horse_power
        self.plugs = plugs
        self.liters =  liters

    def engine_info(self):
        return f'{"_"*20}\nHorse Power: {self.horse_power}\nPlugs: {self.plugs}\nLiters: {self.liters}\n{"_"*20}'

    def start(self):
        print('Engine is on')

class Battery():
    def __init__(self, voltage, type):
        self.voltage = voltage
        self.type = type
    def battery_info(self):
        return f'{"_"*20}\nVoltage: {self.voltage}\nType: {self.type}\n{"_"*20}'
    def battery_condition(self):
        return 'good'

class Car():
    def __init__(self, make, model, colour, engine, battery):
        self.make = make
        self.model = model
        self.colour = colour
        self.engine = engine
        self.battery =  battery

    def car_engine(self):
        print(self.engine.engine_info())
    
    def car_battery(self):
        print(self.battery.battery_info())
    
    def start_car(self):
        self.engine.start()

#instantiating the objects
battery = Battery('24V', 'Lithium')
engine = Engine('5hp', '6 plugs', '4 liter')

car = Car('Honda', 'Avensis', 'Black', engine, battery)

car.car_battery()
car.car_engine()
car.start_car()

Output:

Voltage: 24V
Type: Lithium
____________________
____________________
Horse Power: 5hp
Plugs: 6 plugs
Liters: 4 liter
____________________
Engine is on

In the example above, the class Car is a composite class containing objects of other classes – Engine and Battery. From this class, you can access the attributes and methods of the objects that make up the composite class.

Exceptions

Exceptions are unexpected events that occur during the execution of a program, and handling them correctly can help prevent crashes and ensure the program runs smoothly.

They occur not because the syntax is incorrect, but are introduced by unexpected events during the course of the execution of a program.

For instance, if your program is dependent on the internet to work, and for some reason, the internet service is disrupted, an exception will occur. Perhaps, if the file your program is meant to read is not available or has accidentally been removed, an exception will occur.

The program will be stopped with error messages showing the reasons behind the sudden interruption of the program. Sometimes, the exceptions could be in multiple folds, making it difficult to get clues on the reasons behind the errors.

Because of this, it’s important to anticipate them in advance and handle them properly and not allow them to disrupt the program flow.

Python provides several mechanisms for handling exceptions, and understanding how to use them can help you write robust and reliable code.

Handling exceptions with try-except

The most common way to handle exceptions in Python is with a try-except block. The basic syntax of a try-except block is as follows:

#try-except block
try:
    file =  open('data.txt')
    result = file.read()
    print(result)
except:
    print('something went wrong!')

In this code, the try block contains the code that might raise an exception, while the except block contains the code to handle the exception if it occurs. If an exception is raised in the try block, Python will execute the except block instead of crashing the program.

Handling multiple exceptions

In some cases, you may want to handle different types of exceptions differently. For example, you might want to print a different error message for a TypeError than for a ValueError. To handle multiple exceptions in Python, you can use multiple except blocks, like this:

#catching multiple exceptions
try:
    result = input()
    print(result)
except ValueError:
    print(e)
except KeyError:
    print(e)

Output:

else block

You might wish to get your program to do something if an exception is caught. To do this, you will use the else block as shown below:

#except block
try:
    result = input()
except Exception as e:
    print('something just happened!')
else:
    print(e)

finally block

The finally block is where you put codes that must run regardless of whether an exception is caught or not.

Since codes in the finally block run even when an exception happens, it is a perfect place to perform such garbage collection operations like closing open files to avoid the files from corrupting.

For example:

#finally block
try:
    file =  open('data.txt')
    result = file.read()
    print(result)
except:
    print('something went wrong!')
finally:
    file.close()

Testing

Testing is important in Python (as well as in any other programming language) because it helps to ensure that the code you have written works correctly and meets the intended requirements.

Even experienced programmers don’t always get their programs working on the first attempt. There are times when you think that your program is working correctly only for it to break with unanticipated inputs.

The essence of testing is to ensure that a program is working as expected for a wide range of possible inputs.

A lot of times, people tend to confuse testing with debugging.

Testing is done to ensure that the program is working correctly while debugging is done to find errors or bugs that are preventing the program from working correctly.

Testing is like quality control checks, while debugging is fixing errors.

Making your programs easy to test

Not all programs are easy to test. Hence, you should write programs in such a way that it is easy to test and debug. One such way is by organizing your programs into functions and classes.

Breaking it down this way makes it possible for these units of your program to be independently tested.

There are two kinds of tests and these are unit tests and integration tests.

In unit tests, the various units that make up your program are tested independently. In integration tests, the various components are tested as a whole to know if they work together and still produce the expected results.

The process is to test. If there’s an error, then you debug to fix the error. If you must succeed as a programmer, then testing and debugging are very vital skills you must master.

Unittest Module

Python provides a variety of testing frameworks and tools to perform tests. One of the most popular testing frameworks for Python is unittest, which is part of Python’s standard library.

Here is an example of how to use unittest to perform tests:

#testing in python

import unittest

def calc(num1, num2):
    result = num1 + num2
    return result


class FuncTest(unittest.TestCase):

    def test_calc(self):
        result = calc(2,4)
        self.assertEqual(6, result)

if __name__== "__main__":
    unittest.main()

In this example, we first import the unittest module. Then we define a class called FuncTests that inherits from unittest.TestCase. This class contains a test function, test_calc that uses the assertEqual method to check whether the result of the calculation operation is equal to the expected result.

Finally, the test was run using the .main() method of the unittest module.

Other testing frameworks

There are also other testing frameworks for Python, such as pytest and nose, which provide additional features and flexibility for writing and running tests.

The basic approach of defining test functions and using assertion methods to check the results remains the same, though the syntax and structure may differ.

Conclusion

Python is a versatile programming language that can be used in a wide variety of applications, from web development and data analysis to artificial intelligence and scientific computing.

Python can open up a range of career opportunities in various fields. As you embark on the journey for mastery, the following books will be of immense help.

Resources

  1. Python crash course by Eric Matthes
  2. Learning Python by Mark Lutz
  3. Data Structures and Algorithms in Python by Michael T. Goodrich et. al

Leave a Reply

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