Introduction

If you are learning Python for the very first time, then this is the right tutorial for you. Congratulations for choosing to learn python. Fortunately for you, I am an experienced programmer in python programming language and so, I will give you detailed guidance on how to get started fast. We will simply begin by understanding what python is. Python is a computer programming language that allows you as the user to work fast compared to other programming languages. For you as a beginner, you will notice that the syntax and indentation structure in this language is quite easy to learn. In other words, python is a powerful high level programming language that is object oriented. Because of its simplicity, it is quite perfect for beginners. This tutorial details what python is, how to get started on python, the reasons why you should learn it and finally how to learn it to solve a number of problems.

Professionally, Python plays a critical role in performing backend we development, scientific computing, data analysis as well as artificial intelligence among others. Other developers have also used python in coming up with games, productivity tools and desktop applications among others. Therefore, as you read this tutorial, you will also be able to learn how to do these activities as well. An important thing to note is that Python is beginner friendly. This is because it was designed to be very easy and fun. Because of this reason, learning it is a great motivator. Many people who have learnt python including myself will tell you that it is a satisfying experience coding with it and using it to develop prototypes and tools. It is also because of these friendliness that this program is quickly gaining popularity among users and thus, serving as an efficient replacement of Java.

Some of the reasons why you should learn Python programming language include;

Ease to understand:

Considering that Python is a high level language, it reads just like English. This means that the language takes lots of stress off the learning process. It also has the ability of handling a lot of complexities and hence, permits beginners to pay a closer attention towards learning the concepts of programming and not having to worry so much on the details.

Flexibility:

Python being a dynamically typed language, it is very flexible in the sense that there are no hard rules on the manner in which to build its features. This means that you have a greater degree of flexibility when it comes to solving problems utilizing other techniques. It is also very much forgiving when it comes to errors. Therefore, you will still have the ability to compile and run the program to the part where you hit a snug.

Unfortunately for Python, when it comes to aspects of scalability, it is not easy to maintain and it is also very slow. Considering that this programming language is dynamically types as we already mentioned above, it is this same statement that can be translated to mean something else based on the context. This is because as the python application grows in complexity and size, it becomes a great challenge to maintain it. The main reason is that the errors becomes very hard to detect and track down for fixing. Therefore, it takes a great deal of experience and technical know-how for one to design the code or even write unit tests that will be instrumental in making maintenance easy.Additionally, python is very slow because it is very flexible! This might sound weird to you but it is true. Because of it being slow, the machine will require lots of referencing to ascertain the definitions of things hence, slowing down the performance. The good thing is that there are alternatives such as PyPy that are very fast implementations of Python. Despite the fact that they are not as fast as Java, it boosts the speed significantly.  As you walk into the world of programming languages, the truth is that you will begin to understand that support is very vital. This is because as a programming developer, community is all about receiving help and reciprocating that by giving help to those that also need it. Therefore, if the community is large, there is a high likelihood that you will get the help that you require. It will also mean that more and more people are building tools that are useful and thus making the development process quite easy.

Python History

Python language is a fairly old language that was first created by someone called Guido Van Rossum. The designing process of the programming language began in the late 1980s and its release was done in February 1991. You might be thinking, how did this guy even develop the language? Well, Guido Van Rossum was working on working on Amoeba distributed OS group. At the time, he wished to use an interpreted language such as ABC to access the system calls of the Amoeba. He then made the decision to create an extensible language that was later referred to as Python. So why the name python? You might ask. Many people actually think that it was named after a very dangerous snake, but this is not true. Guido Van Rossum was a comedy series fanatic and thus named the programming language Python after the comedy series “Monty Python’s Flying Circus”

Python Audience

This tutorial I designed for the beginners who would wish to learn Python programming language to solve some of the problems that they face such as data analysis, development of useful tools among others. It is also designed for software programmers who would wish to learn how to get started using Python right from scratch. In order to learn this programming language, you should have a basic understanding of terminologies used in computer programming. However if you have a basic understanding of any programming language, it is an added advantage.

Python Features

When it comes to the features of python programming language, one of the most important things that you have to note is that it is a general dynamic language that emphasizes on readability. As mentioned earlier, one of the things that has made it quite popular among its users is beginner-friendly codes. While other programming languages are quite complex in their syntaxes, Python is simple for anyone to understand. Some of the key features that stand out include the following:

Open source

Python just like most programming languages such as PHP, Perl, Swift and Rust among others is an open source. This means that its source code is available within the license and hence, users are permitted to gain access, distribute or even perform modifications to the code without necessarily getting permission from the developers.

Portable

Considering the fact that Python language is open source, it has been ported to run on a wide range of platforms. These platforms include the following; Windows, BeOS, Mac, Sharp Zarus, Solaris, PocketPC, PlayStation among others. However, if your intention is to run python on another platform different from the usual ones, it is important that you exercise a lot of caution to ensure that you are not using any system-dependent features at all.

Object-Oriented and Procedure-Oriented

One of the most important feature to note about Python is that it is both procedure and object oriented in its functionality. Procedure oriented simply refers to the fact that the language is designed in such a manner that it is around protocols and functions that are re-used throughout the entire language. In comparison to this, object oriented simply refers to the language being built around objects that combines functionality and data together.

Embeddable

This simply refers to the ability of Python programming language to embed other programming languages within itself such as C and C++ programming languages. Because of this feature, Python permits users to boost their codes with scripting functions.

Easy to learn

Just as we have mentioned above, Python is beginner friendly and thus making the programming language easy to lean and understand. This is often irrespective of prior knowledge, skills or experience in programming languages. This means that if you are new to programming and looking to learn the first language, Python is the best way to begin. It is because of its simple syntaxes that make the language easy and fun. These are traits that are quite rare among other programming languages.

Libraries

One of the greatest strengths of this programming language is its libraries. A standard library is one that contains tools that help programmers to better use the language. It offers support to a great deal of protocols such as HTTP and MIME among others, and formats. In the Python’s standard library are modules that play a significant role in the creation of a graphical user interface, modules for unit testing as well as modules that are important for manipulating regular expressions. However, of importance to note is that Python’s standard library is not required to run or use Python in an application.

How then do you Install Python?

To install Python is generally easy. Today, most of the UNIX and Linux distributors’ include a recent version of Python. Additionally, some Windows computers such as HP comes with Python already installed. However, just in case your computer does not have Python already installed, all you have to do is visit the following link; https://www.python.org/downloads/ and you will have the Python installation page appear. Depending on what OS you are using, select the one that suits your Operating System. Once you have done that, you will have versions of Python. For example, for Windows, you have version 3.6.1 or 2.7.13 among others. Click on the version that you would like to use. It is always advisable to install the latest version. An .exe file will be downloaded to your computer. Go to Downloads on your computer and click on the .exe file that you just downloaded. Follow the simple guidelines on installation and a shortcut will be created on your desktop. At this point, you are now set to begin writing codes or even executing commands on Python for a wide range of tasks.

Python Versions

It is important to note that there are many versions of Python just like other software. As times goes by, there are improvements and upgrades that happen to the previous version leading to a release of new versions. The first thing that you have to do is for you to determine whether you have python already installed in your computer and what version it is. Begin this by opening a command prompt and then typing python.exe. Press enter. If you get a feedback telling you “python is not recognized as an external or internal command”, this could mean that python is not installed in your computer or the PATH that you are using to locate the file is not correct. The other option is to locate the python.exe file in c:\ and d:\ compartments of your computer. If you still cannot get any results, it is then safe to assume that python is not installed in your computer. However, if you do find it, it could mean that the file is corrupted and is the reason it did not update the PATH and if you run it, it will identify what version it is that you have installed.

That said, there are a number of versions that are available for download online by simply visiting https://www.python.org/doc/versions/ . It is always safe to ensure that you are using the latest version to reap the benefits of in-built applications that have been upgraded. Some of these versions include:Python Applications

Python Applications

There are a wide number of python application tools that play important roles in different areas. Some of the applications are important for web & internet development, scientific purposes, software development, desktop graphical user interface among others. Here, I will give the categories that python is useful and the various applications used for that purpose. These include;

Web and internet development

Frameworks such as Django and Pyramid are used in web development. Django is an MVC (Model, View and Controller) application tool that serves as an important web framework. Pyramid on the other hand is a minimalistic web framework that is inspired through such tools as Django, pylons and Zope. RapidSMS is important in extending the capabilities and logics of Django so as to communicate with SMS messages. Other microframeworks include Flask and Bottle. There are alos application that play a critical role in advanced content management systems. These applications include django CMS and Plone.

Python’s standard library also plays an important role in offering support to a wide range of internet protocols such as XML an HTML, Email processing, JSON, IMAP, FTP among other internet protocols.

Scientific role

In addition to web and internet development roles, there are other applications that play a significant role in scientific as well as numeric computing. Some of these Python applications include; Pandas that plays an important role in data analysis as well as library modelling. SciPy on the other hand refers to a collection of packages that are important in engineering, mathematics and science. IPython is a very robust interactive shell that is important in carrying out simple editing and recording of work sessions. It also offers support to visualization and parallel computing. Biopython is used solving molecular biology questions. Ornage is also important open-source application used in visual programming to perform interactive visualization of data and data mining, data analysis as well as machine learning.

Education

In education, python is a very important programming language that plays a key role both at the introductory and advanced course levels. Mathics is an open-source application that plays a key role in mathematical programming. NumPy serves as a Python language extension that offers a great deal of support for both large and fast matrices and multi-dimensional arrays. Matplotlib on the other hand is an application extension of MATLAB used in plotting and performing mathematical functions. SymPy is important in symbolic mathematical calculations while SageMath serves as a large mathematical software application that essentially incorporates the work done by over hundred free software projects.

Desktop graphical user interface

Some of the python applications that are used in grapgical user interface include; PyQt which is a very popular cross platform grapgical user interface library that is founded on Qt. Pyside is an alternative python applications to PyQt. Kivy is an open source python application that plays a significant role in multi-touch application softwares and is characterzed by a natural user interface. Just like Kivy, AppJar is a cross platform application. However, this application plays a crucial role in offering an easy wrapper functions around most other applications such as Tkinter only that it has an extra built-in functionality.

Python Variables

Just as the name suggests, a python variable refers to anything that is subject to change. In other words, it is simply a way through which most computer program languages use to refer to memory locations. In these memory locations, there are a wide range of variables such as numbers, texts among other data types. You can view a variable as a container that plays a significant role in the storage of values. Therefore, as the computer program is running, variables can be easily accessed and altered. Depending on the data type of a given variable it is the role of the interpreter to allocate memory as well as make the decision on what is to be stored in the memory reserved. This means that you can assign a different data type to a variable and thus, store them as either decimals, integers or even in other cases characters.

You might then ask, how do we assign variables? Well, in the case of python, variables do not necessarily require an explicit declaration to reserve memory space. This is because the declaration takes place automatically once a value is assigned to a certain variable. In this case, it is the equal sign (=) that is used in assigning variables. Therefore, the operand that appears at the far left of the operator = sign represents the name of the variable while the operand at the right of the operator = sign represents the value that is stored in the variable.

For instance,

Hemorrhage = 100 represents an integer assignement
Kilos = 2000.8 represents a floating point
Name = “Martin” represents a string
Print Hemorrhage
Print Kilos
Print Name

In other words, Hemorrhage, Kilos and Name refers to variables

Apart from the instance above where one variable is assigned one value, there are other cases where python permits you as a user to assign a single value to many variables at the same time.

For instance;

g = h = i = 56

In this case, it is the integer 1 that is assigned all three variables. Alternatively, you can assign multiple objects to multiple variables.

For instance;

g = h = i = 56, 46, “Andrew”

Keywords and Identifiers

In python, keywords are also referred to as reserved words. In this case, python keywords cannot be used as functions, variable names or any identifier at all. This is because their major role is to define a syntax and the structure of the python programming language. Keywords are also case sensitive. There are several keywords in python but the number varies with the python version. An important point to note is that all the keywords are in lowercase except None, True and False and because of this, they must be written as they are. Some of the keywords include; class, from, for, lambda, return, continue, try, is, finally, def, del, global, and, with, while, nonclonal and else among others.

Looking at each one of the keywords and attempting to figure out what each one of them means is quite overwhelming. However, some examples are as follows:

True and False refer to truth values in python language. In most cases, they are results of comparison or logical operations. For instance;

1= = 1
True
5>3
True
20<1
False

None is another very specialcontents that is used in python language to represent absence of a value or just a null value. The most important thing that you have to understand is that you cannot create several None objects. Rather, you can assign the None value to a variable. The assigned variable will be equal to one another. You have to note that None does not mean False in any way. It also does not mean 0 or an empty list, string, dictionary among others.
Therefore, when you run the command;

None == 0, the output is False

However, you can simply say that;

X = None
W = None
Therefore, x = w
Hence, x == w
True

Additionally, when you have void functions that do not return anything, the output is a None object.

For instance;

def a void function ():
g = 3
c = 9
K = g + c

In python, an identifier simply refers to a name that is used to identify a given variable, class, module, and functions among other objects. Identifiers often begin with letters ranging from A to Z or simply an underscore (_) that is then followed by a zero or more letters or just an underscore that is followed by digits ranging from 0 to 9.It is important to note that python does not permit punctuation characters. These punctuation characters include $, %, and @ within identifies. Python is also case sensitive, and therefore, Power and power are taken to be two different identifiers.

Some of the naming conventions for Python identifiers include the following:

  • Class names begin with an uppercase letter while all identifiers begin with a lowercase letter
  • In case an identifier ends with two underscores that are trailing each other, the identifiers is said to be language defined special name
  • Beginning an identifier with a single leading underscore is an indication that the identifier is more private.
  • Finally, beginning an identifier with two leading underscores is an indicator that the identifier is strongly private

Executing Python

Programming is pointless if you cannot execute commands or even run python scripts.When you run a python script, it is the role of the interpreter to convert the program into a format that the computer can understand. To execute python, there are two major ways that this can be done. The first one is calling the python interpreter using a shebang line and the second one is using an interactive python shell.

Programmers often write standalone scripts that are very independent of the environment. The scripts are saved with a .py extension to indicate that the file is a python program. Once the interpreter has been invoked, the file is read and interpreted. The most important point to note is that running these files on Windows and Linux is quite different. Windows uses the prompt command. The path of the program looks like this;

C:\Python37\python.exeC:\Users\Username\Desktop\my_python_script.py

With Windows, there are two executable files named python.exe and python.exe. If you wish to have a terminal pop up then it is advisable that you use the python.exe because it is typically a GUI program. You have to ensure that the script you are running is executable.

To make the script executable use the command;

Chmod +x mypythonscript. py

Assuming that you already have python program installed in your computer and that it is running well, the first thing that you have to do is to open a terminal or console. Then type into the terminal the term ‘python’. Press the Enter key on your keyboard. The screen will display the following statements;

user@hostname:~python

Python3.6.0(default,May132016,04:35:05)

[GCC4.2.1Compatible Apple Clang4.1((tags/Apple/clang-421.11.66))]on darwin

Type”help”,”copyright”,”credits”or”license”formore information.

An important thing that you have to bear in mind is that while working with the live interpreter, everything that you key in is read and interpreted there and then. This means that running commands and getting output is done in real-time. Therefore, you have to have a proper mental plan in order to effectively interpret the output of the scripts you are running because everything you are doing is interactive. Hence, to run script, you have to import it to the environment you are working from or invoke python executable.

Python examples

There are several examples that we can explore in this tutorial just to get you started on python programming. Let us consider the following examples;

To add up two numbers

Num1=78
Num2=92
#Add numbers 1 and 2
Sum = float (num1) + float (num2)
#To display the sum
print (‘The sum of {0} and {1} is {2}’.format(num1, num2, sum))
170

To print a statement/comment
#print Good morning America

print (‘Good morning America’)

Good morning America
1. Checking if the input number is prime or not

num=407
# num = int(input(“Enter a number: “))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,”is not a prime number”)
print(i,”times”,num//i,”is”,num)
break
else:
print(num,”is a prime number”)# if input number is less than
# or equal to 1, it is not prime
else:
print(num,”is not a prime number”)

Output: 407 is not a prime number

Python I/O and Import

With python, you get access to a wide range of in-built functions that are readily available. Some of these in built functions include input() and print() that are used as standard input and output operators respectively.

Python output

This often uses the function print(). This function is important in outputting data to the screen. For example;

Script.py
Print (“This is my shirt”)

#the output on the screen: This is my shirt

j = 5
print (‘The value of j is’, j)
Output: The value of j is 5

In the second example above, you will notice that a space was added in between the string and the variable j. The truth is that this is a default way but it can be changed.

The actual syntax for the print() function is as follows;

Print(*objects, sep=’’, end=’\n’, file=sys.stdout, flush= False)

In this case, objects refer to the values that are to be printed. Sep is a separator that is used in between values and is set as a default space character. Once all the values have been printed, then the end is printed and this defaults into a line

Output formatting

In some cases, you will realize that you would like to format the output that you have to look a little attractive. In order to achieve this, all you have to do is use the str.format() technique. This method is quite visible to any string object.

Let us consider the following example;

X = 8; y = 40
Print (‘The value of x is {} and y is {}’. format(x,y) )
The value of x is 8 and y is 40

You will realize that the use of the curly braces is simply to serve as placeholders. However, in order for us to specify the order in which the output is printed, we simply use tuple index.

Python input

In order for flexibility to be realized, it is important that we take the input from the user. In python, we have the function input() that performs this function. To get the syntax for this particular function, simply enter the command;

Input[prompt]. The prompt string is what defines what to be displayed on the screen. However, it is optional. Let us consider the following example;

num = input(‘Enter a number’)
Enter a number 78
Num
‘78’

From this example, you will appreciate the fact that the value 78 entered here is a string and not a number. In order for us to convert this into a number, we use the function int() or float().

Python import

When the program grows into something big, it is often a very good idea to categorize it into a number of modules. In other words, a module refers to the file that contains python definitions as well as statements. The python module is made up of a file name that ends with an extension .py. Therefore, the definitions that are found inside a module can thus be imported to another module. The keyword that we use in this case is import.

Python Operators

Python operators simply refer to special symbols that are important in carrying our arithmetic as well as logical computations while the value that the operator works on is referred to as an operand.

Consider this example;

> 2 + 5
> 7

In this case, the + sign serves as an operator that is important in performing addition. The values 2 and 5 are the operands while the value 7 is the output.
There are several classifications of operators on Python. These operators include:

A. Arithmetic Operators

These ones play an important role in performing mathematical operations such as multiplication, additions and multiplication.

For example:

Addition such as r + y + 9
Subtraction such as r – y – 9
Multiplication such as r * y
Floor division such as r // y

 

B. Comparison operators

These ones are used in comparing values. This means that they can either be True or False based on the conditions. For example;
Greater than sign (>) to mean that the operand on the left is greater than the one on the right e.g. r > y
Less than (<) means that the operand on the left is less than the one of the right e.g. r < y = = means that both operands are equal to one another e.g. r = = y ! Means that the tow operands are not equal to one another e.g. r != y >= means that if the value on the left is greater or equal to the one on the right, then it is True otherwise it is False e.g. r >= y
<= means less or equal to. Therefore, if the value on the left is less or equal to the one on the right, then it is True otherwise it is False e.g. r <= y

C. Assignment operators

These ones are used in assigning values to variables. For instance, x = 7 serves as a simple assignment operator that assigns the value 7 to the variable x.

D. Boolean operators

They are also referred to as logical operators. They include and, or, not operators.
And is used when both of the operands are true e.g. x and y
Or is used when either of the operands is true e.g. x or y
Not is used when the operands are false. In other words, they complement the operand e.g not y

E. Bitwise operators

These operators often act on the operand as though they were a string of binary digits. In other words, the manner in which they operate is bit by bit just as the name suggest.
For instance, in binary, 2 is 10 while 7 is 111

Let us consider the following examples. Assume that r=10 (0000 1010) and y=4 (0000 0100 in binary).
& means AND e.g. r and y = 0 (0000 0000)
<< means left shift e.g. r << 2 = 40 (0010 1000)
^ means XOR e.g. r ^ y = 14 (0000 1110)

F. Special operators

These include the membership and the identity operators.

Identity operators: These include is and is not operators that play a significant role in checking if two variables or values are located on the same memory compartment. However, finding two values or variables that are equal does not mean that they are identical.

For instance;

is operators is considered to be True is the operands are identical to each other. E.g. r is True
is not is an operator that is said to be True if the operands are not identical to each other e.g. y is not True

Membership operators: These include in and not in operators that play an important role in testing whether a given variable or value is found in a sequence.

For instance;

in is said to be True if the variable or the value is present in a sequence e.g. 8 in r
not in is said to be True given that the values or variables are not found in a sequence e.g. 8 not in r

Statements and Comments

Statements simply refers to a set of instructions that Python can execute. For instance, x = 4 is an assignment statement. Other kinds of statements include if, for and while among others.

In most cases, you will realize that the end of a statement in python is simply marked by a newline character. However, there is a possibility of us extending a statement over multiple lines using the \ sign as a line continuation character.

For example;

x = 3+5+7+ \
5+9+0+ \
4+6+8

On the other hand, comments in python are important in offering a detailed description of the things that are happening inside a program. This means that you will be looking at a source code and not have a difficult time figuring it out. The truth is that, when you are programming or writing codes, you might end up forgetting them in like a month or two. Writing comments is the best way to explain concepts in the form of comments. In order to do this, you simply use the hash sign (#) at the beginning of the comment. Comments also extend to the newline character.

For example;

# This is a comment
# print out God loves us
Print(‘God loves us’)

If we have comments that are extending to multiple other lines, the best way of doing it is simply using the hash sign.

For instance;

#since this is a long weekend
#I plan to host some
# friends over for a party

Alternatively, you can simply use triple quotes for this comment.

For instance;

“”” Since this is a long weekend
I plan to host some
friends over for a party”””

Operator Precedence

Let us consider a scenario where you have an expression like 4 + 6 * 3, do you think that the addition is done first or the multiplication? Well, in High school, the rules in mathematics requires us to do multiplication first. This means that multiplication has the highest precedence over the addition operator. In the table below, you will get a list of operators ranging from the one with the lowest precedence to the one with the highest precedence. In python, the operators present low in the table are first evaluated before proceeding to the ones higher in the table. I would advise that you make good use of parentheses to group operators and operands in order to specify the precedence more explicitly. This is also important in making the pogram readable.

For instance;

4 + (6 * 3) is better than just 4 + 6 * 3.

Flow Control

Python if…else

This is one of the most common statement types in python. When using the python if statement, you can have none or more of these parts. However, the else statement is optional. The ‘if else’ statements is often represented in short as elif. The main reason for this is to avoid any excessive indentation.
An important point to note is that the else statement is used only when the condition of the if statement is False. In other words, you can interpret the else statement as “If this condition is true, then execute this code. Else, execute that other code”. The else statement often does not have a condition. It often is composed of else as the keyword, followed by a colon and on the next line that follows it, begin with an indented block of code otherwise referred to as else clause.

Let us consider the following example;

y = int (input(“ Enter the integer: ”))
Enter the integer: 25
If y < 0:
y = 0
print(‘Negative changed to zero’)
elif y = = 0
print(‘zero’)
elif y = = 1
print(‘single)
else: more
print(‘more)
More

 

Python for Loop

A loop refers to a statement that permits one to execute a statement or even group of statements in multiple lines. Within python, there are different types of loop statements that play an important role in looping. These include;

While loop

This loop statement type is important in repeating a statement whenever the group condition is TRUE. In other words, it evaluates the condition prior to executing the loop.

Example

# Program to add number
# sum = 1+2+3+…+y
y = 2
# preparethe total and counter
sum= 0
x = 1
while x<= y:
sum= sum+ x
x = x+1 # update counter
# print the total
print(“The totalis”, total)

For loop

This is an important statement that plays a key role in executing sequence of statements several times and then abbreviates the code that is responsible for managing the loop variable.

Nested loop

With this, you can simply use one or several loop statements ranging from while, for and do among others in a single code.
An important factor to point out is that loop control statements often alter their execution form the normal sequence. This means that when execution leaves a scope, all automatic objects created within that very scope are destroyed. Some of the control statements include break, pass and continue.

Break simply terminates the loop statement and then moves the execution to the statement right after the loop. The continue command often plays a role in causing the loop to skip the remainder of the body. It then reevaluates the condition before repeating. Pass plays a key role when a statement is syntactically needed. However, in this case, you do not require any command to execute it.

Looping Technique

Functions

Python Function

Function Argument

In python, a function can be defined as an operator that takes a wide range of arguments. Let us consider the following example;

def greetings (message):
“ “ “This message sends greetings to
the person intended to receive the message” “ “
print(“Hi”, name + ‘, ’ + message)
greet (“Patricia”, “Good evening”)
Run
Output
Hello Patricia, Good evening

In this case, the function greet() is made up of two parameters. Considering the fact that we have called this function with two arguments, the run is very smooth and there are no errors. However, if we had called it with different arguments, then the operator would give an error. There are different types of function arguments namely; python default argument, python arbitrary argument and finally, python keyword argument.

Python default argument

In python, arguments can assume the form of default values. In this case, we can simply assign a default value to an argument by simply using an assignment operator (=). Let us consider the following example;

defgreet(name, msg=”Bonjour!”):
“””This function greets
the person to whom the message is provided.
If message is not provided,
it defaults to “Bonjour!””””
print(“Hi”,name+’, ‘+msg)
greet(“Martin)
greet(“Martin”,”Good evening?”)
Run

In the above example, one important thing to note is that the function name does not have a default value. This means that it is mandatory. The parameter message has a default value “Bonjour!” This means that it is optional. Therefore, if a value is provided, then the provided value will overwrite the default. Hence, any argument in a function can have a default value. This is to mean that non-default arguments cannot follow default arguments.

Python keyword argument

Whenever we call a function with certain values, it is these values that get assigned to the argument depending on their position. For instance, in the example we gave of default arguments, in the function greet(), when we call greet (“Patricia”, “Good evening”), the value Patricia automatically is assigned to name and Good evening to message. In the same manner, python often permits functions to be used as keyword arguments. This means that whenever we call a function in this manner, the position of the argument can be changed. That means that we can mix both positional arguments with keyword arguments during a call. However, we have to bear in mind that the keyword argument has to follow a positional argument. This is because if you have a positional argument following a keyword argument, you will get an error.

For instance;

greet (name=“Patricia”, “Good evening”)
syntaxErroe: non-keyword arg after keyword arg

Python Arbitrary arguments

In other cases, you will find that we do not know in advance the number of arguments that will be passed to a function. Therefore, python will simply allow us to handle this situation by using function calls with arbitrary number of arguments. When using the def function, we often use the asterisk before a parameter name. This is to denote the kind of argument that we are using.

Let us consider the following example;

def greet(*names)
“””This function greets all
person in the names tuple.”””
fornameinnames:
print(“Hi”,name)
greet(“Michael”,”Jamal”,”Abdullah”,”John”)
Run
Output
Hi Michael
Hi Jamal
Hi Abdullah
Hi John

In this case, we have used a number of arguments at the same time. These arguments are often wrapped up in a tuple prior to getting passed into a function. Inside the function, we then use for loop in order to retrieve the argument.

Python Recursion

In python, recursion simply refers to defining something using itself. One thing we know by now is that in python, a function can be used to call other functions.

Let us consider the following example;

To determine the factorial of an integer. Factorial simply means the product of all integers starting from 1 to that specific number.
Factorial of 4 (Also, 4!)
Means, 1*2*3*4=24
In python, this is represented as follows;

defcalc_factorial(x):
ify==1:
return1
else:
return(x*calc_factorial(x-1))
num=4
print(“The factorial of”, num, “is”, calc_factorial(num))
Run

In this example, the function calc_factorial is recursive. Therefore, when we call this function using a positive integer, it will call itself recursively by simply decreasing the number. Recursion ends at the point where the number is reduced to 1. This is referred to as the base condition which plays an important role in stopping the recursion otherwise the function will continue calling itself to infinity. Some of the advantages of these recursive functions is that they make the code look neat and elegant, and break a complex task into simpler sub-problems that are easy to solve. Additionally, with recursion, sequence generation is much simpler than using nested iteration. On the other hand, recursion has its downsides such as the logic behind it may be quite difficult to follow through. Recursion is also expensive in terms of high memory requirement and time consumed. Finally, the recursion function often are very difficult to debug.

Anonymous Function

These are also referred to as lambda functions and hence lambda used as the keyword. They simply are functions that do not have a name. Such a function has the following syntax; lambda argument: expression.

They often have multiple arguments but only one expression that s evaluated and returned. Let us consider the following example;

double=lambday: y*2
# Output: 40
print(double(20))
Run

In this example, lambda y: y * 2 refers to the anonymous function. y denotes the argument and y * 2 as the expression that is under evaluation and then returned. This function has a number of roles. These include using it when a nameless function is required just for a short time. In python, it is also used as an argument to a higher-order function. Therefore, used together with built-in functions that include filter () and map () among others.

For example;

# lambda used with filter ()# In this case, they take both a function and a list as arguments. The function is therefore, called using all items in the list and then a new list is returned. The new list returned is made up of items that the function evaluates to be True.

# Program to filter out only the even items from a list
my_list=[1, 7, 14, 76, 98, 11, 39, 52]
new_list=list(filter(lambdax: (x%2==0) , my_list))
# Output: [14, 76, 98,52]
print(new_list)
Run

Python Modules

This refers to python definitions and statements. For instance, a file that contains python code such as genome.py is referred to as a module and the module name is genome. The main role of modules in python is to break down large arguments into smaller chunks that are very east to manage and organize. Additionally, the main advantage of modules is in its ability to provide code reusability. Instead of copying the content of each module into a program, the simplest thing to do is to import it.

Let us first create a module and save the results in a file called module1;

def add(x, y):
“””This program adds two
numbers and return the result”””result = x+ y
return result

How then can you import the file to your environment? Well, we simply do this by using the import keyword. Let us consider the following example to import module1 file that we previously created.

> import module1

Additionally, we can use the name of the module to gain access to a number of functions by simply using a dot operation. For instance;

module1.subtract(86, 80)
6

Python Package

In our computers, we do not store all of our files in one location. We often use hierarchical order of directories to make access to the content very simplified. This means that files that are similar are in one location. In the same manner, Python has a number of packages for storage of directories and modules for files. This means that as the application program becomes bigger in size, we group similar modules in one package and different modules in different packages. A directory will also have a number of sub-directories within it and in that manner, Python packages has sub-packages and modules within it.

To import modules from a package, we still use the dot operator we discussed in the section above. For instance, if we wish to import a module called genomethat is in the Module directoryand sequencing sub-directory, we simply do this;

Import module.sequencing.genome

Native Data types

The data that is stored in the computer memory can assume many types. For instance, when you are storing the body weight of an individual, it is often in numeric value while the address is in alpha-numeric. In the same way, python has a wide range of standard data types that are important in defining the operations possible on them. These operations then define the storage method for each one of them. Python has five different data types. These include; strings, numbers, dictionary, tuple and list.

Strings

In python, a string is a contiguous set of characters that are represented in the form of quotation marks. It permits for the use of either single or double quotes. The slice operators are very important in this case for sub-setting the strings. These slice operators include ([] and :). In this case, the + sig is used for concatenation while the * is a repetition operator.

Let us consider the following example:

str = ‘Good morning’

print str will simply print the complete string, str [0] will print the first character of the string, str [2: ] prints the string beginning from the third character, str * 2 prints the string twice and finally str + “EXAM” will print the concatenated string.
The outcome will therefore, be as follows:
Good morning
G
od morning
Good morning Good morning
Good morningEXAM

Numbers

Numbers is a data type that stores numeric values. They are often created by simply assigning a value to them. For instance;
gme1 = 1
gme2 = 79
Additionally, you can delete a reference to a number object by simply using the command del.
Let us consider the following example:

del gme1[, gme2[, gme3[……..,gme Nth]]]]; also del gme or del gme1, gme2

Python also supports four types of numerical values. These include; complex numbers, floating point real values, integers and long integers.

For example:

Integers such as 20, 40 87, -456 among others
Long such as 537838933629843L, 672389004568930L among others
Float such as 798.2-E12, -35.48e100, 0.0 among others
Complex such as 3.41j, 4.53e-7j, -.678+0j among others

Judging from the long integer example that we have given above, we have used a capital L after the integer. This is because, python allows you to use lowercase l with long but then it is preferred that you use uppercase L in order to avoid any form of confusion with the number 1. On the other hand, a complex number often consists of an ordered pair of floating numbers that are denoted x + yj. In this case, x and y denote real numbers while j is an imaginary unit.

Lists

This is the most versatile of all data types in python. This is because, list often contains items that are separated either by commas or square brackets. To some degree, python’s list is quite similar to arrays in C programming language. The only one difference between them is the fact that all items that belong to a list can of different data types.
The values that are in a list often are accessible using the slice operators [] and :. This is mostly the case when it comes to indices ranging from 0 all the way to -1. Just like in strings, the + sign is also used for concatenation while the * sign is used for repetition.

Let us consider the following example:

list = [‘dghf’, 7893, 4.567, ‘brad’]
tinylist = [16793, ‘brad’]
print list command will print the complete list.
print list [0] will print the first element of the list
print list [1:3] will print elements of the list beginning from the second value to the third
print list [2:] will print elements of the list beginning from the third one
print tinylist * 2 will print list twice
print list + tinylist will simply combine the two lists into one (i.e. concatenate the two)

Tuples

This refers to a long sequence data type that is much like list. In other words, a tuple often is made up of a number of values that are separated by commas. However, unlike list, tuples are enclosed using parentheses. The major difference between tuples and lists is that lists are enclosed using square brackets and the elements there in can be changes as well as their sizes. In the case of tuples, elements are enclosed using parentheses and cannot be altered whatsoever. In other words, tuples are read-only lists.

For instance;

tuple = (‘dghf’, 7893, 4.567, ‘brad’)
tinytuple = [16793, ‘brad’]

When you attempt to update a tuple, you get a warning “invalid syntax with tuple”. This is because, updating a tuple is not allowed.

Dictionary

A python dictionary is more like a hash table type because they work like associative arrays or hashes often found in Perl. They also consist of key-value pairs. A dictionary key can take the form of any python type but in most cases, they are strings and numbers in nature. On the other hand, values often assume arbitrary python objects. Curly braces are used to enclose dictionaries and values in such a case are assigned and accessed using square braces.

For instance:

dict = {}
dict[‘one’] means one
dict[2] = “This is two”
tinydict = {weight:’89.6′,’code’:89234,’dept’:’Biochemistry’, name: ‘Martin’}

Therefore;

Print dict[‘one’] will print values for ‘one’ key, while dict[2] prints values for the 2 key. tinydict.keys prints all the keys and tinydict.values will print all the values. Finally, tinydict will print the complete dictionary.
One important point to note is that dictionaries do not have any concepts of order among their elements. Therefore, it is considered incorrect to state that the elements are ‘out of order’. This is because they are simply unordered.

Python Set

File Handling

File Operation

A file simply refers to a disk location in the computer that is used in storage of information in the non-volatile memory permanently. There are three major operations that we can do for a file. These include; opening the file, reading it and then finally closing it. This means that for us to read or write to a file, we first have to open it first and once we are done, we close it.

Opening a file

For us to open a file in python, we simply use a built-in function open().Using this function, we can simply open the file and make the modifications that we need.

To open the file module1 that we created above, we simply do this;

>> open(“module1”)
#or we can alternatively specify the path to that very file
>> open(“C:/Python36/README/module1”)
#alternatively, we can simply can specify the mode we want when opening a file. This means that we can write (w), read (r) or append (a) a file.
>>>> open(“module1”, ‘w’)

Closing a file

Once we have done the modifications that we needed with the file, we then have to close the file in the right way. In order to do this, we simply use the close() function to do so. It is important to note that, in spite python having a garbage collector, we cannot depend on it to close our files. To close the file we opened above, we simply do this;

>> y = open(“module1”)
#To close the file;
y.close()# this is not safe because if an exception takes place in the process of closing the file, then the code will exit without closing the file
#alternatively, you can do this
To close the file in a safer manner, we simply use the with statement to do this, without necessarily calling the close() function;
y = open (“module1”, encoding = ‘utf-8’)
#finally;
with open (“module1”, encoding = ‘utf-8’) as y

Writing to a file

For you to write to a file, you first have to open the file in write, append or exclusive creation modes. However, you have to be keen when using the write mode so that you do not overwrite what already exists in the file. To write, simply use the write () method. For instance;

with open(“module1”,’w’,encoding =’utf-8′)as y:
y.write(“my second file\n”)
y.write(“This file\n\n”)
y.write(“contains hundred lines\n”)

Reading from a file

To read the file, we simply do this by using the read mode while opening the file. There are several methods that we can employ in this case. We can use the read(size) to determine the size of the data. However, when you fail to specify the size parameter, it simply reads into the file and returns all the lines of the file to the end.

>>> y= open(“module1”,’r’, encoding=’utf-8′)
>>> y.read(5)
‘This reads the first 4 data of the file module1’>>> y.read(4)
‘Reads the next four lines of the file module1’

We can also use other methods to read into the file. These methods include seek () method and tell () methods which change the position of the cursor in the file and tells the position of the file respectively.

Let us consider the following examples;

>>> y.tell()# get the current file position
56
>>> y.seek(2)# bring file cursor to second line
2
>>>print(y.read())# read the entire file
#To read line by line, we simply use the for loop command
>>>for line in y:
…print(line,end=”)

Python Directory

Coming Soon.

Python Exception

Coming Soon.

Exception Handling

Coming Soon.

User-defined Exception

Coming Soon.

Python Namespace

Coming Soon.

Python Class

Coming Soon.

Python Inheritance

Coming Soon

Multiple Inheritance

Coming Soon.

Operator Overloading

Coming Soon.

Conclusion

Congratulations for completing your beginner basics on python programming language. From the information that we have learnt above, it is evident that Python programming language is very easy to learn and indeed very powerful. With Python, you can be able to carry out a number of tasks with just a simple code. However, this will not come easy without practice. Remember that practice makes perfect! Keep practicing and within no time, you will be able to write scripts that you can easily execute and complete tasks in a few minutes that would have otherwise taken weeks or even months. I believe that at this point, you are ready to proceed to more advanced levels of Python!