Python For DAM (DataScience, AI and Machine learning) Series

Python For DAM (DataScience, AI and Machine learning) Series

Chapter 1: Introduction to python

If you are new to learning python, then you have come to the right place. Welcome to the Python for DAM series, a weekly series for python beginners where I will be sharing with you the python fundamentals and tips you need to build a solid foundation for data science, AI and Machine learning. In this first chapter: Introduction to Python, we start from scratch! I will be introducing you to python in a quick and easy way and we will be covering the following:

  • Getting set: installing python and an IDE (Jupyter Notebooks)

  • Python basics: syntax, variables, data types and basic operations

  • Data Structures: lists, dictionaries and tupules

  • Control Flow: For and While loops

  • Functions: Defining and Calling functions

  • Modules

  • One last thing

1.Getting Set

Installation

We begin by downloading and installing python from the Official python website be sure to download and install the latest version that is compatible with your computer.

IDE (Intergrated Development Environment)

While python comes with an interactive interpreter (python shell) where you can run your python commands from, it is advisable to install and use an IDE instead. An IDE makes it easier for you to write and manage your code.

Some popular python IDEs are Pycharm, Jupyter notebooks and visual studio code.

I recommend Jupyter notebooks for a start as they are excellent for data science and machine learning tasks. You get to execute your code in individual code cells which make it easy to debug, run and re-run separate parts of your code effectively. You can also view visualisations and include documentation all in your Jupyter notebooks.

To get Jupyter notebook, download and install the anaconda navigator. once installed open it and navigate to the Jupyter notebook icon it should look like the one below

2. Basics: syntax, variables and data types

Syntax

Before we begin this section, I'll like to guide you to write your very first python code. Write the following code in the IDE of your choice, be sure to not to miss out the slightest detail.

print("Hello World")

If you've done that correctly, you should have an output of "Hello World". You can now see how easy to use python is, this is one of the many reasons it is so popular.

We can look at syntax as the way a thing is programmed/designed to work. In the python statement above, "print" is a function that commands the computer to display whatever message is put in the bracket. The message also has to be in double or single quotation marks so that the computer recognises that it isn't a command but a message that needs to be printed exactly as it was written in the quotation marks.

These are all part of the python's syntax and as we progress you will learn more of it. Another important python syntax you will be experiencing is the use of indentation. In python we use indents to define blocks of code and when you don't apply indents correctly, your code may not run as intended.

#sample of code with indentation
if True:
    print("Congratulation you've won the lottery")

notice the very first sentence written in gray beginning with # this is called a comment. In programming it is good practice to write comments that explain parts of your code. It makes it easier for you (or someone) to understand and pickup from where your left if you take a breakor when someone needs to take over from you or read your code. Simply add the # sign and write your comment python will ignore it and not read it as part of the code.

Variables

Variables are the labelling you give to your data when working with them in python. it makes your code more understandable and easier to correct (in case of error or when you want to make adjustments to your code).

#the following are examples of variables
Age = 32 
Name = 'Samson'
height = 6.2

Data Types

Python supports various data types and here are some of the most common ones.

#int(integer)
age = 32

#str(string)
Name = 'Samson'

#bool(boolean)
is_female = True

#float(floating point number)
height = 6.2

int (integer): these are whole numbers without decimal points.

bool (Boolean): these give an output that is either true or false.

str (string): these are mainly texts enclosed in single or double quotations.

float (floating point number): these are numbers with decimal points included.

Basic Operations

In python you can execute a range of basic mathematical operations, such as addition, subtraction, multiplication, division, modulus, exponent and more.

Here are a few examples to get you started.

#Some basic operations in python
a = 5
b = 2

print(a + b) #calculates and diplays the result of adding 5 and 2 a

print(a - b) #calculates and diplays the result of subtracting 2 from 5

print(a/b) #calculates and diplays the result of dividing 5 by 2

print(a*b) #calculates and diplays the result of multiplying 5 and 2

print(a%b) #calculates and diplays the remainder when 5 is divided by 2

print(a**b) #calculates and diplays the result of 5 raised to the power of 2

3. Data Structures

Now let's look at some common ways we would be working with data in python. As you start working with python, most of the data you will be working with will be in form of lists, dictionaries and tuples.

#Some common types of data structures.
my_list = [2, 3, 4, 5]

my_dict = {Name:"Samson", Age:32, height:6.2}

my_tuple = (1,2,3)

Notice the type of bracket used in each case. Aside from the bracket, each type of structure has distinctive characteristics for example in lists and dictionaries we can add remove or modify elements, but we can't do that in tuples.

4.Control Flow

Control flow allows us to instruct the computer on the order to carry out a sequence of commands, based on our specified conditions and control structures you supply. The two types of control flow we will be covering are conditional statements and loops.

Conditionals

This type of control flow uses the if, elif(else if) and else statements.

#example of conditional control flow
age = 23

if age < 18:
    print("You are a minor")
elif age >=18 and age< 65:
    print("You are an adult")
else:
    print("You are a senior citizen")

In the code above, when the age supplied is:

  • less than 18 the first block of code is executed.

  • equal to 18 or greater but less than 65 the second block of code is executed.

  • anything else, the last code block is executed.

Note that in this kind of statements you can have as many elif statements that your code needs as possible.

Loops

Loops are great for automating tasks that are repetitive. You simply have to write the code once; specify the variable you need to be changed in each run and add any condition your code needs.

There are two main loops that you will most likely come across and they are the for loops and the while loops.

For loops

For loops are great for when you want to carry out iteration on lists, tuples, strings or ranges.

#example of a for loop
fruits = [ 'apple', 'banana', 'mango', 'orange', 'pineapple' ]

for fruit in fruits:
    print(fruit)

In the example above the name of the list is fruits while fruit is used to represent each variable in the list. The for loop iterates through every item in the list and prints it.

While loops

While loops are used when you want to continue to run a certain iteration until a specified condition is met.

#example of while loops
count = 0
while count < 5:
    print(count)
    count += 1

In the code above we start by defining the variable count as 0, Then we write the while loop. We specify that the loop should continue to run as long as count is less than 5. We instruct that count should be printed in every run and after that, it should be increased by a value of 1.

The result should look like this:

0
1
2
3
4
#You can also write the same code as follows
count = 0
while count < 5:
    print(count)
    count = count + 1

5.Functions

Functions make blocks of code 'portable' so that we can easily reuse them without having to continuously write long blocks of code and run the risk of making mistakes whenever we rewrite them.

How do we use functions?

We start by Defining the function:

#defining a function called greet
def greet(name):
    print(f"Hello {name} !")

In the code above we just defined a function called greet . it requires us to input the name of the person to be greeted (for example Mary), then it displays "Hello Mary!"

(the 'f' in the print statement means format, it allows the name in the string to change according to what was writen in the function)

if we've defined the function then how do we use it? we use it by Calling the function.

#how to call the function you just created
greet("Mary")

As we said earlier your out put should be "Hello, Mary!. Be sure to add " " or ' ' any time you are inputting text that you want python to print as is so that it recognises that it is not a command.

#You can also write the same code as follows
def greet(name):
    print("Hello, " + name + "!")

6.Modules

Modules are a way of creating a library of codes that you can continuously reuse in a portable way (i.e. you won't have to constantly rewrite them). To create a module, you define your codes in a file and save it with the name you wish to call the module and add a .py extension.

For example, lets create a module called my_module( after writing the code, remember to save the file as my_module.py)

#my_module.py
def add (x, y):
    return (x + y)

def subtract(x, y):
    return (x - y)

def divide(x, y):
    return(x/y)

def multiply(x, y):
    return(x*y)

We've created a module that adds, subtracts, divides and multiplies.

Now whenever you are writing python codes you can use your module in any script you write by importing it as follows.

import my_module

result = my_module.add(7,8)
print(result)

result_1 = my_module.divide(9,3)
print(result_1)

That is how you create and use modules. You can effectively use modules to do much more complicated things as continue to learn and grow.

7.One Last Thing

  • Note that python is case sensitive.

  • There are few rules for naming variables, try to do a little research about it.

  • Python like mathematics is PRACTICE endeavor to practice, don't learn by reading or watching videos alone, practice as you learn and practice regularly. You either "use it or you lose it".

  • Learn by doing. Don't wait until you feel you have learnt everything in python before you start working with it, as soon as you have had some practice look for beginner friendly projects like this one to get your juices flowing.

  • Research is your friend and a key part of your learning, except you aren't practicing you will encounter many errors and or need to use many new codes, make research using google and/or chat gpt.

  • Be enthusiastic and don't give up. It may seem hard at first, but you will triumph if you persist.

  • Congratulations on making it to this point and see you on the next one!