Python For Beginners

The Ultimate Crash Course In Python. A Smart Guide To Mastering The Powerful Programming Language And Learn It Faster

Leonard Base

Table Of Contents

Introduction

Chapter 1

Basics Of The Python Programming Language

Chapter 2

Installation Of Python

Chapter 3

What Are Variables?

Chapter 4

A Deep Dive Into Data Types

Chapter 5

Type Conversion And Type Casting

Variable Scope And Lifetime In Python Functions

Chapter 6

Classes And Objects In Python

Chapter 7

Loops In Python

Chapter 8

Lifetime Of Variables And Functions

Chapter 9

Python Modules And Packages

Chapter 10

Dictionaries And Data Structures In Python

Chapter 11

Data Processing, Analysis, And Visualization

Conclusion

© Copyright 2020 by Leonard Base All rights reserved.

This document is geared towards providing exact and reliable information with regards to the topic and issue covered.

In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic means or in printed format. Recording of this publication is strictly prohibited and any storage of this document is not allowed unless with written permission from the publisher. All rights reserved.

The information provided herein is stated to be truthful and consistent, in that any liability, in terms of inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any legal responsibility or blame be held against the publisher for any reparation, damages, or monetary loss due to the information herein, either directly or indirectly.

Respective authors own all copyrights not held by the publisher.

The information herein is offered for informational purposes solely, and is universal as so. The presentation of the information is without contract or any type of guarantee assurance.

The trademarks that are used are without any consent, and the publication of the trademark is without permission or backing by the trademark owner. All trademarks and brands within this book are for clarifying purposes only and are the owned by the owners themselves, not affiliated with this documen t

Introduction

In this Python Beginner’s Guide, you are about to learn...

The Most Vital Basics of Python programming. Rapidly get the dialect and begin applying the ideas to any code that you compose.

The Useful features of Python for Beginners—including some ideas you can apply to in real world situations and even other programs.

Different mechanics of Python programming: control stream, factors, records/lexicons, and classes—and why taking in these center standards are essential to Python achievement.

Protest arranged programming, its impact on present-day scripting languages, and why it makes a difference.

This guide has been composed specifically for Newbies and Beginners. You will be taken through each step of your very first program, and we will explain each portion of the script as you test and analyze the data.

Machine learning is defined as a subset of something called artificial intelligence (AI). The ultimate goal of machine learning is to first comprehend the structure of the presented data and align that data into certain models that can then be understood and used by anyone.

Despite the fact that machine learning is a department in the computer science field, it truly is different from normal data processing methods.

In common computing programs, formulas are groups of individually programmed orders that are used by computers to determine outcomes and solve problems. Instead, machine-learning formulas allow computers to focus only on data that is inputted and use proven stat analysis in order to deliver correct values that fall within a certain probability. What this means is that computers have the ability to break down simple data models which enables it to automate routine decision-making steps based on the specific data that was inputted.

Any innovation client today has profited from machine learning. Facial acknowledgment innovation enables internet based life stages to enable clients to tag and offer photographs of companions.

Optical character acknowledgment (OCR) innovation changes over pictures of content into portable kind. Proposal motors, controlled by machine learning, recommend what motion pictures or TV programs to watch next in view of client inclinations. Self-driving autos that depend on machine learning on how to explore may soon be accessible to shoppers.

Machine learning is a ceaselessly growing field. Along these lines, there are a few things to remember as you work with machine learning philosophies, or break down the effect of machine learning forms.

In this book, we'll look at the normal machine learning strategies for managed and unsupervised learning, the basic algorithmic methodologies including the k-closest neighbor calculation, specific decision tree learning, and deeply impactful techniques. We will also investigate which programming is most used in machine learning, giving you a portion of the positive and negative qualities.

Moreover, we'll talk about some important biases that are propagated by machine learning calculations, and consider what can be done to avoid biases affecting your algorithm building.

There are plenty of books on this subject on the market. Thanks for choosing this one! Every effort was made to ensure it’s full of useful information as possible, please enjoy!

Chapter 1

Basics of the Python Programming Language

Python is an awesome decision on machine learning for a few reasons. Most importantly, it's a basic dialect at first glance. Regardless of whether you're not acquainted with Python, getting up to speed is snappy in the event that you at any point have utilized some other dialect with C-like grammar.

Second, Python has an incredible network which results in great documentation and inviting and extensive answers in Stack Overflow (central!).

Third, coming from the colossal network, there are a lot of valuable libraries for Python (both as "batteries included" an outsider), which take care of essentially any issue that you can have (counting machine learning).

Wait I thought this machine language was slow?

Unfortunately, it is a very valid question that deserves an answer. Indeed, Python is not at all the fastest language on the planet.

However, here's the caveat: libraries can and do offload the costly computations to the substantially more performant (yet much harder to use) C and C++ are prime examples. There's NumPy, which is a library for numerical calculation. It is composed in C, and it's quick. For all intents and purposes, each library out there that includes serious estimations utilizes it—every one of the libraries recorded next utilize it in some shape. On the off chance that you read NumPy, think quick .

In this way, you can influence your computer scripts to run essentially as quick as handwriting them out in a lower level dialect. So there's truly nothing to stress over with regards to speed and agility.

If you want to know which Python libraries you should check out. Try some of these.

“Scikit-learn”

Do you need something that completely addresses everything from testing and training models to engineering techniques?

Then scikit-learn is your best solution. This incredible bit of free programming gives each device important to machine learning and information mining. It's the true standard library for machine learning in Python; suggested for the vast majority of the 'old' ML calculations.

This library does both characterization and relapse, supporting essentially every calculation out there (bolster vector machines, arbitrary timberland, Bayes, you name it). It allows a simple exchanging of calculations in which experimentation is a lot simpler. These 'more seasoned' calculations are shockingly flexible and work extremely well in a considerable amount of problems and case studies.

In any case, that is not all! Scikit-learn additionally does groupings, plural dimensionalities, and so on. It's likewise exceedingly quick since it keeps running on NumPy and SciPy.

Look at a few cases to see everything this library is prepared to do, the instructional exercises on the website, and the need to figure out if this is a good fit.

“NLTK”

While not a machine learning library essentially, NLTK is an unquestionable requirement when working with regular computer language. It is bundled with a heap of Datasets and other rhetorical data assets, which is invaluable for preparing certain models. Aside from the libraries for working with content, this is great for determining capacities, for example, characterization, tokenization, stemming, labeling, and parsing—that's just the beginning.

The handiness of having the majority of this stuff perfectly bundled can't be exaggerated. In case you are keen on regular computer language look at a few of their website's instructional exercises!

“Theano”

Utilized generally in research and within the scholarly community, Theano is the granddad of all deeply profound learning systems. Since it is written in Python, it is firmly incorporated with NumPy.

Theano enables you to make neural systems which are essential scientific articulations with multidimensional clusters. Theano handles this so you that you don't need to stress over the real usage of the math included.

It bolsters offloading figures to a considerably speedier GPU, which is an element that everybody underpins today, yet, back when they presented it, this wasn't the situation. The library is extremely developed now and boasts an extensive variety of activities, which is extraordinary with regards to contrasting it and other comparative libraries.

The greatest grievance out there about Theano is the API might be cumbersome for a few, making the library difficult to use for beginning learners. In any case, there are tools that relieve the agony and makes working with Theano pretty straightforward, for example, try using Keras, or Blocks, and even Lasagne.

“TensorFlow”

The geniuses over at Google made TensorFlow for inside use in machine learning applications and publicly released it in late 2015. They needed something that could supplant their more established, non-open source machine learning structure, DistBelief . It wasn't sufficiently adaptable and too firmly ingrained into their foundation. It was to be imparted to different analysts around the globe .

Thus, TensorFlow was made. Despite their slip-ups in the past, many view this library as a much needed change over Theano, asserting greater adaptability and more instinctive API. Another great benefit is it can be utilized to create new conditions, supporting tremendous amounts of new GPUs for training and learning purposes. While it doesn't bolster as wide a scope of functionality like Theano, it has better computational diagram representations.

TensorFlow is exceptionally famous these days. In fact, if you are familiar with every single library on this list, you can agree that there has been a huge influx in the number of new users and bloggers in this library and its functionality. This is definitely a good thing for beginners.

“Keras”

Keras is a phenomenal library that gives a top-level API to neural systems and is best for running alongside or on top of Theano or TensorFlow. It makes bridling full intensity of these intricate bits of programming substantially simpler than utilizing them all by themselves. The greatest benefit of this library is its exceptional ease of understanding, putting the end users’ needs and experiences as its number one priority. This cuts down on a number of errors.

It is also secluded; which means that individual models like neural layers and cost capacities can be grouped together with little to no limitations. This additionally makes the library simple to include new models and interface them with the current ones.

A few people have called Keras great that it is similar to cheating on your exam. In case you're beginning with higher learning in this area, take the illustrations and examples and discover what you can do with it. Try exploring.

Furthermore, by chance that you need to START learning, it is recommended that you begin with their instructional exercises and see where you can go from that point .

Two comparative choices are Lasagne and Blocks; however, they just keep running on Theano. If you attempted Keras and have difficulty, perhaps, experiment with one of these contrasting options to check whether they work out for you.

“PyTorch”

If you are looking for a popular deep learning library, then look no further than Torch, which is written in the language called Lua. Facebook recently open-sourced a Python model of Torch and named it PyTorch, which allows you to easily use the exact same libraries that Torch uses, but from Python, instead of the original language, Lua.

PyTorch is significantly easier for debugging because of one major difference between Theano, TensorFlow, and PyTorch. The older versions use allegorical computation while the newer does not. Allegorical computation is simply a way of saying that coding an operation, for example, ‘a + b’, will not be computed when that line is read. Before it is executed it must be translated into what is called CUDA or C. This makes the debugging much harder to execute in Theano/TensorFlow since this error is more difficult to pinpoint with a specific line of code. It’s basically harder to trace back to the source. Debugging is not one of this library’s strongest features.

This is extremely beginner-friendly; as your learning increases, try some of their more advanced tutorials and examples.

HISTORY OF PYTHON

Python was invented in the later years of the 1980s. Guido van Rossum, the founder, started using the language in December 1989. He is Python's only known creator and his integral role in the growth and development of the language has earned him the nickname "Benevolent Dictator for Life". It was created to be the successor to the language known as ABC.

The next version that was released was Python 2.0, in October of the year 2000 and had significant upgrades and new highlights, including a cycle-distinguishing junk jockey and back up support for Unicode. It was most fortunate, that this particular version, made vast improvement procedures to the language turned out to be more straightforward and network sponsored.

Python 3.0, which initially started its existence as Py3K. Funny right? This version was rolled out in December of 2008 after a rigorous testing period. This particular version of Python was hard to roll back to previous compatible versions which are the most unfortunate. Yet, a significant number of its real highlights have been rolled back to versions 2.6 or 2.7 (Python), and rollouts of Python 3 which utilizes the two to three utilities, that helps to automate the interpretation of the Python script.

Python 2.7's expiry date was originally supposed to be back in 2015, but for unidentifiable reasons, it was put off until the year 2020. It was known that there was a major concern about data being unable to roll back but roll FORWARD into the new version, Python 3. In 2017, Google declared that there would be work done on Python 2.7 to enhance execution under simultaneously running tasks.

BASIC FE ATURES OF PYTHON

Python is an unmistakable and extremely robust programming language that is object-oriented based almost identical to Ruby, Perl, and Java.

A portion of Python's remarkable highlights:

Python uses a rich structure, influencing, and composing projects that can be analyzed simpler.

It is a simple to utilize dialect that makes it easy to get your program working. This makes Python perfect for model improvement and other specially appointed programming assignments, without trading off viability.

It accompanies a huge standard library that backs tons of simple programming commands, for example, extremely seamless web server connections, processing and handling files, and the ability to search through text with commonly used expressions and commands.

Python's easy to use interactive interface makes it simple to test shorter pieces of coding. It also comes with IDLE which is a "development environment".

Python effortlessly extended out by including new modules executed in a source code like C or C++.

Python can also be inserted into another application to give an easily programmed interface.

Python will run anyplace, including OS X, Windows Environment, Linux, and even Unix, with informal models for the Android and iOS environments.

Python can easily be recorded, modified and re-downloaded and distributed, be unreservedly adjusted and re-disseminated. While it is copyrighted, it's accessible under open source. Ultimately, Python is a free software.

Common Programming Language Features of Python

A huge array of common data types: floating point numbers, complex numbers, infinite length integers, ASCII strings, and Unicode, as well as a large variety of dictionaries and lists.

Python is guided in an object-oriented framework, with multiple classes and inheritance.

Python code can be bundled together into different modules and packages.

Python is notorious for being a much cleaner language for error handling due to the catching and raising of exceptions allowed.

Information is firmly and progressively composed. Blending incongruent data types, for example, adding a string and a number together, raises an exception right away where errors are caught significantly sooner than later.

Python has advanced coding highlights such as comprehending lists and iterators.

Python's programmed memory administration liberates you from having to physically remove unused or unwanted code.

Chapter 2

Installation of Python

Python is both procedural and object-oriented coding language. It has a straightforward syntax. Python is cross-platform implying that it can be run on different Operating Systems environments such as Linux, Windows platform, Mac OS X platform, UNIX platform and can be ported to .NET and Java virtual machines. Python is free and open source. While most recent versions of Mac and Linux have Python preinstalled, it is recommended that one installs and runs the current version.

Installing Python

Most recent versions of Linux and Mac have Python already installed in them. However, you might need to install Python, and the following are the steps for installing Python in Windows, Mac OS X or Linux.

Installing Python in Macintosh Operating System X

a)    Visit Download Python page which is the credible site and click “Download Python 3.7.2 (The version may differ from the one stated here).

b)    When the download completes, click open the package and follow the instructions given. The installation should complete with “The installation was successful” prompt.

c)     Now, visit Download Notepad++ and download the text editor and install it by opening the package and following the message prompts. The Notepad++ text editor is free and suited to help write source code (raw text programming words). 

Installing Python in Linux Operating Systems

v.    It is now time to issue instructions to run the source code on your OS (Operating System )

Installing Python in Windows Operating System

a)    Visit Download Python site which is the recommended site and click “Download Python 3.7.2 (The version may differ from the one stated here).

b)    When your download completes, open the package by clicking and follow the guidelines given. The Python installation should complete with “The installation was successful” prompt. When you install Python successfully, it also installs a program known as IDLE along with it. IDLE is a graphical user interface when working with Python.

c)     Now, visit Download Notepad++  and download the text editor and install it by opening the package and following the message prompts. The Notepad++ text editor is free and suited to help write source code (raw text programming words). 

How to Run Python

Before we start running our first Python program, it is important that we understand how we can run python programs. Running or executing or deploying or firing a program simply means that we are making the computer process instructions/lines of codes. For instance, if the lines of codes (program) require the computer to display some message, then it should. The following are the ways or mode of running python programs. The interpreter is a special program that is installed when installing the Python package and helps convert text code into a language that the computer understands and can act on it (executing).

Immediate Mode

It is a way of running python programs that are not written in a file. We get into the immediate mode by typing the word python in the command line and which will trigger the interpreter to switch to immediate mode. The immediate mode allows typing of expressions directly, and pressing enter generates the output. The sign below is the Python prompt:

>> >

The python prompt instructs the interpreter to accept input from the user. For instance, typing 2+2 and pressing enter will display 4 as the output. In a way, this prompt can be used as a calculator. If you need to exit the immediate mode, type quit() or exit().

Now type 5 +3, and press enter, the output should be 8. The next mode is the Script Mode.

Script Mode

The script mode is used to run a python program written in a file; the file is called a script.

Integrated Development Environment (IDE)

An IDE provides a convenient way of writing and running Python programs. One can also use text editors to create a python script file instead of an IDE by writing lines of codes and saving the file with a .py extension. However, using an IDE can simplify the process of writing and running Python programs. The IDEL present in the Python package is an example of an IDE with a graphical user interface and gets installed along with the Python language. The advantages of IDE include helping getting rid of repetitive tasks and simplify coding for beginners. IDE provides syntax highlighting, code hinting, and syntax checking among other features. There also commercial IDE such as the PyScripter IDE that performs most of the mentioned functions.

Note

We have presented what Python is, how to download and install Python, the immediate and script modes of Python IDE, and what is an IDE.

Your First Program in Python

The rest of the illustrations will assume you are running the python programs in a Windows environment.

Start IDLE

Navigate to the File menu and click New Window

Type the following:

print (“Hello World!”)

On the file, menu click on Save. Type the name of myProgram1.py

Navigate to Run and click Run Module to run the program.

The first program that we have written is known as the “Hello World!” and is used to not only provide an introduction to a new computer coding language but also test the basic configuration of the IDE. The output of the program is “Hello World!” Here is what has happened, the Print() is an inbuilt function, it is prewritten and preloaded for you, is used to display whatever is contained in the () as long as it is between the double quotes. The computer will display anything written within the double quotes.

Assignment

Now write and run the following python programs:

a)    print(“I am now a Python Language Coder!”)

b)     print(“This is my second simple program!”)

c)      print(“I love the simplicity of Python”)

d)    print(“I will display whatever is here in quotes such as owyhen2589gdbnz082”)

Now we need to write a program with numbers, but before writing such a program, we need to learn something about Variables and Types.

Remember python is object-oriented and it is not statically typed which means we do not need to declare variables before using them or specify their type. Let us explain this statement; an object-oriented language simply means that the language supports viewing and manipulating real-life scenarios as groups with subgroups that can be linked and shared mimicking the natural order and interaction of things. Not all programming languages are object-oriented; for instance, Visual C programming language is not object-oriented. In programming, declaring variables means that we explicitly state the nature of the variable. The variable can be declared as an integer, long integer, short integer, floating integer, a string, or as a character including if it is accessible locally or globally. A variable is a storage location that changes values depending on conditions .

For instance, number1 can take any number from 0 to infinity. However, if we specify explicitly that int number1 it then means that the storage location will only accept integers and not fractions for instance, fortunately or unfortunately, python does not require us to explicitly state the nature of the storage location (declare variables) as that is left to the python language itself to figure out that.

Before tackling types of variables and rules of writing variables, let us run a simple program to understand what variables when coding a python program are.

Start IDLE

Navigate to the File menu and click New Window

Type the following:

num1=4

num2=5

sum=num1+num2

print(sum)

On the file, menu click on Save. Type the name of myProgram2.py

Navigate to Run and click Run Module to run the program.

The expected output of this program should be “9” without the double quotes.

Explanation

At this point, you are eager to understand what has just happened and why the print(sum) does not have double quotes like the first programs we wrote. Here is the explanation.

The first line num1=4 means that variable num1(our shortened way of writing number1, first number) has been assigned 4 before the program runs .

The second line num2=5 means that variable num2(our shortened way of writing number2, second number) has been assigned 5 before the program runs.

The computer interprets these instructions and stores the numbers given

The third line sum=num1+num2 tells the computer that takes whatever num1 has been given and add to whatever num2 has been given. In other terms, sum the values of num1 and num2.

The fourth line print(sum) means that display whatever sum has. If we put double quotes to sum, the computer will display the word sum and not the sum of the two numbers! Remember that cliché that computers are garbage in and garbage out. They follow what you give them!

Note

+ is an operator for summing variables and has other users that will be discussed later.

Now let us try out three Assignments involving numbers before we explain types of variables and rules of writing variables so that you get more freedom to play with variables. Remember variables values vary for instance num1 can take 3, 8, 1562, 1.

Follow the steps of opening the Python IDE and do the following:

The output should be 54

num1=43

num2=11

sum=num1+num2

print(sum)

The output should be 167

num1=101

num2=66

sum=num1+num 2

print(sum)

The output should be 28

num1=9

num2=19

sum=num1+num2

print(sum)

Variables

We have used num1, num2, and sum and the variable names were not just random, they must follow certain rules and conventions. Rules are what we cannot violate while conventions are much like the recommended way. Let us start with the rules:

The Rules of When Naming Variables in Python

a)    Variable names should always start with a letter or an underscore, i.e.

num1

_num1

b)    The remaining part of the variable name may consist of numbers, letters, and underscores, i.e.

number1

num_be_r

c)     Variable names are case sensitive meaning that capital letters and non-capital letters are treated differently.

Num1 will be treated differently with num1.

Assignment

Write/suggest five variables for:

Hospital department.

Bank.

Media House.  

Given scri=75, scr4=9, sscr2=13, Scr=18

The variable names above are supposed to represent scores of students. Rewrite the variables to satisfy Python variable rules and conventions.

Conventions When Naming Variables in Python

As earlier indicated, conventions are not rules per se are the established traditions that add value and readability to the way we name variables in Python.

Uphold readability. Your variables should give a hint of what they are handling because programs are meant to be read by other people other than the person writing them. Number1 is easy to read compared to n1. Similarly, first_name is easy to read compared to firstname or firstName or fn. The implication of all these is that both are valid/acceptable variables in python, but the convention is forcing us to write them in an easy to read form.

Use descriptive names when writing your variables. For instance, number1 as a variable name is descriptive compared to yale or mything. In other words, we can write yale to capture values for number1, but the name does not outrightly hint what we are doing. Remember when writing programs; assume another person will maintain them. The person should be able to quickly figure out what the program is all about before running it.

Due to confusion, avoid using the uppercase ‘O,’ lowercase letter ‘l’ and the uppercase letter ‘I’ because they can be confused with numbers. In other terms, using these letters will not be a violation of writing variables, but their inclusion as variable names will breed confusion.

Assignment 1

Re-write the following variable names to (1) be valid variable names and follow (2) conventions of writing variable names.

23doctor

line1

Option3

iMydesk

#cup3

Assignment 2

Write/Suggest variable names that are (1) valid and (2) conventional.

You want to sum three numbers.

You want to store the names of four students.

You want to store the names of five doctors in a hospital.

Summary

Variables are storage locations that a user specifies before writing and running a python program. Variable names are labels of those storage locations. A variable holds a value depending on circumstances. For instance, doctor1 can be Daniel, Brenda or Rita. Patient1 can be Luke, William or Kelly. Variable names are written by adhering to rules and conventions. Rules are a must while conventions are optional but recommended as they help write readable variable names. When writing a program, you should assume that another person will examine or run it without your input and thus should be well written. The next chapter will discuss Variables. In programming, declaring variables means that we explicitly state the nature of the variable. The variable can be declared as an integer, long integer, short integer, floating integer, a string, or as a character including if it is accessible locally or globally. A variable is a storage location that changes values depending on conditions. Use descriptive names when writing your variables.

Chapter 3

What are Variables?

Variables are names for values. In Python the = symbol assigns the value on the right to the name on the left. The variable is created when a value is assigned to it. Here is a Python program that assigns an age to a variable age and a name in quotation marks to a variable first_name.

age = 42

first_name = 'Eunice'

Types of Variables

Now that we have defined what are variables are and the rules to write variable names in the last chapter, let us explore different types of variables.

a)     Numbers

The Python accommodates two kinds of numbers, namely floating point numbers and integer numbers. Python also supports complex numbers. When you sign a value to a number, then a number object is created. For example:

number3 =9

number4=12

Different Numerical Types Supported in Python

•    long for example 681581903L

•    int for example 11, 123, -151

•    float for example 0.5, 23.1, -54.2

•    complex for example 4.12 j

Exercise

Identify the type of numerical below:

a.    234, 19, 312

b.    4.56, 2.9, 9.3

c.    76189251468290127624471

Identify the numerical type suitable for the following contexts:

d.    Salary amount.

e.    Counting the number of students in a class.

f.    Getting the census figure in an entire country of China.

b)     Strings

A single or double quote in Python is used to indicate strings. The subsets of strings can be taken by using the slice operator ([:]) and []) with indexes beginning at () in the start of the string and operating their way from -1 at the end. Strings can be joined using the + (plus) sign known as the concatenation operator. The asterisk (*) is used as a repetition operator. Remember counting in programming starts from index zero (the first value)!

Note

The # (hash sign) is used to indicate a single line comment. A comment is a descriptive information about a particular line(s) of code. The comment is normally ignored by when running the program. The comment should be written after the # sign in python. Comments increase the readability of the program written.

Assignment

You will key in/type the following program statement:

str = 'I think I am now a Programmer.'

a.    Write a program statement that will display the entire string/statement above .

b.    Write a program statement to display characters of the string from the second character to the sixth.

c.    Write a single program statement that will display the entire string two times. ( use *).

d.    Write a program statement that will add the following at the end of the statement above, “ of Python.”

Identifiers and Keywords

At this point, you have been wondering why you must use print and str in that manner without the freedom or knowledge of why the stated words have to be written in that manner. The words print and str constitute a special type of words that have to be written that way always.   Each programming language has a set of keywords. In most cases, some keywords are found across several programming languages. Keywords are case sensitive in python meaning that we have to type them in their lowercase form always. Keywords cannot be used to name a function (we will explain what it is later), name of a variable.

There are 33 keywords in Python, and all are in lowercase save for None, False, and True. They must always be written as they appear below:

Note

The print() and str are functions, but they are inbuilt/preloaded functions in Pythons. Functions are a set of rules and methods that act when invoked. For instance, the print function will display output when activated/invoked/called. At this point, you have not encountered all of the keywords, but you will meet them gradually. Take time to skim through, read and try to recall as many as you can.

Assignment

Identify what is wrong with the following variable names (The Assignment requires recalling what we have learned so far)

a.    for=1

b.    yield= 3

c.    34ball

d.    m

Comments and Statements

Statements in Python

A statement in Python refers to instructions that a Python interpreter can work on/execute. An example is str=’ I am a Programmer’ and number1=3. A statement having an equal sign(=) is known as an assignment statement. They are other types of statements such as the if, while, and for which will be handled later.

Assignment

a. Write a Python statement that assigns the first number value of 18.

b. Write a programming statement that assigns the second number value of 21.

c.  What type of statements are a. and b. above?

Multi-line Python Statement

Spreading a statement over multiple lines is possible. Such a statement is known as a multi-line statement. The termination of a programming statement is denoted by new line character. To spread a statement overs several lines, in Python, we use the backslash (\) known as the line continuation character. An example of a multi-line statement is:

sum=3+6+7+\

9+1+3+\

11+4+8

The example above is also known as an explicit line continuation. In Python, the square brackets [] denotes line continuation similar to parenthesis/round brackets (), and lastly braces {}. The above example can be rewritten as

sum=(3+6+7+

9+1+3+

11+4+8 )

Note

We have dropped the backslash(\) known as the line continuation character when we use the parenthesis(round brackets) because the parenthesis is doing the work that the line continuation \ was doing.

Solved Question

Why do you think multi-line statements are necessary we can simply write a single line, and the program statement will run just fine?

Answer

Multi-line statements can help improve formatting/readability of the entire program. Remember, when writing a program always assume that it is other people who will use and maintain it without your input.

Assignment

Rewrite the following program statements using multi-line operators such as the \, [],() or {} to improve readability of the program statements.

a.    total=2+9+3+6+8+2+5+1+14+5+21+26+4+7+13+31+24

b.    count=13+1+56+3+7+9+5+12+54+4+7+45+71+4+8+5

Semicolons are also used when creating multiple statements in a single line. Assume we have to assign and display the age of four employees in a python program. The program could be written as:

employee1=25; employee2=45; employee3=32; employee4=43.

Indentation in Python

Indentation is used for categorization program lines into a block in Python. The amount of indentation to use in Python depends entirely on the programmer. However, it is important to ensure consistency. By convention, four whitespaces are used for indentation instead of using tabs. For example :

Note

I will explain what kind of program this is later. Indentation in Python also helps make the program look neat and clean. Indentation creates consistency. However, when performing line continuation indentation can be ignored. Incorrect indentation will create an indentation error. Correct python programs without indentation will still run, but they might be neat and consistent from human readability view.

Comments in Pythons

When writing python programs and indeed any programming language, comments are very important. Comments are used to describe what is happening within a program. It becomes easier for another person taking a look at a program to have an idea of what the program does by reading the comments in it. Comments are also useful to a programmer as one can forget the critical details of a program written. The hash (#) symbol is used before writing a comment in Python. The comment extends up to the newline character. The python interpreter normally ignores comments. Comments are meant for programmers to understand the program better.

Example

i.    Start IDLE

ii.   Navigate to the File menu and click New Window

iii.  Type the following:

#This is my first comment

#The program will print Hello World

Print(‘Hello World’)   #This is an inbuilt function to display

iv.    On the file, menu click on Save. Type the name of myProgram5.py

Navigate to Run and click Run Module to run the program

Assignment

This Assignment integrates most of what we have covered so far.

Write a program to sum two numbers 45, and 12 and include single line comments at each line of code.

Write a program to show the names of two employees where the first employee is “Daisy” and the second employee is “Richard.” Include single comments at each line of code.

Write a program to display the student registration numbers where the student names and their registration are: Yvonne=235, Ian=782, James=1235, Juliet=568.

Multi-line Comments

Just like multi-line program statements we also have multi-line comments. There are several ways of writing multi-line comments. The first approach is to type the hash (#) at each comment line starting point.

For Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

#I am going to write a long comment line

#the comment will spill over to this line

#and finally end here.

The second way of writing multi-line comments involves using triple single or double quotes: ‘’’ or”. For multi-line strings and multi-line comments in Python, we use the triple quotes. Caution: When used in docstrings they will generate extra code, but we do not have to worry about this at this instance.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following :

“This is also a great

illustration of

a multi-line comment in Python.”

Python’s Docstring

In Python, docstring refers to words offering description and are written as the initial program statement in a function, module, method, or class definition. (We will handle this later on). Docstrings in Python are written using triple quotes.

Assignment

This Assignment will utilize several concepts that we covered earlier.

Given the following program statement: Color1=’red’; color1=’blue’; CoLor1=’yellow’ explain why all the three will be treated as different variables in Python.

Consider the following Python program and identify what is wrong with it.

student1_age=23                        #This is the age of the first student

student2_age=19                                       #This is the age of the student

sotal_age=student1_age +student2_age     #Getting the sum of the ages of the

print(age)                             #Displaying their ages

c.    Rewrite b. above to be a valid Python program

Basic Operators in Python

So far we have been using the summation (+) operator, and it also doubles up as a concatenation operator (appending statements). However, we want to expand our list of operators, and this leads us to basic operators in Python .

Arithmetic Operators

The multiplication (*), division (/), subtraction (-), and addition (+) are the arithmetic operators used to manipulate numbers.

Assignment

Write the following programs and run it

a.    Difference

number1=35                #declaring first number

number2= 12                #declaring second number

difference=number2-number1    #declaring what the difference does

print(difference)            #Calling the print function to display what difference has

b.    Multiplication

number1=2                #declaring first number   

number2= 15                #declaring second number

product=number1*number2        #declaring what the product does

print(product)                #Calling the print function to display what product has

c.    Division

number1=10                #declaring first number   

number2= 50                #declaring second number

division=number2/number1        #declaring what the division does

print(division)                #Calling the print function to display what product has

Modulus

The modulus operator is used to return the integer remainder after division. The modulus=dividend%divisor .

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number1=2                #declaring first number   

number2= 15                #declaring second number

remainder=number2%number1    #declaring what the remainder does

print(remainder)                #Calling the print function to display remainder has

Squaring and Cubing in Python

Squaring a number-number**2

Cubing a number-number**3

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Square of 3 in Python will be 3**2

Cube of 5 in Python will be 5**3

Square of 3

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number=3                 #declaring  variable number and assigning value 3

square=number** 2

print(square)                #Calling the print function to display what square has

Cube of 5

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number=5                #declaring  variable number and assigning value 5

cube=number**3

print(cube)                #Calling the print function to display what cube has

Assignment

Use python operators to write and run a python program that finds the following:

a.    Cube of 7

b.    Square of 15

c.    Cube of 6

d.    Square of 11

e.    Cube of 8

f.    Square of 13

Note

We can still multiply 2 two times to get the square of 2. The reason for using the square and cube operators is to help us write compact and efficient code. Remember that the interpreter goes through each line including comments only that it ignores comments. Using the cube and square operators helps compact code and increase the efficiency of interpretation including troubleshooting as well as human readability of the code .

Operators with String in Python

In Python certain operators are used to help in concatenating strings. The addition sign is used to concatenate strings in Python.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

status=” I am happy I know” + “how to write programs in Python.”   

print(status)

Python Multiplication of a string to create a sequence

many_words=”Great Programmer” * 5

print(many_words)

Assignment

a.    Use a concatenation operator to join the following strings in Python

I have realized

that programming is a passion,

dedication and frequent practice.

b.    Use an operator to generate ten times the following string

Happy

Summary

Chapter 4

A Deep Dive into Data Types

Numbers

As mentioned earlier, Python accommodates floating, integer and complex numbers. The presence or absence of a decimal point separates integers and floating points. For instance, 4 is integer while 4.0 is a floating point number.

On the other hand, complex numbers in Python are denoted as r+tj where j represents the real part and t is the virtual part.  In this context the function type() is used to determine the variable class. The Python function is instance() is invoked to make a determination of which specific class  function originates from.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number=6

print(type(number))    #should output class int

print(type(6.0))    #should output class float

complex_num=7+5j

print(complex_num+5)

print(isinstance(complex_num, complex)) #should output Tru e

Important: Integers in Python can be of infinite length. Floating numbers in Python are assumed precise up to fifteen decimal places.

Number Conversion

This segment assumes you have prior basic knowledge of how to manually or using a calculator to convert decimal into binary, octal and hexadecimal. Check out the Windows Calculator in Windows 10, Calculator version 10.1804.911.1000 and choose programmer mode to automatically convert.

Programmers often need to convert decimal numbers into octal, hexadecimal and binary forms. A prefix in Python allows denotation of these numbers to their corresponding type.

Number System  Prefix

Octal    ‘0O’ or '0o'

Binary    ‘0B' or '0b'

Hexadecimal   '0X or '0x'

Example

print(0b1010101)  #Output:85

print(0x7B+0b0101)  #Output: 128 (123+5)

print(0o710)   #Output:710

Assignment

Create a program in Python to display the following:

i) 0011 11112

ii) 7478

iii) 931 6

Type Conversion

Sometimes referred to as coercion, type conversion allows us to change one type of number into another. The preloaded functions such as float(), int() and complex() enable implicit and explicit type conversions. The same functions can be used to change from strings.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

int(5.3)   #Gives 5

int(5.9)   #Gives 5

The int() will produce a truncation effect when applied to floating numbers. It will simply drop the decimal point part without rounding off. For the float() let us take a look:

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

float(6)   #Gives 6.0

ccomplex(‘4+2j’) #Gives (4+2j)

Assignment

Apply the int() conversion to the following:

a. 4.1

b. 4.7

c. 13.3

d. 13.9

Apply the float() conversion to the following :

e. 7

f. 16

g. 19

Decimal in Python

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

(1.2+2.1)==3.3  #Will return False, why?

Explanation

The computer works with finite numbers and fractions cannot be stored in their raw form as they will create infinite long binary sequence.

Fractions in Python

The fractions module in Python allows operations on fractional numbers.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Important

Creating my_fraction from float can lead to unusual results due to the misleading representation of binary floating point.

Mathematics in Python

To carry out mathematical functions, Python offers modules like random and math.

Start IDLE .

Navigate to the File menu and click New Window.

Type the following:

import math

print(math.pi)   #output:3.14159….

print(math.cos(math.pi)) #the output will be -1.0

print(math.exp(10))  #the output will be 22026.4….

print(math.log10(100)) #the output will be 2

print(math.factorial(5)) #the output will be 120

Exercise

Write a python program that uses math functions from the math module to perform the following:

a. Square of 34

b. Log1010000

c. Cos 45 x sin 90

d. Exponent of 20

Random function in Python

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

import math

print(random.shuffle_num(11, 21))

y=[‘f’,’g’,’h’,’m’]

print(random.pick(y))

random.anypic(y )

print(y)

print(your_pick.random())

Lists in Python

We create a list in Python by placing items called elements inside square brackets separated by commas. The items in a list can be of mixed data type.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_mine=[]   #empty list

list_mine=[2,5,8]  #list of integers

list_mine=[5,”Happy”, 5.2] #list having mixed data types

Assignment

Write a program that captures the following in a list: “Best”, 26,89,3.9

Nested Lists

A nested list is a list as an item in another list.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_mine=[“carrot”, [9, 3, 6], [‘g’]]

Exercise

Write a nested for the following elements: [36,2,1],”Writer”,’t’,[3.0, 2.5]

Accessing Elements from a Lis t

In programming and in Python specifically, the first time is always indexed zero. For a list of five items we will access them from index0 to index4. Failure to access the items in a list in this manner will create index error. The index is always an integer as using other number types will create a type error. For nested lists, they are accessed via nested indexing.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_mine=[‘b’,’e’,’s’,’t’]

print(list_mine[0])   #the output will be b

print(list_mine[2])   #the output will be s

print(list_mine[3])   #the output will be t

Exercise

Given the following list:

your_collection=[‘t’,’k’,’v’,’w’,’z’,’n’,’f’]

a. Create a program in Python to display the second item in the list

b. Create a program in Python to display the sixth item in the last

c. Create a program in Python to display the last item in the list.

Nested List Indexing

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

nested_list=[“Best’,[4,7,2,9]]

print(nested_list[0][1 ]

Python Negative Indexing

For its sequences, Python allows negative indexing. The last item on the list is index-1, index -2 is the second last item and so on.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_mine=[‘c’,’h’,’a’,’n’,’g’,’e’,’s’]

print(list_mine[-1])   #Output is s

print(list_mine [-4]) ##Output is n

Slicing Lists in Python

Slicing operator(full colon) is used to access a range of elements in a list.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_mine=[‘c’,’h’,’a’,’n’,’g’,’e’,’s’]

print(list_mine[3:5])   #Picking elements from the 4 to the sixth

Example

Picking elements from start to the fifth

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

print(list_mine[:-6])

Example

Picking the third element to the last .

print(list_mine[2:])

Exercise

Given class_names=[‘John’, ‘Kelly’, ‘Yvonne’, ‘Una’,’Lovy’,’Pius’, ‘Tracy’]

a. Write a python program using slice operator to display from the second students and the rest.

b. Write a python program using slice operator to display first student to the third using negative indexing feature.

c. Write a python program using slice operator to display the fourth and fifth students only.

Manipulating Elements in a List using the assignment operator

Items in a list can be changed meaning lists are mutable.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_yours=[4,8,5,2,1]

list_yours[1]=6   

print(list_yours)    #The output will be [4,6,5,2,1]

Changing a range of items in a list

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_yours[0:3]=[12,11,10] #Will change first item to fourth item in the list

print(list_yours)   #Output will be: [12,11,10,1 ]

Appending/Extending items in the List

The append() method allows extending the items in the list. The extend() can also be used.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_yours=[4, 6, 5]

list_yours.append(3)

print(list_yours)   #The output will be [4,6,5, 3]

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_yours=[4,6,5]

list_yours.extend([13,7,9])

print(list_yours)   #The output will be [4,6,5,13,7,9]

The plus operator(+) can also be used to combine two lists. The * operator can be used to perform iteration of a list a given severally.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_yours=[4,6,5]

print(list_yours+[13,7,9])  # Output:[4, 6, 5,13,7,9 ]

print([‘happy’]*4)   #Output:[“happy”,”happy”, “happy”,”happy”]

Removing or Deleting Items from a List

The keyword del is used to delete elements or the entire list in Python.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_mine=[‘t’,’r’,’o’,’g’,’r’,’a’,’m’]

del list_mine[1]

print(list_mine)  #t, o, g, r, a, m

Deleting Multiple Elements

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

del list_mine[0:3]

Example

print(list_mine)  #a, m

Delete Entire List

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

delete list_mine

print(list_mine)  #will generate an error of lost not found  

The remove() method or pop() function may be used to remove specified item. The pop() method will remove and return the last item if index is not given and helps implement lists as stacks. The clear() method is used to empty a list.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_mine=[‘t’,’k’,’b’,’d’,’w’,’q’,’v’]

list_mine.remove(‘t’)

print(list_mine)    #output will be [‘t’,’k’,’b’,’d’,’w’,’q’,’v’]

print(list_mine.pop(1))   #output will be ‘k’

print(list_mine.pop())   #output will be ‘v’

Assignment

Given list_yours=[‘K’,’N’,’O’,’C’,’K’,’E’,’D’]

a. Pop the third item in the list, save the program as list1.

b. Remove the fourth item using remove() method and save the program as list2

c. Delete the second item in the list and save the program as list3.

d. Pop the list without specifying an index and save the program as list4.

Using Empty List to Delete an entire or specific elements

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

list_mine=[‘t’,’k’,’b’,’d’,’w’,’q’,’v’]

list_mine=[1:2]=[]     

print(list_mine)   #Output will be [‘t’,’w’,’q’,’v’]

List Methods in Python

Assignment

Use list access methods to display the following items in reversed order list_yours=[4,9,2,1,6,7]

Use list access method to count the elements in a.

Use list access method to sort the items in a. in an ascending order/default.

Inbuilt Python Functions that can be used to manipulate Python Lists

Tuple in Python

A tuple is like a list but we cannot change elements in a tuple.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

tuple_mine = (21, 12, 31)

print(tuple_mine)

tuple_mine = (31, "Green", 4.7)

print(tuple_mine)

Accessing Python Tuple Elements

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

tuple_mine=[‘t’,’r’,’o’,’g’,’r’,’a’,’m’ ]

print(tuple_mine[1])   #output:’r’

print(tuple_mine[3])   #output:’g’

Negative Indexing

Just like lists, tuples can also be indexed negatively.

Like lists, -1 refers to the last element on the list and -2 refer to the second last element.  

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

tuple_mine=[‘t’,’r’,’o’,’g’,’r’,’a’,’m’]

print(tuple_mine [-2])  #the output will be ‘a’

Slicing

The slicing operator, the full colon is used to access a range of items in a tuple.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

tuple_mine=[‘t’,’r’,’o’,’g’,’r’,’a’,’m’]

print(tuple_mine [2:5])  #Output: ‘o’,’g’,’r’,’a’

print(tuple_mine[:-4])   #’g’,’r’,’a’,’m’

Note

Tuple elements are immutable meaning they cannot be changed.  However, we can combine elements in a tuple using +(concatenation operator). We can also repeat elements in a tuple using the * operator, just like lists .

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

print((7, 45, 13) + (17, 25, 76))

print(("Several",) * 4)

Note

Since we cannot change elements in tuple, we cannot delete the elements too. However removing the full tuple can be attained using the kwyword del.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

t_mine=[‘t’,’k’,’q’,’v’,’y’,’c’,’d’]

del t_mine

Available Tuple Methods in Python

They are only two methods available for working Python tuples.

count(y)

When called will give the item numbers that are equal to y.

index(y)

When called will give index first item index that is equal to y.

Example

Start IDLE.

Navigate to the File menu and click New Window .

Type the following:

t_mine=[‘t’,’k’,’q’,’v’,’y’,’c’,’d’]

print(t_mine.count('t'))

print(t_mine.index('l'))

Testing Membership in Tuple

The keyword in us used to check the specified element exists in a tuple.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

t_mine=[‘t’,’k’,’q’,’v’,’y’,’c’,’d’]

print('a' t_mine)  #Output: True

print('k' in t_mine)  #Output: False

Inbuilt Python Functions with Tuple 

String in Python

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

string_mine = 'Colorful'

print(string_mine)

string_mine = "Hello"

print(string_mine)

string_mine = '''Hello'''

print(string_mine )

string_mine = """I feel like I have

been born a programmer"""

print(string_mine)

Accessing items in a string

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

str = 'Colorful'

print('str = ', str)

print('str[1] = ', str[1])  #Output the second item

print('str[-2] = ', str[-2]) #Output the second last item

print('str[2:4] = ', str[2:4]) #Output the third through the fifth item

Deleting or Changing in Python

In Python, strings are immutable therefore cannot be changed once assigned. However, deleting the entire string is possible.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

del string_mine

String Operations

Several operations can be performed on a string making it a widely used data type in Python.

Concatenation using the + operator, repetition using the * operato r

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

string1=’Welcome’

string2=’Again’

print(‘string1+string2=’,string1+string2)

print(' string1 * 3 =', string1 * 3)

Exercise

Given string_a=”I am awake” and string_b=”coding in Python in a pajama”

String Iteration

The for control  statement is used to continually scan through an entire scan until the specified severally are reached before terminating the scan.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Membership Test in String

The keyword in is used to test if a sub string exists.

Example

‘t’ in “triumph’   #Will return True

Inbuilt Python Functions for working with Strings

They include enumerate() and len().The len() function returns the length of the string .

String Formatting in Python

Escape Sequences

Single and Double Quotes

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

print('They said, "We need a new team?"') # escape with single quotes

# escaping double quotes

print("They said, \" We  need a new team\"")

Escape Sequences in Python

The escape sequences enable us to format our output to enhance clarity to the human user. A program will still run successful without using escape sequences but the output will be highly confusing to the human user. Writing and displaying output in expected output is part of good programming practices. The following are commonly used escape sequences.

Examples

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

print("D:\\Lessons\\Programming")

print("Prints\n in two lines")

Summary

Integers, floating point, and complex numbers are supported in Python. There are integers, floating and complex classes that help convert different number data types. The presence or absence of a decimal point separates integers and floating points. For instance, 4 is integer while 4.0 is a floating point number. Programmers often need to convert decimal numbers into octal, hexadecimal and binary forms. We can represent binary, hexadecimal and octal systems in Python by simply placing a prefix to the particular number. Sometimes referred to as coercion, type conversion allows us to change one type of number into another.

Inbuilt functions such as int() allows us to convert data types directly. The same functions can be used to convert from strings. We create a list in Python by placing items called elements inside square brackets separated by commas. In programming and in Python specifically, the first time is always indexed zero. For a list of five items we will access them from index0 to index4. Failure to access the items in a list in this manner will create index error.

Chapter 5

Type Conversion and Type Casting

Type Conversion refers to the process of changing the value of one programming data type to another programming data type. Think of dividing two integers that lead to decimal numbers. In this case, it is necessary to convert force the conversion of an integer into a float number. Python has two types of conversion: implicit type conversion and explicit conversion.

i.    Implicit Conversion Type

In this case, Python automatically changes one data type to another data type, and the process does not require user involvement. Implicit type conversion is mainly used with the intent of avoiding data loss.

Example

Converting Integer to Float

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=451

number_flo=4.51

number_new=number_int+number_flo

print(“the type of data of number_int-“, type(number_int))

print(“the type of data of number_flo-“, type(number_flo))

print(“value of number_new-“number_new )

print(“type of data of number_new-“, type(number_new))

Explanation

The programming is adding two variables one of data type integer and the other float and storing the value in a new variable of data type float. Python automatically converts small data types into larger data types to avoid prevent data loss. This is known as implicit type conversion.

Note

Python cannot, however, convert numerical data types into string data type or string data type into numerical data type implicitly. Attempting such a conversion will generate an error.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=432         #lower data type

number_str=”241”        #higher data type

print(“The type of data of number_int-“, type(number_int))

print(“The type of data of number_str-“, type(number_str))

print(number_int+number_str)

Challenge: Can you guess why this is occurring? Python interpreter is unable to understand whether we want concatenation or addition precisely. When it assumes the concatenation, it fails to locate the other string. When it assumes the addition approach, it fails to locate the other number. The solution to the error above is to have an explicit type conversion.

ii.    Explicit Conversion

Here, programmers convert the data type of a named programming object to the needed data type. Explicit conversion is attained through the functions float(), int(), and str() among others .

The syntax for the specific or explicit conversion is:

(needed_datatype) (expression)

Example

Summing of a string and integer using by using explicit conversion

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=431

number_str=”231”

print(“Type of data of number_int-“, type(number_int))

print(“Type of data number_str prior to Type Casting-“, type(number_str))

number_str=int(number_str)

number_sum=number_int+number_str

print(“Addition of number_int and number_str-“, number_sum)

print(“Type of data of the sum-“, type(number_sum))

Note: Running this program will display the data types and sum and display an integer and string.

Explanation

In the above program, we added number_str and number_int variable. We then converted number_str from string(higher data type) to integer(lower data type)type using int() function to perform the summation. Python manages to add the two variables after converting number_str to an integer value. The number_sum value and data type are an integer data type.  

Summary

The conversion of the object from one data type to another data type is known as type conversion. The python interpreter automatically performs implicit type conversion. Implicit type conversion intends to enable Python to avoid data loss. Typecasting or explicit conversion happens when the data types of object are converted using the predefined function by the programmer. Unlike implicit conversion, typecasting can lead to data loss as we enforce the object to a particular data type.

The previous explicit conversion/typecasting can be written as:

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=431                #int data type

number_str=”231”                #string data type

number_str=int(number_str)            #int function converting string into int data type

number_sum=number_int+number_str    #variable number_sum

print(“Addition of number_int and number_str-“, number_sum)

Note

Explicit conversion/Type casting requires some practice to master, but it is easy.

The trick is here:

the variable name to convert=predefined function for the desired data type (variable name to convert)

Assignment

Use the knowledge of type casting/explicit data conversion to write a program to compute the sum of :

a.    score_int=76

score_str=”61.”

b.    count_str=231

count_str=”24”

Use the knowledge of type casting/explicit data conversion to write a program find the product of:

c.    number_int=12

number_str=”5.”

d.    odds_int=6

odds_str=”2”

e.    minute_int=45

minute_str=”7”

Input, Output, and Import in Python

In Python input and output (I/O) tasks are performed by inbuilt functions. The print() performs output/display, while input() performs input tasks.  The print() is used to output data to standard output devices such as a screen. However, it is also possible to copy data to a file. You are now familiar with the print function written as a print(). It is an inbuilt function because we do not have to write it and specify what and how it works. They are two main types of functions, inbuilt/built-in and user-defined functions that we will handle later. When we want the print function to reference or pick the value of a variable, we do not use double quotes.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number=6    #variable definition and assignmen t

print(number)    #displaying value stored in variable number

Note: Now assume we want to offer some explanation to the user running this program as he or she will only 6 and does not understand why 6 appears on the screen.

number=6

print(“This is a number stored in the variable number, it is:” number)

Note: We can display string and other data types in the print function. A comma is generally used to demarcate the end of one data type and the beginning of another.

Assignment

a)      Given score=5, write a Python program that displays “The score is 5”. The program should reference/extract the value of score in its print function.

b)    Given age=26, write a Python to display “Richard’s age is 26”. The program should reference/extract the value of score in its print function.

c)     Given marks=87, write a Python program that displays “The average marks in the class is 87”. The program should reference/extract the value of score in its print function.

Note that the new line in Python is gotten by “\n” without the double quotes and outside the string or line code.

Formatting Output

It may become necessary to play around with the layout of the output to make it appealing, formatting. The str.format() method is used to format output and is visible/accessible to any string object.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following :

lucy=3; brian= 7

print(‘The age of lucy is {} and brian is {}’.format(lucy,brian))

Note

The expected output is “The age of lucy is 3, and Brian is 7”.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

print(‘Brian loves {1} and {0}’.format(‘soccer’, ‘movies’))

#The expected output will be: He likes soccer and moves

print(‘he likes {1} and {0}’.format(‘soccer’, ‘movies’))

#Output: He likes movies and soccer

Note

The use of tuple index/ numbers to specify the order of displaying frees up the programmer as one does not have to retype the entire string when switching the order of the variables.

Assignment

Given print(‘She studies {0} and {1}’.format(‘Health’, ‘ICT’))

a.    Rewrite the Python program to display “She studies ICT and Health.”

b.    Rewrite the Python program to display “She studies Health and Health.”

c.    Rewrite the Python program to display “She studies ICT and ICT.”

In real life the concept above (tuple index/specifying order of display) may be useful where you don’t have to rewrite entire lines of codes. For instance, think of a website that asks users to register for an account but begins with asking surname before the first name. Now assume that the ICT team has recommended that the users should be asked their first name first before the surname. Write a simple Python simulation program to demonstrate how the tuple index concept can increase efficiency, readability, and maintainability of code.

Input in Python

So far our Python programs have been static meaning that we could not key in as everything was given to the variable before running the program. In real life, applications allow users to type in values to a program and wait for it to act on the values given. The input function (input()) is used to accept input of values from the user.

Syntax/way of using it in Python

variable name=input(‘option to include a message to the user on what is happening/can leave it out’).

Example

A program that accepts numerals from users

number=input(‘Type your number here:’)    #Will display: Type a number here:

Important: Python interpreter at this stage will treat any numbers entered as a string. For Python interpreter to treat the keyed-in number as the number, we must convert the number using type conversion functions for numbers which are int() and float().

To convert the number into an integer, after input from the user does the following:

int(‘number’)

To convert the number into a float, after input from the user does the following:

float(‘number’ )

Assignment

a)    . Create a program in Python to accept numerical data from users for their age, to capture the age of a user

b)    Use explicit type conversion to convert the string entered into a floating value in a.

c)     Create a program in Python to accept salary figure input from users.

d)    Use explicit type conversion to convert the string into a floating value in c.

e)    Write a program to accept the count of students/number of students’ in a class from users.

f)      Use explicit type conversion to convert the string entered into an integer data type in e.

Import in Python

The programs we have run so far are small, but in reality, a program can be hundreds to ten thousand lines of code. In this case, a large program is broken into smaller units called modules. These modules are related but on different files normally ending with the extension .py. Python allows importing of a module to another module using the keyword import. Analogy: You probably have some of your certificates scanned and stored in your Google drive, have your notebook in your desk, have a passport photo in your phone external storage, and a laptop in your room. When writing an application for an internship, you will have to find a way of accessing all these resources, but in normal circumstances, you will only work with a few even though all of them are connected. The same is true for programs.

Example

Assume we need to access the math pi that is a different module. The following program will illustrate:

Start IDLE.

Navigate to the File menu and click New Window .

Type the following:

import.math        #referencing to the contents of math module

print(math.pi)      #Now utilizing the features found in that referenced math

Namespace and Scope in Python

The identifier is simply a named object. Python handles every item as an object.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number=3

print(id(3)=‘, id(3))

print(‘id(number)=’, id(number))

Note: Both are referring to the same object.

Namespace in Python

When we start the Python interpreter, a namespace containing all inbuilt names is created as long the workspace remains application is active. Inbuilt functions such as print() and id() exist throughout the program.

Built-in Namespace: These are functions, methods, and associated data that immediately accessible as soon the Python interpreter loads and as such are accessible to each instance and area of the workspace.

Global Namespace: This involves the contents of a module that are accessible throughout the module. Modules can have several functions and methods .

Local Namespace: Mostly for user-defined functions, a local namespace is restricted to the particular function and outside the function access is not implicitly possible.

Variable Scope

Even though there might be several unique namespaces specified, it may not be possible to access all of the namespaces given because of scope. The concept of scope refers to a segment of the program from where we access the namespace directly without any prefix. The following are the scope types:

i.    Scope containing local names, current function.

ii.    Scope containing global names, the scope of the module.

iii.    Scope containing built-in names of the outermost scope.

Summary

Type Conversion refers to the process of changing the value of one data type to another data type. Think of dividing two integers that lead to decimal numbers. In this case, it is necessary to convert force the conversion of an integer into a float number. Python has two types of conversion: implicit type conversion and explicit conversion. In Python input and output (I/O) tasks are performed by inbuilt functions. The print() performs output/display, while input() performs input tasks.  Namespace in Python refers to a collection of names. While different namespaces can co-exist at an instance, they are completely isolated. When we start the Python interpreter, a namespace containing all inbuilt names is created as long the workspace remains application is active.

Functions in Python help split large code into smaller units. Functions make a program more organized and easy to manage.

In Python functions will assume the syntax form below:

def name_of_function (arguments):

“””docstring”” ”

statements(s)

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

def welcome(salute):

"""The Python function welcomes you to

the individual passed in as

parameter"""

print("Welcome " + salute + ". Lovely Day!")

Calling a Method in Python

We can call a function once we have defined it from another function or program.

Calling a function simply involves typing the function name with suitable parameters.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

welcome(‘Brenda’)

The output will be “Welcome Brenda. Lovely Day!’

Assignment

Write a function that when called outputs“Hello (student name), kindly submit your work by Sunday” .

Docstring

It is placed after the function header as the first statement and explains in summary what the function does. Docstring should always be placed between triple quotes to accommodate multiple line strings.

Calling/Invoking the docstring we typed earlier

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

print(welcome._doc_)

The output will be “This function welcomes you to

the individual passed in as

parameter”.

The syntax for calling/invoking the docstring is:

print(function_name. _doc_)

Python function return statement

Return syntax

return [list of expressions]

Explanation

The return statement can return a value or a None object.

Example

Print(welcome(“Richard”))    #Passing arguments and calling the function

Welcome Richard. Lovely Day!

None                #the returned valu e

Example of Returning a Value other None

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Variable Scope and Lifetime in Python Functions

Variables and parameters defined within a Python function have local scope implying they are not visible from outside. In Python the variable lifetime is valid as long the function executes and is the period throughout that a variable exists in memory. Returning the function destroys the function variables.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

def function_my()

marks=15

print(“The value inside the function is:”, marks)

marks=37

function_my()

print”The value outside the function is:”,marks)

Function Types

They are broadly grouped into user-defined and built-in functions. The built-in functions are part of the Python interpreter while the user-defined functions are specified by the user .

Assignment

Give three examples of built-in functions in Pythons

Function Argument

Calling a function requires passing the correct number of parameters otherwise the interpreter will generate an error.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

def salute(name,mesage):

"""This function welcomes to

the student with the provided message"""

print("Welcome",salute + ', ' + message)

welcome("Brenda","Lovely Day!")

Note

The function welcome() has two parameters. We will not get any error as has been fed with two arguments. Let us try calling the function with one argument and see what happens:

welcome(“Brenda”)    #only one argument passed

Running this program will generate an error saying “TypeError: welcome() missing 1 required positional argument. The same will happen when we pass no arguments to the function.

Example 2

Start IDLE.

Navigate to the File menu and click New Window.

Type the following :

welcome()

The interpreter will generate an error “TypeError: welcome() missing 2 required positional arguments”.

Type Conversion refers to the process of changing the value of one programming data type to another programming data type. Think of dividing two integers that lead to decimal numbers. In this case, it is necessary to convert force the conversion of an integer into a float number. Python has two types of conversion: implicit type conversion and explicit conversion.

Implicit Conversion Type

In this case, Python automatically changes one data type to another data type, and the process does not require user involvement. Implicit type conversion is mainly used with the intent of avoiding data loss.

Example

Converting Integer to Float

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=451

number_flo=4.51

number_new=number_int+number_flo

print(“the type of data of number_int-“, type(number_int))

print(“the type of data of number_flo-“, type(number_flo))

print(“value of number_new-“number_new)

print(“type of data of number_new-“, type(number_new) )

Explanation

The programming is adding two variables one of data type integer and the other float and storing the value in a new variable of data type float. Python automatically converts small data types into larger data types to avoid prevent data loss. This is known as implicit type conversion.

Note

Python cannot, however, convert numerical data types into string data type or string data type into numerical data type implicitly. Attempting such a conversion will generate an error.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=432         #lower data type

number_str=”241”        #higher data type

print(“The type of data of number_int-“, type(number_int))

print(“The type of data of number_str-“, type(number_str))

print(number_int+number_str)

Challenge: Can you guess why this is occurring? Python interpreter is unable to understand whether we want concatenation or addition precisely. When it assumes the concatenation, it fails to locate the other string. When it assumes the addition approach, it fails to locate the other number. The solution to the error above is to have an explicit type conversion.

Explicit Conversion

Here, programmers convert the data type of a named programming object to the needed data type. Explicit conversion is attained through the functions float(), int(), and str() among others.

The syntax for the specific or explicit conversion is :

(needed_datatype) (expression)

Example

Summing of a string and integer using by using explicit conversion

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=431

number_str=”231”

print(“Type of data of number_int-“, type(number_int))

print(“Type of data number_str prior to Type Casting-“, type(number_str))

number_str=int(number_str)

number_sum=number_int+number_str

print(“Addition of number_int and number_str-“, number_sum)

print(“Type of data of the sum-“, type(number_sum))

Note: Running this program will display the data types and sum and display an integer and string.

Explanation

In the above program, we added number_str and number_int variable. We then converted number_str from string(higher data type) to integer(lower data type)type using int() function to perform the summation. Python manages to add the two variables after converting number_str to an integer value. The number_sum value and data type are an integer data type.

Summary

The conversion of the object from one data type to another data type is known as type conversion. The python interpreter automatically performs implicit type conversion. Implicit type conversion intends to enable Python to avoid data loss. Typecasting or explicit conversion happens when the data types of object are converted using the predefined function by the programmer. Unlike implicit conversion, typecasting can lead to data loss as we enforce the object to a particular data type.

The previous explicit conversion/typecasting can be written as:

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=431                #int data type

number_str=”231”                #string data type

number_str=int(number_str)            #int function converting string into int data type

number_sum=number_int+number_str    #variable number_sum

print(“Addition of number_int and number_str-“, number_sum)

Note

Explicit conversion/Type casting requires some practice to master, but it is easy.

The trick is here:

the variable name to convert=predefined function for the desired data type (variable name to convert)

Assignment

Use the knowledge of type casting/explicit data conversion to write a program to compute the sum of:

a.    score_int=76

score_str=”61.”

b.    count_str=23 1

count_str=”24”

Use the knowledge of type casting/explicit data conversion to write a program find the product of:

c.    number_int=12

number_str=”5.”

d.    odds_int=6

odds_str=”2”

e.    minute_int=45

minute_str=”7”

Input, Output, and Import in Python

In Python input and output (I/O) tasks are performed by inbuilt functions. The print() performs output/display, while input() performs input tasks.  The print() is used to output data to standard output devices such as a screen. However, it is also possible to copy data to a file. You are now familiar with the print function written as a print(). It is an inbuilt function because we do not have to write it and specify what and how it works. They are two main types of functions, inbuilt/built-in and user-defined functions that we will handle later. When we want the print function to reference or pick the value of a variable, we do not use double quotes.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number=6    #variable definition and assignment

print(number)    #displaying value stored in variable number

Note: Now assume we want to offer some explanation to the user running this program as he or she will only 6 and does not understand why 6 appears on the screen .

number=6

print(“This is a number stored in the variable number, it is:” number)

Note: We can display string and other data types in the print function. A comma is generally used to demarcate the end of one data type and the beginning of another.

Assignment

a)    Given score=5, write a Python program that displays “The score is 5”. The program should reference/extract the value of score in its print function.

b)    Given age=26, write a Python to display “Richard’s age is 26”. The program should reference/extract the value of score in its print function.

c)     Given marks=87, write a Python program that displays “The average marks in the class is 87”. The program should reference/extract the value of score in its print function.

Note that the new line in Python is gotten by “\n” without the double quotes and outside the string or line code.

Formatting Output

It may become necessary to play around with the layout of the output to make it appealing, formatting. The str.format() method is used to format output and is visible/accessible to any string object.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

lucy=3; brian= 7

print(‘The age of lucy is {} and brian is {}’.format(lucy,brian) )

Note

The expected output is “The age of lucy is 3, and Brian is 7”.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

print(‘Brian loves {1} and {0}’.format(‘soccer’, ‘movies’))

#The expected output will be: He likes soccer and moves

print(‘he likes {1} and {0}’.format(‘soccer’, ‘movies’))

#Output: He likes movies and soccer

Note

The use of tuple index/ numbers to specify the order of displaying frees up the programmer as one does not have to retype the entire string when switching the order of the variables.

Assignment

Given print(‘She studies {0} and {1}’.format(‘Health’, ‘ICT’))

a.    Rewrite the Python program to display “She studies ICT and Health.”

b.    Rewrite the Python program to display “She studies Health and Health.”

c.    Rewrite the Python program to display “She studies ICT and ICT.”

In real life the concept above (tuple index/specifying order of display) may be useful where you don’t have to rewrite entire lines of codes. For instance, think of a website that asks users to register for an account but begins with asking surname before the first name. Now assume that the ICT team has recommended that the users should be asked their first name first before the surname. Write a simple Python simulation program to demonstrate how the tuple index concept can increase efficiency, readability, and maintainability of code.

Input in Python

So far our Python programs have been static meaning that we could not key in as everything was given to the variable before running the program. In real life, applications allow users to type in values to a program and wait for it to act on the values given. The input function (input()) is used to accept input of values from the user.

Syntax/way of using it in Python

variable name=input(‘option to include a message to the user on what is happening/can leave it out’).

Example

A program that accepts numerals from users

number=input(‘Type your number here:’)    #Will display: Type a number here:

Important: Python interpreter at this stage will treat any numbers entered as a string. For Python interpreter to treat the keyed-in number as the number, we must convert the number using type conversion functions for numbers which are int() and float().

To convert the number into an integer, after input from the user does the following:

int(‘number’)

To convert the number into a float, after input from the user does the following:

float(‘number’)

Assignment

a)    Create a program in Python to accept numerical data from users for their age, to capture the age of a use r

b)    Use explicit type conversion to convert the string entered into a floating value in a.

c)     Create a program in Python to accept salary figure input from users.

d)    Use explicit type conversion to convert the string into a floating value in c.

e)    Write a program to accept the count of students/number of students’ in a class from users.

f)      Use explicit type conversion to convert the string entered into an integer data type in e.

Import in Python

The programs we have run so far are small, but in reality, a program can be hundreds to ten thousand lines of code. In this case, a large program is broken into smaller units called modules. These modules are related but on different files normally ending with the extension .py. Python allows importing of a module to another module using the keyword import. Analogy: You probably have some of your certificates scanned and stored in your Google drive, have your notebook in your desk, have a passport photo in your phone external storage, and a laptop in your room. When writing an application for an internship, you will have to find a way of accessing all these resources, but in normal circumstances, you will only work with a few even though all of them are connected. The same is true for programs.

Example

Assume we need to access the math pi that is a different module. The following program will illustrate:

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

import.math        #referencing to the contents of math modul e

print(math.pi)      #Now utilizing the features found in that referenced math

Namespace and Scope in Python

The identifier is simply a named object. Python handles every item as an object.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number=3

print(id(3)=‘, id(3))

print(‘id(number)=’, id(number))

Note: Both are referring to the same object.

Namespace in Python

When we start the Python interpreter, a namespace containing all inbuilt names is created as long the workspace remains application is active. Inbuilt functions such as print() and id() exist throughout the program.

Built-in Namespace: These are functions, methods, and associated data that immediately accessible as soon the Python interpreter loads and as such are accessible to each instance and area of the workspace.

Global Namespace: This involves the contents of a module that are accessible throughout the module. Modules can have several functions and methods.

Local Namespace: Mostly for user-defined functions, a local namespace is restricted to the particular function and outside the function access is not implicitly possible .

Variable Scope

Even though there might be several unique namespaces specified, it may not be possible to access all of the namespaces given because of scope. The concept of scope refers to a segment of the program from where we access the namespace directly without any prefix. The following are the scope types:

Scope containing local names, current function.

Scope containing global names, the scope of the module.

Scope containing built-in names of the outermost scope.

Summary

Type Conversion refers to the process of changing the value of one data type to another data type. Think of dividing two integers that lead to decimal numbers. In this case, it is necessary to convert force the conversion of an integer into a float number. Python has two types of conversion: implicit type conversion and explicit conversion. In Python input and output (I/O) tasks are performed by inbuilt functions. The print() performs output/display, while input() performs input tasks.  Namespace in Python refers to a collection of names. While different namespaces can co-exist at an instance, they are completely isolated. When we start the Python interpreter, a namespace containing all inbuilt names is created as long the workspace remains application is active.

Chapter 6

Classes and Objects in Python

Python supports different programming approaches as it is a multi-paradigm. An object in Python has an attribute and behavior. It is essential to understand objects and classes when studying machine learning using Python object-oriented programming language.

Example

Car as an object:

Attributes: color, mileage, model, age

Behavior: reverse, speed, turn, roll, stop, start.

Class

It is a template for creating an object.

Example

class Car:

Note

By convention, we write the class name with the first letter as uppercase. A class name is in singular form by convention.

Syntax

class Name_of_Class:

From a class, we can construct objects by simply making an instance of the class. The class_name() operator creates an object by assigning the object to the empty method.    

Class or Object Instantiation

From our class Car, we can have several objects such as a first car, second care or SUVs.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

my_car=Car()

pass

Assignment

a.    Create a class and an object for students.

b.    Create a class and an object for the hospital.

c.    Create a class and an object for a bank.

d.    Create a class and an object for a police department.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

class Car:

category=”Personal Automobile”

def __init__(self, model, insurance):

self.model = model

self.insurance =insurance

subaru=Car(“Subaru”,”Insured”)

toyota=Car(“Toyota”,”Uninsured” )

print(“Subaru is a {}”.format(subaru._class_.car))

print(“Toyota is a {}”.format(toyota._class_.car))

print(“{} is {}”.format(subaru.model, subaru.insurance))

print(“{} is {}”.format(toyota.model, toyota.insurance))

Functions

Functions defined within a body of the class are known as methods and are basic functions. Methods define the behaviors of an object.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

def __init__(self, model, insurance):

self.model = model

self.insurance =insurance

def ignite(self, ignite):

return "{} ignites {}".format(self.model, ignition)

def stop(self):

return "{} is now stopping".format(self.model)

subaru=Car(“Subaru”,”Insured”)

print(subaru.ignite("'Fast'"))

print(subaru.stop())

Note

The methods ignite() and stop() are referred to as instance methods because they are an instance of the object created .

Assignment

a.    Create a class Dog and instantiate it.

b.    Create a Python program to show names of two dogs and their two attributes from a.

Inheritance in Python

A way of creating a new class by using details of existing class devoid of modifying it is called inheritance. The derived class or child class is the newly formed class while the existing class is called parent or base class.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Explanation

We created two Python classes in the program above. The classes were Dog as the base class and Pitbull as the derived class. The derived class inherits the functions of the base class. The method _init_() and the function super() are used to pull the content of _init_() method from the base class into the derived class.

Data Encapsulation/Data Hiding

Encapsulation in Python Object Oriented Programming approach is meant to help prevent data from direct modification. Private attributes in Python are denoted using a single or double underscore as a prefix.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

“__” or “_” .

class Tv:

def __init__(self):

self.__Finalprice = 800

def offer(self):

print("Offering Price: {}".format(self.__finalprice))

def set_final_price(self, offer):

self.__finalprice = offer

t = Tv()

t.offer()

t.__finalprice = 950

t.offer()

# using setter function

t.setFinalPrice(990)

t.sell()

Explanation

The program defined a class Tv and used _init_(0 methods to hold the final offering price of the TV. Along the way, we attempted to change the price but could not manage. The reason for the inability to change is because Python treated the _finalprice as private attributes. The only way to modify this value was through using a setter function, setMaxPrice() that takes price as a parameter.

Polymorphism

In Python, polymorphism refers to the ability to use a shared interface for several data types.

Start IDLE.

Navigate to the File menu and click New Window .

Type the following:

Explanation

The program above has defined two classes Tilapia and Shark all of which share the method jump() even though they have different functions. By creating common interface jumping_test() we allowed polymorphism in the program above. We then passed objects bonny and biggy in the jumping_test() function.

Assignment

a.    In a doctor consultation room suggest the class and objects in a programming context.

b.    In a football team, suggest programming class and objects.

c.    In a grocery store, suggest programming class and objects.

Definition of a Class

The keyword def is used to define a class in Python. The first string in a Python class is used to describe the class even though it is not always needed.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

class Dog

‘’’Briefly taking about class Dog using this docstring’’’

Pass

Example 2

Start IDLE.

Navigate to the File menu and click New Window .

Type the following:

Class Bright:

“My other class”

b=10

def salute(self):

print(‘Welcome’)

print(Bright.b)

print(Bright.salute)

print(Bright.__doc__)

Creating an Object in Python

Example from the previous class

Open the previous program file with class Bright

student1=Bright()

Explanation

The last program will create object student1, a new instance. The attributes of objects can be accessed via the specific object name prefix. The attributes can be a method or data including the matching class functions.  In other terms, Bright.salute is a function object and student1.salute will be a method object.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

class Bright:

"Another class again! "

c = 20

def salute(self):

print('Hello')

student2 = Bright()

print(Bright.salute)

print(student2.salute)

student2.salute()

Explanation

You invoked the student2.salute() despite the parameter ‘self’ and it still worked without placing arguments. The reason for this phenomenon is because each time an object calls its method, the object itself is passed as the first argument. The implication is that student2.salute() translates into student2.salute(student2). It is the reason for the ‘self; name.

Constructors

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

class NumberComplex

class ComplexNumber:

def __init__(self,realnum = 0,i = 0):

self.real = realnum

self.imaginarynum = i

def getData(self):

print("{0}+{1}j".format(self.realnumber,self.imaginarynum))

complex1 = NumberComplex(2,3 )

complex1.getData()

complex2 = NumberComplex(5)

complex2.attribute = 10

print((complex2.realnumber, complex2.imaginarynumber, complex2.attribute))

complex1.attribute

Deleting Objects and Attributes

The del statement is used to delete attributes of an object at any instance.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

complex1 = NumberComplex(2,3)

del complex1.imaginarynumber

complex1.getData()

del NumberComplex.getData

complex1.getData()

Deleting an Object

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

complex1=NumberComplex(1,3)

del complex 1

Explanation

When complex1=NumberComplex(1,3) is done, a new instance of the object  gets generated in memory and the name complex1 ties with it. The object does not immediately get destroyed as itt temporarily stays in memory before the garbage collector purges it from memory. The purging of the object helps free resources bound to the object and enhances system efficiency. Garbage destruction Python refers to automatic destruction of unreferenced objects.

Inheritance in Python

In Python inheritance allows us to specify a class that takes all the functionality from the base class and adds more. It is a powerful feature of OOP.

Syntax

class ParentClass:

Body of parent class

class ChildClass(ParentClass):

Body of derived class

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

class Rect_mine(Rect_mine):

def __init__(self):

Shape.__init__(self,4)

def getArea(self):

s1, s2, s3,s4 = self.count_sides

perimeter = (s1+s2+s3+s4 )

area = (s1*s2)

print('The rectangle area is:' %area)

Example 2

r = rect_mine()

r.inputSides()

Type b1 : 4

Type l1 : 8

Type b2 : 4

Type l1:    8

r.dispSides()

Type b1 is 4.0

Type l1 is 8.0

Type b2 is 4.0

Type l1 is 8.0

r.getArea()

Function Overriding in Python

When a method is defined in both the base class and the derived class, the method in the child class/derived class will override the parent/base class. In the above example, _init_() method in Rectangle class will override the _init_() in Shape class.

Inheritance in Multiple Form

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following :

MultiInherit is derived from class Parent1 and Parent2.

Multilevel Inheritance

Inheriting from a derived class is called multilevel inheritance.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

class Parent:

pass

class Multilevel1(Parent):

pass

class Multilevel2(Multilevel1):

pass

Explanation

Multilevel1 derives from Parent, and Multilevel2 derives from Multilevel1.

Method Resolution Order

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

print(issubclass(list,object))

print(isinstance(6.7,object))

print(isinstance("Welcome",object) )

Explanation

The specific attribute in a class will be scanned first. The search will continue into parent classes. This search does not repeat searching the same class twice. The approach or order of searching is sometimes called linearization of multi derived class in Python. The Method Resolution Order refers to the rules needed to determine this order.

Operator Overloading in Python

Inbuilt classes can use operators and the same operators will behave differently with different types. An example is the + that depending on context will perform concatenation of two strings, arithmetic addition on numbers, or merge lists. Operating overloading is an OOP feature that allows assigning varying meaning to an operator subject to context.  

Making A Class Compatible with Inbuilt Special Functions

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

class Planar:

def __init__(self, x_axis= 0, y_axis = 0):

self.x_axis = x_axis

self.y_axis = y_axis   

def __str__(self):

return "({0},{1})".format(self.x_axis,self.y_axis)

Explanation

planar1=Planar(3,5)

print(planar1)            #The output will be (3,5 )

Additional inbuilt methods

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

class Planar:

def __init__(self, x_axis= 0, y_axis = 0):

self.x_axis = x_axis

self.y_axis = y_axis

str(planar1)

format(planar1)

Explanation

It then follows that each time we invoke format(planar1) or str(planar1), Python is in effect executing planar1._str_() thus the name, special functions.

Operator + Overloading

The _add_() function addition in a class will overload the +.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

class Planar:

def __init__(self, x_axis= 0, y_axis = 0):

self.x_axis = x_axis

self.y_axis = y_axis    

def __str__(self):

return "({0},{1})".format(self.x_axis,self.y_axis)

def __add__(self,z):

x_axis = self.x_axis + z.x_axis

y_axis = self.y_axis + z.y_axis

return Planar(x_axis,y_axis)

Assignment

a.    Print planar1 + planar2 from the example above.

Explanation

When you perform planar1+planar2 in Python, it will call planar._add_(planar2) and in turn Planar._add_(planar1, planar2).

Revisit Logical and Comparison Operators

Assignment

a.    Given x=8, y=9, write a Python program that uses logical equals to test if x is equal to y.

b.    Write a program that evaluates x!=y in Python programming language.

c.    Write and run the following program

m = True

n = False

print('m and n is',m and n)

print('m or n is',m or n)

print('not m is',not n)

d.    From the program in c., which program statement(s) evaluates to True, or False .

e.    Write and run the following program in Python

m1 = 15

n1 = 15

m2 = 'Welcome'

n2 = 'Welcome'

m3 = [11,12,13]

n3 = [11,12,13]

print(m1 is not n1)

print(m2 is n2)

print(m3 is n3)   

f.    Which program statement(s) generate True or False states in e.

g.    Write and run the following program

m = 'Welcome'

n = {11:'b',12:'c'}

print('W' in m)

print('Welcome' not in m)

print(10 in n)

print('b' in n)

h.    Which program statement(s) in g. return True or False states.

The special functions needed for overloading other operators are listed below.

Overloading Comparison Operators

In Python, comparison operators can be overloaded.    

Example

Assignment

a.    Perform the following to the example above Planar(1,1)

b.    Again perform Planar(1,1) in the above example.

c.    Finally, perform Planar(1,1) from the above example.

Functions for Implementing Overloading of Comparison Operators

Summary

Python supports different programming approaches as it is a multi-paradigm. An object in Python has an attribute and behavior. From a class, we can construct objects by simply making an instance of the class. The class_name() operator creates an object by assigning the object to the empty method. The keyword def is used to define a class in Python. The first string in a Python class is used to describe the class even though it is not always needed. When a method is defined in both the base class and the derived class, the method in the child class/derived class will override the parent/base class. In the above example, _init_() method in Rectangle class will override the _init_() in Shape class.

Inbuilt classes can use operators and the same operators will behave differently with different types. An example is the + that depending on context will perform concatenation of two strings, arithmetic addition on numbers, or merge lists. Operating overloading is an OOP feature that allows assigning varying meaning to an operator subject to context.From a class, we can construct objects by simply making an instance of the class. The class_name() operator creates an object by assigning the object to the empty method.

The _init_() function is a special function and gets called whenever a new object of the corresponding class is instantiated. Functions defined within a body of the class are known as methods and are basic functions. Methods define the behaviors of an object. In Python, polymorphism refers to the ability to use a shared interface for several data types. An illustration is a program that has defined two classes Tilapia and Shark all of which share the method jump() even though they have different functions. By creating common interface jumping_test() we allowed polymorphism in the program above. We then passed objects bonny and biggy in the jumping_test() function. 

Chapter 7

Loops in Python

Before tackling flow control, it is important we explore logical operators. Comparison operators are special operators in Python that evaluate to either True or False state of the condition.

Program flow control refers to a way in which a programmer explicitly species the order of execution of program code lines. Normally, flow control involves placing some condition (s) on the program code lines. In this chapter, we will explore and test various flow controls in Python.

if…else Statement

The if..else statement in Python is a decision making when executing the program. The if…else statement will ONLY execute code if the specified condition exists.

The syntax of if…else in Python

if test expression:

Statement(s)

Explanation

The python program will only execute the statements(s) if the test expression is true. The program first evaluates the test expression before executing the statement(s). The program will not execute the statement(s) if the test expression is False. By convention, the body of it is marked by indentation while the first is not indented line signals the end.

Assignment

Think of scenarios, real-life, where the if…else condition is required .

•    If you have not enrolled for a course, then you cannot sit for the exam else sit for the exam.

•    If you have paid for house rent then you will be issued with acknowledgment receipt else request for more time.

•    If you are a licensed driver then you can drive to school else you hire a taxi.

•    If you are tired then you can watch movies else can complete the essay.

•    If you are an ethical person then you will acknowledge your mistake else you will overlook the damage caused.

•    If you are committed to programming then you will practice daily else you will lose interest.

•    If you have signed for email alerts you will be updated frequently else you will have to check the website daily.

•    If you plead guilty to all accounts you are likely to be convicted else the merit of your case will depend on cross-examination of witnesses and evidence presented.

Note

When we use the if statement alone without the else part, it will only print/display if the condition is true, it will not cater for the alternative, the case where the first condition is not present.

Example 1

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number=5

if number>0            #The comparison operator

print(number, “The number is a positive number” )

Explanation

The program contains the if the condition that tests if the given number satisfies the if condition, “is it greater than 0” since 5 is greater than zero, the condition is satisfied the interpreter is allowed to execute the next statement which is to extract and display the numerical value including the string message. The test condition in this program is “number>0. But think of when the condition is not met, what happens? Let us look at Example 2.

Example 2

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number=-9

if number>0:

print(number, “This is a positive number”)

Explanation

The program contains only the if statement which tests the expression by testing of -9 is greater than zero since it is not the interpreter will not execute the subsequent program code lines.  In real life, you will want to provide for an alternate in case the first condition is not met. This program will not display anything when executed because the if the condition has not been met. The test condition in this program is “number>0.

Assignment

Write programs in Python using if statement only to perform the following:

a.    Given number=7, write a program to test and display only even numbers.

b.    Given number1=8, number2=13, write a program to only display if the sum is less than 10 .

c.    Given count_int=57, write a program that tests if the count is more than 45 and displays, the count is above the recommended number.

d.    Given marks=34, write a program that tests if the marks are less than 50 and display the message, the score is below average.

e.    Given marks=78, write a program that tests if the marks are more than 50 and display the message, great performance.

f.    Given number=88, write a program that tests if the number is an odd number and displays the message, Yes it is an odd number.

g.    Given number=24, write a program that tests and displays if the number is even.

h.    Given number =21, write a program that tests if the number is odd and displays the string, Yes it is an odd number.

Note

The execution of statements after the if expression will only happen where the if the expression evaluates to True, otherwise the statements are ignored.

if…else Statement in Python

The if…else syntax

if test condition:

Statements

else:

Statements

The explanation the if statement, the if…else statement will execute the body of if in the case that the tests condition is True. Should the if…else tests expression evaluate to false, the body of the else will be executed. Program blocks are denoted by indentation. The if…else provides more maneuverability when placing conditions on the code .

Example

A program that checks whether a number is positive or negative

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_mine=-56

if(number<0):

print(number_mine, “The number is negative”)

else:

print(number_mine, “The number is a positive number”)

Assignment

Write a Python program that uses if..else statement to perform the following

a.    Given number=9, write a program that tests and displays whether the number is even or odd.

b.    Given marks=76, write a program that tests and displays whether the marks are above pass mark or not bearing in mind that pass mark is 50.

c.    Given number=78, write a program that tests and displays whether the number is even or odd.

d.    Given marks=27, write a program that tests and displays whether the marks are above pass mark or not bearing in mind that pass mark is 50.

Assignment

Write a program that accepts age input from the user, explicitly coverts the age into integer data types, then uses if…else flow control to tests whether the person is underage or not, the legal age is 21. Include comments and indentation to improve the readability of the program .

if…elif…else Statement in Python

Now think of scenarios where we need to evaluate multiple conditions, not just one, not just two but three and more. Think of where you have to choose team member, if not Richard, then Mercy, if not Richard and Mercy then Brian, if not Richard, Mercy, and Brian then Yvonne. Real-life scenarios may involve several choices/conditions that have to be captured when writing a program.

Remember that the elif simply refers to else if and is intended to allow for checking of multiple expressions. The if the block is evaluated first, then elif block(s), before the else block. In this case, the else block is more of a fallback option when all other conditions return false. Important to remember, despite several blocks available in if..elif..else only one block will be executed.

Example

Three conditions covered but the only one can execute at a given instance.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Explanation

There are three possibilities but at any given instance the only condition will exist and this qualifies the use of if family flow control statement. For three or more conditions to evaluate, the if…elif..else flow statement merits.

Nested if Statements in Python

Sometimes it happens that a condition exists but there are more sub-conditions that need to be covered and this leads to a concept known as nesting. The amount of statements to nests is not limited but you should exercise caution as you will realize nesting can lead to user errors when writing code. Nesting can also complicate maintaining of code. The only indentation can help determine the level of nesting .

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

my_charact=str(input(“Type a character here either ‘a’, ‘b’ or ‘c’:”))

if (my_charact=’a’):

if(my_charact=’a’):

print(“a”)

else if:

(my_charact=’b’)

print(“b”)

else:

print(“c”)

Assignment

Write a program that uses the if..else flow control statement to check non-leap year and display either scenario. Include comments and indentation to enhance the readability of the program.

for Loop in Python.

Indentation is used to separate the body of for loop in Python.

Note

Simple linear list takes the following syntax:

Variable_name=[values separated by a comma]

Example

Start IDLE.

Navigate to the File menu and click New Window .

Type the following:

numbers=[12, 3,18,10,7,2,3,6,1]    #Variable name storing the list

sum=0                    #Initialize sum before usage, very important

for cumulative in numbers:        #Iterate over the list

sum=sum+cumulative       

print(“The sum is” ,sum)

Assignment

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Write a Python program that uses the for loop to sum the following lists.

a.    marks=[3, 8,19, 6,18,29,15]

b.    ages=[12,17,14,18,11,10,16]

c.    mileage=[15,67,89,123,76,83]

d.    cups=[7,10,3,5,8,16,13]

range() function in Python

The range function (range()) in Python can help generate numbers. Remember in programming the first item is indexed 0.

Therefore, range(11) will generate numbers from 0 to 10.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

print(range(7))

The output will be 0,1,2,3,4,5, 6

Assignment

Without writing and running a Python program what will be the output for:

a.    range(16)

b.    range(8)

c.    range(4)

Using range() and len() and indexing

Solved Exercise

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

The output of this program will be:

I prefer omelet

I prefer fish

I prefer jazz

Assignment

Create a program in Python to iterate through the following list and include the message I listen to (each of the music genre). Use the for loop, len() and range(). Refer to the previous example on syntax.

folders=[‘Rumba’, ‘House’, ‘Rock’]

Using for loop with else

It is possible to include a for loop with else but as an option. The else block will be executed if the items contained in the sequence are exhausted.

Example

Start IDLE .

Navigate to the File menu and click New Window.

Type the following:

marks=[12, 15,17]

for i in marks:

print(i)

else:

print(“No items left”)

Assignment

Write a Python program that prints all prime numbers between 1 and 50.

while Loop in Python

In Python, the while loop is used to iterate over a block of program code as long as the test condition stays True. The while loop is used in contexts where the user does not know the loop cycles that are required. As indicated earlier, the while loop body is determined through indentation.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Caution : Failing to include the value of the counter will lead to an infinite loop.

Assignment

a.    Write a Python program that utilizes the while flow control statement to display the sum of all odd numbers from 1 to 10.

b.    Write a Python program that employs the while flow control statement to display the sum of all numbers from 11 to 21 .

c.    Write a Python program that incorporates while flow control statement to display the sum of all even numbers from 1 to 10.

Using While loop with else

If the condition is false and no break occurs, a while loop’s else part runs.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

track = 0

while track< 4:

print("Within the loop")

track = track + 1

else:

print("Now within the else segment")

Python’s break and continue

Let us use real-life analogy where we have to force a stop on iteration before it evaluates completely. Think of when cracking/breaking passwords using a simple dictionary attack that loops through all possible character combinations, you will want the program immediately it strikes the password searched without having to complete. Again, think of when recovering photos you accidentally deleted using a recovery software, you will want the recovery to stop iterating through files immediately it finds items within the specified range. The break and continue statement in Python works in a similar fashion.

Example

Start IDLE .

Navigate to the File menu and click New Window.

Type the following:

for tracker in "bring":

if tracker == "i":

break

print(tracker)

print("The End")

continue statement in Python

When the continue statement is used, the interpreter skips the rest of the code inside a loop for the current iteration only and the loop does not terminate. The loop continues with next iteration.

The syntax of Python continue

continue

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

for tracker in "bring":

if tracker == "i":

continue

print(tracker)

print("Finished")

The output of this program will be:

b

r

n

g

Finished

Analogy

Assume that you are running data recovery software and have specified skip word files (.doc, dox extension). The program will have to continue iterating even after skipping word files.

Assignment

a.    Write a Python program using for loop that will break after striking “v” in the string “Oliver”.

b.    Write a Python program that will continue after skipping “m” in the string “Lemon”.

pass Statement in Python

Like a comment, a pass statement does not impact the program as it leads to no operation.

The syntax of pass

pass

Think of a program code that you plan to use in future but is not currently needed. Instead of having to insert that code in future, the code can be written as pass statements.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

my_list={‘k’,’i’,’n’}

for tracker in my_list:

pass

Chapter 8

Lifetime of Variables and Functions

Keywords Arguments in Python

Python provides a way of calling functions using keyword arguments. When calling functions using keyword arguments, the order of arguments can be changed.  The values of a function are matched to the argument position-wise.

Note

In the previous example function welcome when invoked as welcome(“Brenda”, “Lovely Day!”). The value “Brenda” is assigned to the argument name and “Lovely Day!” to msg.

Calling the function using keywords

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

welcome(name=”Brenda”, msg=”Lovely Day!”)

Keywords not following the order

welcome(msg=”Lovely Day!”, name=”Brenda”)

Arbitrary Arguments

It may happen that we do not have knowledge of all arguments needed to be passed into a function. Analogy: Assume that you are writing a program to welcome all new students this semester. In this case, you do not how many will report .

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

def welcome(*names):

“””This welcome function salutes all students in the names tuple.”””

for name in names:

print(“Welcome”.name)

welcome("Lucy","Richard","Fridah","James")

The output of the program will be:

Welcome Lucy

Welcome Richard

Welcome Fridah

Welcome James

Recursion in Python

The definition of something in terms of itself is called recursion.  A recursive function calls other functions.

Example

A Python program to compute integer factorials

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Assignment

Create a program in Python to find the factorial of 7 .

Python Anonymous Function

Some functions may be specified devoid of a name and this are called anonymous function. The lambda keyword is used to denote an anonymous function. Anonymous functions are also referred to as lambda functions in Python.

Syntax

lambda arguments: expression.

Lambda functions must always have one expression but can have several arguments.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

double = lambda y: y * 2

# Output: 10

print(double(5))

Example 2

We can use inbuilt functions such as filter () and lambda to show only even numbers in a list/tuple.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

fresh_marks = list(filter(lambda n: (n%2 == 0) , first_marks))

# Output: [14, 16, 18, 32]

print(fresh_marks)

Lambda function and map() can be used to double individual list items .

Example 3

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

first_score = [3, 7, 14, 16, 18, 21, 13, 32]

fresh_score = list(map(lambda m: m * 2 , first_score))

# Output: [6, 14, 28, 32, 36, 42, 26, 64]

print(fresh_score)

Python’s Global, Local and Nonlocal

Python’s Global Variables

Variables declared outside of a function in Python are known as global variables. They are declared in global scope. A global variable can be accessed outside or inside of the function.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

y= "global"

def foo():

print("y inside the function :", y)

foo()

print("y outside the function:", y)

Explanation

In the illustration above, y is a global variable and is defined a foo() to print the global variable y. When we call the foo() it will print the value of y .

Local Variables

A local variable is declared within the body of the function or in the local scope.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

def foo():

x = "local"

foo()

print(x)

Explanation

Running this program will generate an error indicating ‘x’ is undefined. The error is occurring because we are trying to access local variable x in a global scope whereas foo() functions only in the local scope.

Creating a Local Variable in Python

Example

A local variable is created by declaring a variable within the function.

def foo():

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

x = "local"

print(x)

foo( )

Explanation

When we execute the code, the output is expected to be:

Local

Python’s Global and Local Variable

The following example shows how to use both local and global variables in the same Python program

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

y = "global"

def foo():

global y

x = "local"

y = y * 2

print(y)

print(x)

foo()

Explanation

The output of the program will be:

global global

loca l

Explanation

We declared y as a global variable and x as a local variable in the foo(). The * operator issued to modify the global variable y and finally, we printed both y and x.

Local and Global Variables with the same name

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

y=6

def foo():

y=11

print(“Local variable y-“, y)

foo()

print("Global variable y-", y)

Python’s Nonlocal Variables

A Python’s nonlocal variable is used in a nested function whose local scope is unspecified. It is neither global nor local scope.

Example

This example shows how to create a nonlocal variable.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

def outer():

y = "local variable"

def inner() :

nonlocal y

y = "nonlocal variable"

print("inner:", y)

inner()

print("outer scope:", y)

outer()

Global Keyword in Python

The global keyword I Python allows modification of the variable outside the current scope. The global keyword makes changes to the variable in a local context. There are rules when creating a global keyword:

A global keyword is local by default when we create a variable within a function.

It is global by default when we define a variable outside of a function and you do not need to use the global keyword.

The global keyword is used to read and write a global variable within a function.

The use of global keyword outside a function will have no effect.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number = 3        #A global variable

def add():

print(number)

add()

The output of this program will be 3 .

Modifying global variable from inside the function.

number=3                    #a global variable       

def add():

number= number + 4     # add 4 to 3

print(number)

add()

Explanation

When the program is executed it will generate an error indicating that the local variable number is referenced before assignment. The reason for encountering the error is because the global variable can only be accessed but it is not possible to modify it from inside the function. Using a global keyword would solve this.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Modifying global variable within a function using the global keyword.

number = 3             # a global variable

def add():

global number

number= number + 1 # increment by 1

print("Inside the function add():", number)

add()

print("In main area:", number )

Explanation

When the program is run, the output will be:

Inside the function add(): 4

In the main area: 4

We defined a number as a global keyword within the function add(). The variable was then incremented by 1, variable number. Then we called the add () function to print global variable c.

Creating Global Variables across Python Modules

We can create a single module config.py that will contain all global variables and share the information across several modules within the same program.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Create config.py

x=0

y=”empty”

Then create an update.py file to modify global variables

Import config

config.x=11

config.y=”Today”

Then create a main.py file to evaluate the changes in value

import config

import updat e

print(config.x)

print(config.y)

Explanation

Running the main.py file will generate:

11

Today

Chapter 9

Python Modules and Packages

Python Modules

Modules consist of definitions as well as program statements.

An illustration is a file name config.py which is considered as a module. The module name would be config. Modules are sued to help break large programs into smaller manageable and organized files as well as promoting reusability of code.

Example

Creating the First module

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Def add(x, y):

“””This is a program to add two

numbers and return the outcome"""

outcome=x+y

return outcome

Module Import

The keyword import is used to import.

Example

Import firs t

The dot operator can help us access a function as long as we know the name of the module.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

first.add(6,8)

Import statement in Python

The import statement can be used to access the definitions within a module via the dot operator.

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

import math

print("The PI value is", math.pi)

Import with renaming

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

import math as h

print(“The PI value is-“,h.pi )

Explanation

In this case, h is our renamed math module with a view helping save typing time in some instances. When we rename the new name becomes valid and recognized one and not the original one.

From…import statement Python.

It is possible to import particular names from a module rather than importing the entire module.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

from math import pi

print("The PI value is-", pi)

Importing all names

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

from math import*

print("The PI value is-", pi)

Explanation

In this context, we are importing all definitions from a particular module but it is encouraged norm as it can lead to unseen duplicates.

Module Search Path in Python

Example

Start IDLE .

Navigate to the File menu and click New Window.

Type the following:

import sys

sys.path

Python searches everywhere including the sys file.

Reloading a Module

Python will only import a module once increasing efficiency in execution.

print(“This program was executed”)

import mine

Reloading Code

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

import mine

import mine

import mine

mine.reload(mine)

Dir() built-in Python function

For discovering names contained in a module, we use the dir() inbuilt function.

Syntax

dir(module_name )

Python Package

Files in python hold modules and directories are stored in packages.  A single package in Python holds similar modules. Therefore, different modules should be placed in different Python packages.

Chapter 10

Dictionaries and Data Structures in Python

Dictionary

Believe it or not, a Python dictionary works in a very similar way to a regular dictionary. Python offers many different data structures to hold information, and the dictionary is one of the simplest and most useful. While many things in Python are iterables, not all of them are sequences and a Python dictionary falls in this category. In this article, we will talk about what a Python dictionary is, how it works, and what are its most common applications.

What is a Python Dictionary?

Getting clean and actionable data is one of the key challenges in data analysis. You can’t build and fit models to data that isn’t usable. A Python dictionary makes it easier to read and change data, thereby rendering it more actionable for predictive modeling.

A Python dictionary is an unordered collection of data values. Unlike other data types which hold only one value as an element, a Python dictionary holds a key: value pair. The Python dictionary is optimized in a manner that allows it to access values when the key is known.

While each key is separated by a comma in a Python Dictionary, each key-value pair is separated by a colon. Moreover, while the keys of the dictionary have to be unique and immutable (tuples, strings, integers, etcetera), the key-values can be of any type and can also be repeated any number of times. An example of a Python dictionary is shown below :

How do Python Dictionaries Work?

While there are several Python dictionary methods, there are some basic operations that need to be mastered. We will walk through the most important ones in this section.

Creating a Python dictionary

To create a Python dictionary you need to put items (each having a key and a corresponding value expressed as key: value) inside curly brackets. Each item needs to be separated from the next by a comma. As discussed above, values can repeat and be of any type. Keys, on the other hand, are unique and immutable.  There is also a built-in function dict() that you can use to create a dictionary. For easier understanding note that this built in function is written as diction() in the rest of this book. Here are some examples:

Accessing Items within the Python dictionary

Accessing items in the dictionary in Python is simple enough. All you need to do is put the key name of the item within square brackets. This is important because the keys are unique and non-repeatable.

Example

To get the value of the model key:

k = thisdiction[“model”]

You can also use another of the Python dictionary methods get() to access the item. Here’s what it looks like.

k = thisdiction.get(“model”)

How to Change Values in a Python Dictionary

To change the value of an item, you once again need to refer to the key name. Here is an example.

If you have to change the value for the key “year” from 1890 to 2025:

thisdiction = {

“brand”: “Mitsubishi”,

“model”: “Toyota”,

“year”: 1890

}

thisdiction[“year”] = 2025

How do you loop through a Python Dictionary

You can use a for loop function to loop through a dictionary in Python. By default, the return value while looping through the dictionary will be the keys of the dictionary. However, there are other methods that can be used to return the values.

To print the key names:

for k in thisdiction: 

print(k)

To print the values in the dictionary, one by one:

for k in thisdiction: 

print(thisdiction[k])

Another way of returning the values by using the values() function :

for k in thisdiction.values(): 

print(k)

If you want to Loop through both the keys and the values, you can use the items() function:

for k, m in thisdiction.items(): 

print(k, m)

How Do You Check if a Key Exists in the Dictionary

Here’s how you can determine whether a particular key is actually present in the Python dictionary :

Say you have to check whether the key “model” is present in the dictionary:

thisdiction = {

“brand”: “Mitsubishi”,

“model”: “Toyota”,

“year”: 1890

}

if “model” in thisdiction: 

print(“Yes, ‘model’ is one of the keys in the thisdiction dictionary”)

How do you determine the number of items in the Dictionary

To determine the number of key: value pairs in the dictionary we use one of the most commonly used Python Dictionary methods,  len(). Here’s how it works:

print(len(thisdiction))

How to add an item to the Python Dictionary

To add a new key: value pair to the dictionary, you have to use a new index key and then assign a value to it.

For instance,

thisdiction = {

“brand”: “Mitsubishi”,

“model”: “Toyota”,

“year”: 1890

}

thisdiction[“color”] = “pink”

print(thisdiction )

Removing Items from the Python Dictionary

Here are some of the methods to remove an item from the Python dictionary. Each approaches the same goal from a different perspective.

Method 1

This method, pop(), removes the item which has the key name that is being specified. This works well since key names are unique and immutable.

thisdiction = {

“brand”: “Mitsubishi”,

“model”: “Toyota”,

“year”: 1890

}

thisdiction.pop(“model”)

print(thisdiction)

Method 2

The popitem() method removes the item that has been added most recently. In earlier versions, this method used to remove any random item. Here’s how it works:

thisdiction = {

“brand”: “Mitsubishi”,

“model”: “Toyota”,

“year”: 1890

}

thisdiction.popitem()

print(thisdiction )

Method 3

Much like the pop() method, the del keyword removes the item whose key name has been mentioned.

thisdiction = {

“brand”: “Mitsubishi”,

“model”: “Toyota”,

“year”: 1890

}

del thisdiction[“model”]

print(thisdiction)

Method 4

Unlike the pop() method, the del keyword can also be used to delete the dictionary altogether. Here’s how it can be used to do so:

thisdiction = {

“brand”: “Mitsubishi”,

“model”: “Toyota”,

“year”: 1890

}

del thisdiction

print(thisdiction) #this will cause an error because “thisdiction” no longer exists.

Method 5

The clear() keyword empties the dictionary of all items without deleting the dictionary itself:

thisdiction = {

“brand”: “Mitsubishi”,

“model”: “Toyota”,

“year”: 1890

}

thisdiction.clear()

print(thisdiction)

A list of Common Python Dictionary Methods

There are a number of Python Dictionary methods that can be used to perform basic operations. Here is a list of the most commonly used ones.

Method

Description

clear()

This removes all the items from the dictionary

copy()

This method returns a copy of the Python dictionary

fromkeys()

This returns a different directory with only the key : value pairs that have been specified

get()

This returns the value of the key mentioned

items()

This method returns the thuple for every key: value pair in the dictionary

keys()

This returns a list of all the Python dictionary keys in the dictionary

popitem()

In the latest version, this method deletes the most recently added item

pop()

This removes only the key that is mentioned

update()

This method updates the dictionary with certain key-value pairs that are mentioned

values()

This method simply returns the values of all the items in the list

Merits of a Dictionary in Python

Here are some of the major pros of a Python library:

a)    It improves the readability of your code. Writing out Python dictionary keys along with values adds a layer of documentation to the code. If the code is more streamlined, it is a lot easier to debug. Ultimately, analyses get done a lot quicker and models can be fitted more efficiently.

b)    Apart from readability, there’s also the question of sheer speed. You can look up a key in a Python dictionary very fast. The speed of a task like looking up keys is measured by looking at how many operations it takes to finish. Looking up a key is done in constant time compared with looking up an item in a large list which is done in linear time.

To look up an item in a huge list, the computer will look through every item in the list. If every item is assigned a key-value pair then you only need to look for the key which makes the entire process much faster. A Python dictionary is basically an implementation of a hash table. Therefore, it has all the benefits of the hash table which include membership checks and speedy tasks like looking up keys.

Demerits of a Python dictionary

While a Python dictionary is easily one of the most useful tools, especially for data cleaning and data analysis, it does have a downside. Here are some demerits of using a Python dictionary.

a)    Dictionaries are unordered. In cases where the order of the data is important, the Python dictionary is not appropriate.

b)    Python dictionaries take up a lot more space than other data structures. The amount of space occupied increases drastically when there are many Python Dictionary keys. Of course, this isn’t too much of a disadvantage because memory isn’t very expensive .

Summary

At the end of the day, a Python dictionary represents a data structure that can prove valuable in cleaning data and making it actionable. It becomes even more valuable because it is inherently simple to use and much faster and more efficient as well.

Of course, if you are looking for a career in data science, a comprehensive course with live sessions, assessments, and placement assistance might be just what you need.

Data Structures in Python

Among the basic data types and structures in Python are the following:

Logical: bool

Numeric: int, float, complex

Sequence: list, tuple, range

Text Sequence: str

Binary Sequence: bytes, bytearray, memoryview

Map: dict

Set: set, frozenset

All of the above are classes from which object instances can be created. In addition to the above, more data types/structures are available in modules that come as part of any default Python installation: collections, heapq, array, enum, etc. Extra numeric types are available from modules numbers, decimals and fractions. The built-in function type() allows us to obtain the type of any object.

Explanation

With respect to data types, what are the differences between Python2 and Python3?

The following are important differences:

A division such as 5 / 2 returns integer value 2 in Python2 due to truncation. In Python3, this will evaluate to float value 2.5 even when the input values are only integers.

In Python2, strings were ASCII. To use Unicode, one had to use the unicode type by creating them with a prefix: name = u'Saṃsāra'. In Python3, str type is Unicode by default.

Python2 has int and long types but both these are integrated in Python3 as int. Integers can be as large as system memory allows.

What data structures in Python are immutable and mutable?

Mutable   objects  are those that can be changed after they are created, such as updating/adding/removing an element in a list. It can be said that mutable objects are changed in place.

Immutable objects can't be changed in place after they are created. Among the immutable basic data types/structures are bool, int, float, complex, str, tuple, range, frozenset, and bytes.

The mutable counterparts of frozenset and bytes are set and bytearray respectively. Among the other mutable data structures are list and dict.

With immutable objects it may seem like we can modify their values by assignment. What actually happens is that a new immutable object is created and then assigned to the existing variable. This can be verified by checking the ID (using id() function) of the variable before and after assignment.

What data structures in Python are suited to handle binary data?

The fundamental built-in types for manipulating binary data are bytearray and bytes. They support memoryview that makes use of the buffer protocol to access the storage location of other binary objects without making a copy.

The module array supports storage of simple data types such as thirty-two-bit integers and double floating point values. Characters, integers and floats can be stored array types, which gives low-level access to the bytes that store the data .

What containers and sequences are available in Python?

The diagram below shows List data type and its relationship to other data types.

Containers  are data structures that contain one or more objects. In Python, a container object can contain objects of different types. For that matter, a container can contain other containers at any depth. Containers may also be called collections .

Sequences  are containers that have inherent ordering among their items. For example, a string such as str = "hello world" is a sequence of Unicode characters h, e, l, etc. Note that there is no character data type in Python, and the expression "h" is actually a 1-character string.

Sequences support two main operations (for example, sequence variable seq):

Indexing: Access a particular element: seq[0] (first element), seq[-1] (last element).

Slicing: Access a subset of elements with syntax seq[start:stop:step]: seq[0::2] (alternate elements), seq[0:3] (first three elements), seq[-3:] (last three elements). Note that the stop point is not included in the result.

Among the basic sequence types are list, tuple, range, str, bytes bytearray and memoryview. Conversely, dict, set and frozenset are simply containers in which elements don't have any particular order. More containers are part of collections module.

How can I construct some common containers?

The following examples are self-explanatory:

str: a = '' (empty), a = "" (empty), a = 'Hello'

bytes: a = b'' (empty), a = b"" (empty), a = b'Hello'

list: a = list() (empty), a = [] (empty), a = [1, 2, 3]

tuple: a = tuple() (empty), a = (1,) (single item), a = (1, 2, 3), a = 1, 2, 3

set: a = set() (empty), a = {1, 2, 3}

dict: a = dict() (empty), a = {} (empty), a = {1:2, 2:4, 3:9}

We can construct bytearray from bytes and frozenset from set using their respective built-in functions.

What are iterables and iterators?

An  iterable  is a container that can be processed element by element. For sequences, elements are processed in the order they are stored. For non-sequences, elements are processed in some arbitrary order.

Formally, any object that implements the iterator protocol  is an iterable. The iterator protocol is defined by two special methods, __iter__() and __next__(). Calling iter() on an iterable returns what is called an iterator. Calling next() on an iterator gives us the next element of the iterable. Thus, iterators help us process the iterable element by element.

When we use loops or comprehensions in Python, iterators are used under the hood. Programmers don't need to call iter() or next() explicitly.

Can I convert from one data type to another?

Yes, provided they are compatible. Here are some examples:

int('3') will convert from string to integer

int(3.4) will truncate float to integer

bool(0) and bool([]) will both return False

ord('A') will return the equivalent Unicode code point as an integer value

chr(65) will return the equivalent Unicode string of one character

bin(100), oct(100) and hex(100) will return string representations in their respective bases

int('45', 16) and int('0x45', 16) will convert from hexadecimal to decimal

tuple([1, 2, 3]) will convert from list to tuple

list('hello') will split the string into a list of 1-character strings

set([1, 1, 2, 3]) will remove duplicates in the list to give a set

dict([(1,2), (2,4), (3,9)]) will construct a dictionary from the given list of tuples

list({1:2, 2:4, 3:9}) will return a list based on the dictionary keys.

Should I use a list or a tuple?

If ordering is important, sets and dictionaries should not be used: prefer lists and tuples. Tuples are used to pass arguments and return results from functions. This is because they can contain multiple elements and are immutable. Tuples are also good for storing closely related data. For example, (a, b, c) coordinates or (red, green, blue) color components can be stored as tuples. Use lists instead if values can change during the lifetime of the object.

If a sequence is to be sorted, use a list for in-place sorting. A tuple can be used but it should return a new sorted object. A tuple cannot be sorted in-place.

For better code readability, elements of a tuple can be named. For this purpose, use collections.namedtuple class. This allows us to access the elements via their names rather than tuple indices.

It's possible to convert between lists and tuples using functions list() and tuple().

When to use a set and when to use a dict?

Sets and dictionaries have no order. However, from Python 3.7, the order in which items are inserted into a dict are preserved.

Sets store unique items. Duplicates are discarded. Dictionaries can contain duplicate values but keys must be unique. Since dict keys are unique, often dict is used for counting. For example, to count the number of times a word appears in a document, words can be keys and counts can be values.

Sets are suited for finding the intersection/union of two groups, such as finding those who live in a neighborhood (set 1) and/or also own a car (set 2). Other set operations are also possible .

Strings, lists and tuples can take only integers as indices due to their ordered nature but dictionaries can be indexed by strings as well. In general, dictionaries can be indexed by any of the built-in immutable types, which are considered hashable .  Thus, dictionaries are suited for key-value pairs such as mapping country names (keys) to their capitals (values). But if capitals are the more common input to your algorithm, use them as keys instead.

How can I implement a linked list in Python?

Linked list  is a group of nodes connected by pointers or links. A  node  is one point of statistics or details in the linked list. Not only does it hold data but also it shows direction to the following node in a linked list that is single. Thus, the definition of a node is recursive. For a double-linked list, the node has two pointers, one that connects to the previous node and another one that connects to the next node. Linked lists can be designed to be ordered or unordered.

The head of the linked list must be accessible. This allows us to traverse the entire list and perform all possible operations. A double-linked list might also expose the tail for traversal from the end. While a Node class may be enough to implement a linked list, it's common to encapsulate the head pointer and all operations within LinkedList class. Operations on the linked lists are methods of the class. One possible implementation is given by Downey. A DoubleLinkedList can be a derived class from LinkedList with the addition of a tail pointer and associated methods.

Chapter 11

Data Processing, Analysis, and Visualization

If you work with data, then Data Visualization is an important part of your daily routine. And if you happen to use Python programming language for your analysis, you must be overwhelmed by the sheer number of choices available in the form of data visualization libraries. There are some libraries such as Matplotlib which are used for initial exploration but are not so useful for showing complex relationships in data. There are some which work well with large datasets while there are still others which majorly focus on 3D renderings. There is not a single visualization library that can be considered perfectly the best. There are certain features in one that is better than the other and vice versa. In short, there are a lot of options, and it is impossible to learn and try them all or maybe, get them all to work together. So how do we get our job done? PyViz definitely has the answer.

Understanding Data Processing

Data processing is the act of changing the nature of data into a form that is more useful and desirable. In other words, it is making data more meaningful and informative. By applying machine learning algorithms, statistical knowledge, and mathematical modeling, one can automate this whole process. The output of this whole process can be in any form like tables, graphs, charts, images, and much more, based on the activity done and the requirements of the machine.

This might appear simple, but for big organizations and companies like Facebook, Twitter, UNESCO, and health sector organizations, this whole process has to be carried out in a structured way. The diagram below shows some of the steps that are followed:

Let’s look in detail at each step:

Collection

The most important step when getting started with Machine Learning is to ensure that the data available is of great quality. You can collect data from genuine sources such as Kaggle, data.gov.in, and UCI dataset repository. Please see the following example, when students are getting ready to take a competitive exam, they always find the best resources to use to ensure they attain good results. Similarly, accurate and high-quality data will simplify the learning process of the model. This means that during the time of testing, the model would output the best results.

A great amount of time, capital, and resources are involved in data collection. This means that organizations and researchers have to select the correct type of data which they want to implement or research.

For instance, to work on the Facial Expression Recognition requires a lot of images that have different human expressions. A good data will make sure that the results of the model are correct and genuine.

Preparation

The data collected can be in raw form. Raw data cannot be directly fed into a machine. Instead, something has to be done on the data first. The preparation stage involves gathering data from a wide array of sources, analyzing the datasets, and then building a new data set for additional processing and exploration. Preparation can be done manually or automatically and the data should be prepared in numerical form to improve the rate of learning of the model.

Input

Sometimes, data already prepared can be in the form which the machine cannot read, in this case, it has to be converted into readable form. For conversion to take place, it is important for specific algorithm to be present.

To execute this task, intensive computation and accuracy is required. Please see the following example, you can collect data through sources like MNIST, audio files, twitter comments, and video clips.

Processing

In this stage, ML techniques and algorithms are required to execute instructions generated over a large volume of data with accuracy and better computation.

Output

In this phase, results get procured by the machine in a sensible way such that the user can decide to reference it. Output can appear in the form of videos, graphs, and reports.

Storage

This is the final stage where the generated output, data model, and any other important information are saved for future use.

Data Processing in Python

Let’s learn something in python libraries before looking at how you can use Python to process and analyze data. The first thing is to be familiar with some important libraries. You need to know how you can import them into the environment. There are different ways to do this in Python.

You can type :

Import math as m

From math import *

In the first way, you define an alias m to library math. Then you can use different functions from the math library by making a reference using an alias m. factorial ().

In the second method, you import the whole namespace in math. You can choose to directly apply factorial () without inferring to math.

Note:

Google recommends the first method of importing libraries because it will help you tell the origin of the functions.

The list below shows libraries that you’ll need to know where the functions originate from.

NumPy:   This stands for Numerical Python. The most advanced feature of NumPy is an n-dimensional array. This library has a standard linear algebra function, advanced random number capability, and tools for integration with other low-level programming languages.

SciPy: It is the shorthand for Scientific Python. SciPy is designed on NumPy. It is among the most important library for different high-level science and engineering modules such as Linear Algebra, Sparse matrices, and Fourier transform.

Matplotlib : This is best applied when you have a lot of graphs which you need to plot. It begins from line plots to heat plots and you can apply the Pylab feature in IPython notebook to ensure plotting features are inline.

Pandas: Best applied in structured data operations and manipulations. It is widely used for data preparation and mining. Pandas were introduced recently to Python and have been very useful in enhancing Python’s application in the data scientist community.

Scikit-learn: This is designed for machine learning. It was created on matplotlib, NumPy, and SciPy. This specific library has a lot of efficient tools for machine learning and statistical modeling. That includes regression, classification, clustering, and dimensionality community.

StatsModels: This library is designed for statistical modeling. Statsmodels refers to a Python module which permits users to explore data, approximate statistical models, and implement statistical tests.

Other libraries

Requests used to access the web.

Blaze used to support the functionality of NumPy and Pandas.

Bokeh used to create dashboards, interactive plots, and data applications on the current web browsers.

Seaborn is used in statistical data visualization.

Regular expressions that are useful for discovering patterns in a text data

NetWorx and Igraph applied to graph data manipulations.

Now that you are familiar with Python fundamentals and crucial libraries, let’s now jump into problem-solving through Python.

An exploratory analysis in Python with Pandas

If you didn’t know, Pandas is an important data analysis library in Python. This library has been key at improving the application of Python in the data science community. Our example uses Pandas to read a data set from an analytics Vidhya competition, run exploratory analysis, and create a first categorization algorithm to solve this problem.

Before you can load the data, it is important to know the two major data structures in Pandas. That is Series and DataFrames.

Series and DataFrames

You can think of series as a 1-dimensional labeled array. These labels help you to understand individual elements of this series via labels .

A data frame resembles an Excel workbook, and contains column names which refer to columns as well as rows that can be accessed by row numbers. The most important difference is that column names and row numbers are referred to as column and row index.

Series and data frames create a major data model for Pandas in Python. At first, the datasets have to be read from data frames and different operations can easily be subjected to these columns.

Practice data set – Loan Prediction Problem

The following is the description of variables:

First, start iPython interface in Inline Pylab mode by typing the command below on the terminal:

Import libraries and data set

This chapter will use the following python libraries:

NumPy

Matplotlib

Pandas

Once you have imported the library, you can move on and read the dataset using a function read_csv(). Below is how the code will look till this point.

Notice that the dataset is stored in

“/home/kunal/Downloads/Loan_Prediction/train.csv”

Once you read the dataset, you can decide to check a few top rows by using the function head().

Next, you can check at the summary of numerical fields by using the describe () function.

Distribution analysis

Since you are familiar with basic features of data, this is the time to look at the distribution of different variables. Let’s begin with numeric variables-ApplicantIncome and LoanAmount .

First, type the commands below to plot the histogram of ApplicantIncome.

Notice that there are a few extreme values. This is why 50 bins are needed to represent the distribution clearly.

The next thing to focus on is the box plot. The box plot for fare is plotted by:

This is just a tip of an iceberg when it comes data processing in Python.

Let’s look at:

Techniques for Preprocessing Data in Python

Here are the best techniques for Data Preprocessing in Python.

Rescaling Data

When you work with data that has different scales, you need to rescale the properties to have the same scale. The properties are rescaled between the range 0 to 1 and refer to it as normalization. To achieve this, the MinMaxScaler class from Scikit-learn is used. Please see the following example:

After rescaling, you get the values between 0 and 1. By rescaling data, it confirms the use of neural networks, optimization algorithms as well as those which have distance measures such as the k-nearest neighbors.

Normalizing Data

In the following task, you rescale every observation to a specific length of 1. For this case, you use the Normalizer class. Here is an example:

Binarizing Data

If you use the binary threshold, it is possible to change the data and make the value above it to be 1 while those that are equal to or fall below it, 0. For this task, you use the binarized class. 

As you can see, the python code will label 0 over all values equal to or less than 0, and label 1 over the rest.

Mean Removal

This is where you remove mean from each property to center it on zero.

One Hot Encoding

When you deal with a few and scattered numerical values, you might need to store them before you can carry out the One Hot Encoding. For the k-distinct values, you can change the feature into a k-dimensional vector that has a single value of 1 and 0 for the remaining values.

Label Encoding

Sometimes labels can be words or numbers. If you want to label the training data, you need to use words to increase its readability. Label encoding changes word labels into numbers to allow algorithms operate on them. Here’s an example:

Plotting using Python Funtions

NumPy and pandas are essential tools for data wrangling. Their user-friendly interfaces and performant implementation make data handling easy. Even though they only provide a little insight into our datasets, they are absolutely valuable for wrangling, augmenting, and cleaning our datasets. Mastering these skills will improve the quality of your visualizations.

Even though the statistical concepts covered are very basic, they are necessary to enrich our visualizations with information that, in most cases, is not directly provided in our datasets. This hands-on experience will help you implement exercises and activities in the following chapters.

This will give you theoretical knowledge so that you know when to use a specific chart type and why. It will also lay down the fundamentals of the chapters, which will heavily focus on teaching you how to use Matplotlib and seaborn to create the plots discussed. After we have covered basic visualization techniques with Matplotlib and seaborn, we will dive deeper and explore the possibilities of interactive and animated charts, which will introduce the element of storytelling into our visualizations.

What you should know about plots

Identify the best plot type for a given dataset and scenario

Explain the design practices of certain plots

Design outstanding, tangible visualizations

We will describe visualizations in detail and give practical examples, such as comparing different stocks over time or comparing the ratings for different movies. Starting with comparison plots, which are great for comparing multiple variables over time, we will look at their types, such as line charts, bar charts, and radar charts. Relation plots are handy to show relationships among variables. We will cover scatter plots for showing the relationship between two variables, bubble plots for three variables, correlograms for variable pairs, and, finally, heatmaps.

Composition plots, which are used to visualize variables that are part of a whole, as well as pie charts, stacked bar charts, stacked area charts, and Venn diagrams are going to be explained. To get a deeper insight into the distribution of variables, distribution plots are used. As a part of distribution plots, histograms, density plots, box plots, and violin plots will be covered. Finally, we will talk about dot maps, connection maps, and choropleth maps, which can be categorized into geo plots.

Comparison Plots

Comparison plots include charts that are well-suited for comparing multiple variables or variables over time. For a comparison among items, bar charts (also called column charts) are the best way to go. Line charts are great for visualizing variables over time. For a certain time period (say, less than ten time points), vertical bar charts can be used as well. Radar charts or spider plots are great for visualizing multiple variables for multiple groups.

Line Chart

Line charts are used to display quantitative values over a continuous time period and show information as a series. A line chart is ideal for a time series, which is connected by straight-line segments.

The value is placed on the y-axis, while the x-axis is the timescale.

Uses:

Line charts are great for comparing multiple variables and visualizing trends for both single as well as multiple variables, especially if your dataset has many time periods (roughly more than ten) .

For smaller time periods, vertical bar charts might be the better choice.

The following diagram shows a trend of real-estate prices (in million US dollars) for two decades. Line charts are well-suited for showing data trends:

Line chart for a single variable

Example:

The following diagram is a multiple variable line chart that compares the stock-closing prices for Google, Facebook, Apple, Amazon, and Microsoft. A line chart is great for comparing values and visualizing the trend of the stock. As we can see, Amazon shows the highest growth:

Figure: Line chart showing stock trends for the five companies

Design practices:

Avoid too many lines per chart

Adjust your scale so that the trend is clearly visible

Note

Design practices for plots with multiple variables. A legend should be available to describe each variable.

Bar Chart

The bar length encodes the value. There are two variants of bar charts: vertical bar charts and horizontal bar charts.

Uses:

While they are both used to compare numerical values across categories, vertical bar charts are sometimes used to show a single variable over time .

The do's and the don'ts of bar charts:

Don't confuse vertical bar charts with histograms. Bar charts compare different variables or categories, while histograms show the distribution for a single variable. Histograms will be discussed later in this chapter.

Another common mistake is to use bar charts to show central tendencies among groups or categories. Use box plots or violin plots to show statistical measures or distributions in these cases.

Examples:

The following diagram shows a vertical bar chart. Each bar shows the marks out of 100 that five students obtained in a test:

Figure: Vertical bar chart using student test data

The following diagram shows a horizontal bar chart. Each bar shows the marks out of 100 that five students obtained in a test:

Figure: Horizontal bar chart using student test data

The following diagram compares movie ratings, giving two different scores. The Tomatometer is the percentage of approved critics who have given a positive review for the movie. The Audience Score is the percentage of users who have given a score of 3.5 or higher out of 5. As we can see, The Martian is the only movie with both a high Tomatometer score and Audience Score. The Hobbit: An Unexpected Journey has a relatively high Audience Score compared to the Tomatometer score, which might be due to a huge fan base:

Comparative bar chart

Design practices:

The axis corresponding to the numerical variable should start at zero. Starting with another value might be misleading, as it makes a small value difference look like a big one.

Use horizontal labels, that is, as long as the number of bars is small and the chart doesn't look too cluttered.

Radar Chart

Radar charts , also known as spider or web charts , visualize multiple variables with each variable plotted on its own axis, resulting in a polygon. All axes are arranged radially, starting at the center with equal distances between one another and have the same scale.

Uses:

Radar charts are great for comparing multiple quantitative variables for a single group or multiple groups.

They are also useful to show which variables score high or low within a dataset, making them ideal to visualize performance

Examples:

The following diagram shows a radar chart for a single variable. This chart displays data about a student scoring marks in different subjects:

Conclusion

Thank you for making it to the last chapter of the book Python for beginners.  I hope that you found it informative and helpful. Every measure was taken into consideration to ensure that all the chapters give you detailed and easy to understand information. I intentionally used simple language throughout the book to make sure that you get empowered after reading. The book has deliberately avoided sophisticated theories and stuck to simple Explanations that you can use at your convenience when studying.

The moment you understand programming basics using Python language, it becomes easier to learn advanced concepts such as Artificial Intelligence and Machine Learning. Artificial intelligence is important in everyday life.  This book has taken you through many concepts of Python Programming such as Data Analysis, Polymorphism, Inheritance, Lists, Classes, Loops, Objects, Variables, Methods, and many more.  There is no one specific thing that you can do to learn object-oriented programming overnight. However, if you follow the right steps with commitment and dedication, you will get the results you desire. Make it your routine to combine a number of practical sessions to improve your python programming skills. If you are working with an experienced programmer, follow all the instructions provided to you and ask questions where you do not understand.

The next step is to stop reading and start applying the lessons you have learned in real life. Do whatever you have identified as necessary to improve applications of programming in real life.  You will realize that the majority of those who seem to have it all together lack the basic Python programming skills. Try to engage them and teach them a thing or two you have learned herein. You may even recommend or gift this book to them.  

Finally, if you found this book useful in any way, a good review on Amazon will be highly appreciated !