Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views

New Dou-Csc111 Introduction To Programing - Python February 2024

Uploaded by

ejerajosiah38
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

New Dou-Csc111 Introduction To Programing - Python February 2024

Uploaded by

ejerajosiah38
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 152

Introduction to Computer Programming I

using Python

By

Odeh Christopher & Azaka Maduabuchuku

Faculty of Computing
Department of Computer Science
Dennis Osadebay Universuty,
(DOU)
Awai, Asaba, Delta State

1
Introduction to Computer Programming I ............................................................................................... 1

Introduction to Programming: Computer in Many Forms ............................................................................ 6

Introduction to Programming: Definitions ................................................................................................... 6

Definitions: .................................................................................................................................................... 6

What is Python .............................................................................................................................................. 7

Python Features ......................................................................................................................................... 7

Python History and Versions ......................................................................................................................... 9

Why the Name Python? ................................................................................................................................ 9

Areas of Application of Python ................................................................................................................... 10

How to Install Python on Windows: Step-by-Step Guide ........................................................................... 12

What are IDEs and Code Editors? ............................................................................................................... 17

IDE vs. Code Editor: What's the Difference?............................................................................................... 17

Top Python IDEs .......................................................................................................................................... 17

Features of an IDE ....................................................................................................................................... 26

How to Install All Python Modules at Once Using Pip? .............................................................................. 27

What’s a Python package? .......................................................................................................................... 27

What is the Python Package Index (PyPI)? ................................................................................................. 27

How to install a package with pip? ............................................................................................................. 27

Operator in Pip Command .......................................................................................................................... 30

Why is installing all packages at once bad? ................................................................................................ 31

How to Install Visual Studio Code on Windows? ........................................................................................ 32

Installing Visual Studio Code on Windows.................................................................................................. 32

Setting up Python Programming Environment in mobile phone................................................................ 39

Setting Up Python Programming Environment in PC ......................................................................... 41

Setting up Python Programming Environment: VS Code IDE........................................................... 43

2
Python Keywords ........................................................................................................................................ 45

Introducing Python Keywords..................................................................................................................... 45

Analysis of basic problem-solving methods, ............................................................................................... 46

Basic Concept of Software Development ................................................................................................... 48

What is computer best definition? ............................................................................................................. 48

Problem Solving Using Computer (Steps) ................................................................................................... 48

Problem Analysis ......................................................................................................................................... 48

Program Design ........................................................................................................................................... 49

Guidelines for Developing an Algorithm ..................................................................................................... 50

Standard Flowchart Symbols ...................................................................................................................... 50

Guidelines for Preparing Flowchart ............................................................................................................ 51

Pseudocodes: Guidelines, Advantages & Disadvantages ................................................................. 53

Guidelines for Preparing Pseudocode ........................................................................................................ 53

Coding (Programming) ................................................................................................................................ 54

Compilation and Execution Process ............................................................................................................ 54

Compilation Process.................................................................................................................................... 54

General compilation process is shown in Figure below: ............................................................................ 55

Debugging and Testing (Error and Types Included) .................................................................................... 55

Error ............................................................................................................................................................ 55

Types of Error:............................................................................................................................................. 56

Program (Programmer's and User's) Documentation ................................................................................ 56

Python Program to demonstrate coding/Problem Solving Stages ............................................................. 57

Python Literals ............................................................................................................................................ 59

Python as interpreted Language ................................................................................................................. 61

Python Indentation ..................................................................................................................................... 62

3
Comments ................................................................................................................................................... 63

Variables ..................................................................................................................................................... 65

String variables............................................................................................................................................ 66

Variable Names Description........................................................................................................................ 66

Valid variable names: .................................................................................................................................. 66

Multi Words Variable Names ...................................................................................................................... 67

Python Variables - Assign Multiple Values ........................................................................................... 68

Python - Output Variables ....................................................................................................................... 68

Python - Global Variables ....................................................................................................................... 70

The global Keyword..................................................................................................................................... 70

Python Numbers ......................................................................................................................................... 71

Integer ........................................................................................................................................................ 72

Float ............................................................................................................................................................ 72

Complex ...................................................................................................................................................... 73

Type Conversion.......................................................................................................................................... 73

Python Casting ......................................................................................................................................... 74

Implicit Type Conversion in Python ............................................................................................................ 75

Strings ........................................................................................................................................................ 78

Assign String to a Variable .......................................................................................................................... 78

Multiline Strings .......................................................................................................................................... 79

String Concatenation .................................................................................................................................. 83

Python Booleans ...................................................................................................................................... 84

Python Operators ..................................................................................................................................... 86

Python Data Types ...................................................................................................................................... 91

Python Lists ............................................................................................................................................... 92

4
Python Tuples ......................................................................................................................................... 105

Python Sets ............................................................................................................................................... 114

Python Dictionaries ................................................................................................................................ 122

Dictionary Items ........................................................................................................................................ 122

Control Structures: Conditional Statements ....................................................................................... 134

Indentation in if statement ....................................................................................................................... 135

Python Loops .......................................................................................................................................... 139

The while Loop .......................................................................................................................................... 139

The break Statement ................................................................................................................................ 140

Python for Loops .................................................................................................................................... 140

The break Statement ................................................................................................................................ 141

The continue Statement ........................................................................................................................... 141

Nested Loops ............................................................................................................................................ 143

The pass Statement................................................................................................................................... 144

Python Functions ...................................................................................................................................... 144

Arrays ........................................................................................................................................................ 148

What is an Array? ...................................................................................................................................... 148

Python Classes/Objects............................................................................................................................. 150

Bibliography .............................................................................................................................................. 152

5
Introduction to Programming: Computer in Many Forms

Introduction to Programming: Definitions


Definitions:
1) Program: A series of codes written in a computer programming language to perform a
task
2) Programming: The process of writing a program or coding. Also the process of setting
something up to perform at action either in the presence or future
3) Software: A collection of programs that have been packaged with some other items
such as images or files which together serve a specific purpose. Eg. Microsoft Word
4) System Software: Software that controls the operation of a computer. Eg. MacOS,
Android, Windows
5) Application Software: Software that is developed for some specific or related
applications. Eg. Excel.
6) Embedded Software: software that runs in a computer that is inside another machine
7) Editor: software that is used to type computer programs eg notepad
8) Integrated Development Environment (IDE): a software that is used to type, edit, debug
and execute computer programs
9) Programming language: a software that has some organized syntax and semantics to
enable one develop computer programs. E.g. Python, Java, C#, C, C++

6
10) Source code: the original program written in a programming language
11) Interpreter: Software that helps translate source code one-by-one into executable code.
Eg. Python is an “interpreted” programming language
12) Compiler: software that is used to write computer programs that helps convert an entire
source code into an executable file. Eg. Java, C, C++ is are compilers
13) Assembler: software that is used to program a specific computer processor. It cannot be
used for a different processor
14) App: software designed for a single purpose single function
15) Utilities: system software that helps to maintain the proper and smooth functioning of a
Computer System
16) Drivers: software that helps to connect computer hardware devices together. Eg you
have to install the printer driver before you can connect your brand new printer to your
computer
17) Machine language: the syntax of a specific processor
18) Assembly language: an assembler is implemented in the assembly language of a
specific processor
19) Low – level language: programming languages that are close to the processor, eg.
Machine language, assembly language and C.
20) High level language: languages that are not close to the processor and so, can be used
in a variety of computers. Eg. Python, Java, Php, etc.
21) Application programming interface (API): a collection of program functions that have
been developed and added to a programming language or software to make
programming easier for programmers.
22) Built-in functions (BIF) : similar to API. They are a collection of libraries in a
programming language or a software to make programming work easier
etc

What is Python
Python is a general purpose, dynamic, high-level, and interpreted (it translate source
code one-by-one into executable code) programming language. It supports Object
Oriented programming approach to develop applications. It is simple and easy to learn
and provides lots of high-level data structures.
Python Features
Python provides many useful features which make it popular and valuable from the
other programming languages. It supports object-oriented programming, procedural
programming approaches and provides dynamic memory allocation. We have listed
below a few essential features.

1) Easy to Learn and Use

7
Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the
semicolon or curly-bracket, the indentation defines the code block. It is the
recommended programming language for beginners.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the
hello world program you simply type print("Hello World"). It will take only one line to
execute, while Java or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at
a time. The advantage of being interpreted language, it makes debugging easy and
portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a
program only once.
5) Free and Open Source
Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly
working towards making new python modules and functions. Anyone can contribute to
the Python community. The open-source means, "Anyone can download its source
code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come
into existence. It supports inheritance, polymorphism, and encapsulation, etc. The
object-oriented procedure helps programmer to write reusable code and develop
applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our Python code. It converts the program into byte code,
and any platform can use that byte code.
8) Large Standard Library
It provides a vast range of libraries for various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such
as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are
the popular framework for Python web development.
9) GUI Programming Support

8
Graphical User Interface is used for developing Desktop application. PyQT5, Tkinter,
Kivy are the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code
line by line like C,C++ Java. It makes it easy to debug the code.
11. Embeddable
The code of the other programming language can use the Python source code. We can
use Python source code in another programming language as well. It can embed other
language into our code.
12. Dynamic Memory Allocation
In Python, we don't need to specify the data-type of the variable. When we assign some
value to the variable, it automatically allocates the memory to the variable at run time.
Suppose we assigned integer value 15 to x, then we don't need to write int x = 15. Just
write x = 15.

Python History and Versions


a) Python laid its foundation in the late 1980s.
b) The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
c) In February 1991, Guido Van Rossum published the code (labeled version
0.9.0) to alt.sources.
d) In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
e) Python 2.0 added new features such as list comprehensions, garbage collection
systems.
f) On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.
g) ABC programming language is said to be the predecessor of Python language,
which was capable of Exception Handling and interfacing with the Amoeba
Operating System.
Why the Name Python?
There is a fact behind choosing the name Python
Guido van Rossum was reading the script of a popular BBC comedy series "Monty
Python's Flying Circus". It was late on-air 1970s.Van Rossum wanted to select a
name which is unique and little-bit mysterious. So he decided to select naming Python
after the "Monty Python's Flying Circus" for their newly created programming
language.

9
The comedy series was creative and well random. It talks about everything. Thus it is
slow and unpredictable, which made it very interesting.

Areas of Application of Python


Python is known for its general-purpose nature that makes it applicable in almost every
domain of software development. Python makes its presence in every emerging field. It
is the fastest-growing programming language and can develop any application. Here,
we are specifying application areas where Python can be applied.

1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, etc. One of Python web-
framework named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:
a) Django and Pyramid framework(Use for heavy applications)
b) Flask and Bottle (Micro-framework)
c) Plone and Django CMS (Advance Content management)
2) Desktop GUI Applications

10
The GUI stands for Graphical User Interface, which provides a smooth interaction to
any application. Python provides a Tk GUI library to develop a user interface. Some
popular GUI libraries are given below.
a) Tkinter or Tk
b) wxWidgetM
c) Kivy (used for writing multitouch applications )
d) PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. This kind of application
was more popular in the old generation of computers. Python can develop this kind of
application very effectively. It is famous for having REPL, which means the Read-Eval-
Print Loop that makes it the most suitable language for the command-line applications.
Python provides many free library or module which helps to build the command-line
apps. The necessary IO libraries are used to read and write.
4) Software Development
Python is useful for the software development process. It works as a support language
and can be used to build control and management, testing, etc.
a) SCons is used to build control.
b) Buildbot and Apache Gumps are used for automated continuous compilation
and testing.
c) Round or Trac for bug tracking and project management.
5) Scientific and Numeric
This is the era of Artificial intelligence where the machine can perform the task the same
as the human. Python language is the most suitable language for Artificial intelligence
or machine learning. It consists of many scientific and mathematical libraries, which
makes it easy to solve complex calculations.
Implementing machine learning algorithms require complex mathematical calculation.
Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy,
Scikit-learn, etc. If you have some basic knowledge of Python, you need to import
libraries on the top of the code. Few popular frameworks of machine libraries are given
below.
a) SciPy
b) Scikit-learn
c) NumPy
d) Pandas
e) Matplotlib
6) Business Applications

11
Business Applications differ from standard applications. E-commerce and ERP are an
example of a business application. This kind of application requires extensive scalability
and readability, and Python provides all these features.
7) Audio or Video-based Applications
Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python
are TimPlayer, cplay, etc.
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It
is used to develop the 3D representation of a part of a system. Python can create a 3D
CAD application by using the following functionalities.
a) Fandango (Popular )
b) CAMVOX
c) HeeksCNC
d) AnyCAD
e) RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
10) Image Processing Application
Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements.

How to Install Python on Windows: Step-by-Step Guide

12
By default, Python is usually not installed on Windows. However, you can check if it
exists on the system by running one line of command on the command prompt: python--
version
To download Python, you need to visit www.py,thon.org, which is the official Python
website.

Click on the Downloads tab and then select the Windows option.

This will take you to the page where the different Python releases for Windows can be
found. Since I am using a 64bit system, I‟ll select “Windows x86-64 executable
installer”.

13
Once the executable file download is complete, you can open it to install Python.

Click on Run, which will start the installation process.

If you want to save the installation file in a different location, click on Customize
installation; otherwise, continue with Install Now. Also, select the checkbox at the
bottom to Add Python 3.7 to PATH.

14
Once the installation is complete, the below pop-up box will appear: Setup was
successful.

Now that the installation is complete, you need to verify that everything is working fine.
Go to Start and search for Python.

15
You can see Python 3.7 (64-bit) and IDLE. Let‟s open IDLE, which is the short form for
Integrated Development Environment, and run a simple print statement.

As you can see, we have successfully printed “Hello World” in Python Shell. Using the
Python Shell, you can write one line of code and execute it by pressing Enter.
Python also has a command-line interpreter that works similarly to Python IDLE. Let‟s
print “Hello world” in the command-line.

Python‟s command-line interpreter and IDLE are suitable for any beginner to start with.
However, to work in a development environment and build large scale projects, you
should use other popular IDEs and code editors, such as PyCharm, Atom, and Sublime
Text. You can also try out the Anaconda Distribution of Python, which has Jupyter
Notebook and Spyder.
I hope this was helpful, and you were successfully able to download and install Python
on Windows.

16
{Python Shell -- Python provides a Python shell, and it is applied to execute a single
Python command and display the result. Python Shell or REPL which means Read,
Evaluate, Print, and Loop. Python shell reads the complete commands, evaluates the
command, prints the result, and loops it back to reread. Python Shell can be installed
easily by google extension.}

What are IDEs and Code Editors?


IDEs and code editors are tools that software developers use to write and edit code.
 IDEs, or Integrated Development Environments, are usually more feature-rich
and include tools for debugging, building and deploying code.
 IDEs increase programmer productivity by introducing features like editing source
code, building executables, and debugging
 Code editors are generally more straightforward and focused on code editing.
Many developers use IDEs and code editors, depending on the task they want to
achieve.

IDE vs. Code Editor: What's the Difference?


 An Integrated Development Environment (IDE) is a software application that
provides tools and resources to help developers write and debug code. An IDE
typically includes
 A source code editor
 A compiler or interpreter
 An integrated debugger
 A graphical user interface (GUI)
 A code editor is a text editor program designed specifically for editing source
code. It typically includes features that help in code development, such as syntax
highlighting, code completion, and debugging.
 The main difference between an IDE and a code editor is that an IDE has a
graphical user interface (GUI) while a code editor does not. An IDE also has
features such as code completion, syntax highlighting, and debugging, which are
not found in a code editor.
 Code editors are generally simpler than IDEs, as they do not include many other
IDE components. As such, code editors are typically used by experienced
developers who prefer to configure their development environment manually.

Top Python IDEs


Now that you know about the Integrated Development Environment, let's look at a few
popular Python IDEs.
1. IDLE

17
 IDLE (Integrated Development and Learning Environment) is a default editor that
accompanies Python
 This IDE is suitable for beginner-level developers
 The IDLE tool can be used on Mac OS, Windows, and Linux
 Price: Free
The most notable features of IDLE include:
 Ability to search for multiple files
 Interactive interpreter with syntax highlighting, and error and i/o messages
 Smart indenting, along with basic text editor features
 A very capable debugger
 It‟s a great Python IDE for Windows

2. PyCharm
 PyCharm is a widely used Python IDE created by JetBrains
 This IDE is suitable for professional developers and facilitates the development
of large Python projects
The most notable features of PyCharm include:
 Support for JavaScript, CSS, and TypeScript
 Smart code navigation
 Quick and safe code refactoring
 Support features like accessing databases directly from the IDE
 Its a great Python IDE for Windows

18
3. Visual Studio Code
 Visual Studio Code is an open-source (and free) IDE created by Microsoft. It
finds great use in Python development
 VS Code is lightweight and comes with powerful features that only some of the
paid IDEs offer
The most notable features of Visual Studio Code include:
 One of the best smart code completion is based on various factors
 GIT integration (Global Information Tracker) is integrated within the IDE, which
means you can run some commands like git clone , git pull , git commit , and so
on, to help you with source control management.
 Code debugging within the editor
 It provides an extension to add additional features like code highlighting, themes,
and other services

19
4. Sublime Text 3
 Sublime Text is a very popular code editor. It supports many languages,
including Python
 It is highly customizable and also offers fast development speeds and reliability
The most notable features of Sublime Text 3 include:
 Syntax highlighting
 Custom user commands for using the IDE
 Efficient project directory management
 It supports additional packages for the web and scientific Python development
 Its a great Python IDE for Windows

20
5. Atom
 Atom is an open-source code editor by GitHub and supports Python development
 Atom is similar to Sublime Text and provides almost the same features emphasis
on speed and usability
The most notable features of Atom include:
 Support for a large number of plugins
 Smart auto-completion
 Supports custom commands for the user to interact with the editor
 Support for cross-platform development

6. Jupyter
 Jupyter is widely used in the field of data science
 It is easy to use, interactive and allows live code sharing and visualization
The most notable features of Jupyter include:
 Supports for the numerical calculations and machine learning workflow
 Combine code, text, and images for greater user experience
 Intergeneration of data science libraries like NumPy, Pandas, and Matplotlib

21
7. Spyder
 Spyder is an open-source IDE most commonly used for scientific development
 Spyder comes with Anaconda distribution, which is popular for data science and
machine learning
The most notable features of Spyder include:
 Support for automatic code completion and splitting
 Supports plotting different types of charts and data manipulation
 Integration of data science libraries like NumPy, Pandas, and Matplotlib
 Its a great Python IDE for Windows

22
8. PyDev
 PyDev is a strong python interpreter and is distributed as a third-party plugin for
Eclipse IDE
 Being flexible, it is one of the preferred open-source IDE by the developers
The most notable features of PyDev include:
 Django integration, auto code completion, and code coverage
 Supports type hinting, refactoring, as well as debugging and code analysis
 Good support for Python web development

23
9. Thonny
 Thonny is an IDE ideal for teaching and learning Python programming
The most notable features of Thonny include:
 Simple debugger
 Function evaluation
 Automatic syntax error detection
 Detailed view of variables used in a Python program or project

24
10. Wing
 The wing is also a popular IDE that provides a lot of good features to ensure a
productive environment
 Wing offers a 30-day trial version for the developers to check and understand the
features of this IDE
 Price: US $95 - US$179 for commercial license
The most notable features of Wing include:
 It provides immediate feedback to your Python code
 It provides support for test-driven development with unit tests, Pytest, and Django
testing framework.
 It assists in remote development
 Auto code completion is present
11. Vim:
It is a flexible, open-source terminal-based text editor. Vi Improved, which means it is a
revamped version of the Vi text editor.
12. GNU/Emacs:

25
Finding the right code editor for python development can be tricky. Emacs is a set of
macro extensions for different code editors. Richard Stallman adopted it into the GNU
project in the early 1980s.
13. Dreamweaver:
It is one of the popular web development IDE tools. It helps you to create, publish and
manage websites. It can be uploaded to any web server.
14. Eric:
It is a full-featured python editor and IDE, built on the cross-platform
Qt GUI development framework. It has excellent plug-in management support.
15. Visual Studio:
It is an integrated development environment from Microsoft. It is used to develop
computer programs such as web services, web apps, and mobile applications.
16. Pyscripter:
It has all the features expected in a modern Python IDE in a lightweight package. It is
compiled for windows to combine minimal memory consumption with maximum
performance.
17. Rodeo:
It is one of the best IDEs for Python. It was developed for data science-related tasks like
taking data and information from different resources and also plotting for issues. It
supports cross-platform functionality. It can also be used as an IDE for experimenting
interactively.
Features of an IDE
1. Syntax Highlighting
An IDE that knows your language's syntax can provide visual cues and keywords that
are easier to read by visually clarifying the language syntax.
Code without Syntax

Code with Syntax

26
2. Auto-complete
IDEs are generally really good at anticipating what you're more likely to type next,
making coding significantly faster and simpler.
3. Building Executables
IDE takes care of interpreting the Python code, running python scripts, building
executables, and debugging the applications.
4. Debugging
In the event that a program does not run correctly, programmers can easily detect their
code errors using the debugging tools that IDEs offer.

How to Install All Python Modules at Once Using Pip?


One of the most essential tools that make Python one of the best languages is its
package manager called „pip‟, which installs packages. It is written in Python itself and
is the most preferred package manager. It is a command-line tool and can be used to
install, modify, or delete all the packages available in the Python Package Index on your
system within your command-line interface (CLI). From version 3.4 of Python, pip
started coming in pre-installed with the Python language itself.
Let see how we can install a package using pip, and then we‟ll see how we can install
multiple packages at the same time.
What’s a Python package?
A Python package is a collection of related modules that have been bundled together in
a directory for distribution.
What is the Python Package Index (PyPI)?
The Python Package Index helps extend the functionalities of the standard Python
library. The standard Python library has a lot of modules that are built in Python. The
Python Package Index allows you to distribute packages you‟ve created among other
Python programmers.
How to install a package with pip?
The pip command allows you to install a Python package on your system from Python
Package Index (PyPI).
To install a package with pip, you can use the following command line in your shell
window.

pip install <package-name>

27
--upgrade flag
The --upgrade flag can be used to upgrade an already existing package in your system.
pip install --upgrade <package_name>

How to install multiple Python packages using pip?


To install multiple packages at once using the pip command, you can pass multiple
package names in the pip install command and the tool will install all of them into your
system.
pip install numpy matplotlib scipy

28
“==“ operator

The "==" operator is used to specify the version of the package you want to install.
When you just use the pip install <package-name> command, the pip manager installs
the latest version of the package you‟ve requested to install. Sometimes, you don‟t need
the latest version of the package. You may need some previous versions of a package
to resolve some compatibility issues. But most of the time, installing a lower version of a
package will lead to compatibility issues. So you need to be cautious before doing it.

pip install package_name==numpy

29
Operator in Pip Command
When we try to install a specific version of the numPy library, you can see that there is a
version of numPy installed beforehand on my system, and Pip had to uninstall that to
install another version of the package. When we uninstall that previous package, you
can see that the other packages which were dependent on that version of the numPy
broke, and consecutively the error is shown.

"requirements.txt"

The "requirements.txt" text file is the standard way of installing all the packages required
for a Python project. In this process, you create a file named requirement.txt and then
write the name of all the packages you need in that project and also specify the version
limits.
First, we‟ll create the requirement.txt file and write all the packages required in our
project with their version specified.
numpy==1.19.5
pandas==1.3.0
scipy==1.7.0
matplotlib==3.4.2

After that, we can use the pip install command with the -r flag to install all the projects
mentioned in this requirement.txt file.

pip install -r requirements.txt

30
Requirements Txt
Doing so installed all the mentioned packages of their respective versions just like it
would if you are directly installing it with the pip command.
How to install all Python packages using pip? (not recommended)
Now the requirements.txt file may have speed up the process of setting up your project
a bit, but you still needed to write all that text in the file. Even then, you got only one
project setup. What if another project needs another package? You will need to rewrite
the entire requirements.txt. So if you want, you can use these methods to install all the
libraries available at the PyPI (Python Package Index).
Why is installing all packages at once bad?
The reasons why you should not do so are:
 One Python package is often dependent on other Python packages, and
sometimes different Python packages are dependent on different versions of the
same package. This will lead to compatibility issues.
 The Python Package Index contains 1000s of packages. Installing all of them will
fill up your storage and will lead to disk usage issues.
 Installing all the packages will also lead to management and maintenance issues
of the packages in your system, as it will clutter your environment.
31
 Installing all packages will also install the packages which have security
vulnerabilities. This raises security risks too.

How to Install Visual Studio Code on Windows?


Visual Studio Code is the most popular code editor and the IDEs provided by Microsoft
for writing different programs and languages. It allows the users to develop new code
bases for their applications and allow them to successfully optimize them and debug
them properly. It is a very user-friendly code editor and it is supported on all the different
types of operating systems like Windows, macOS, and Linux. It has the support for all
the languages like C, C++, Java, Python, JavaScript, React, Node JS, etc.
Installing Visual Studio Code on Windows
Follow the below steps to install Visual Studio Code on Windows:
Step 1: Visit the official website (https://code.visualstudio.com/download) of the Visual
Studio Code using any web browser like Google Chrome, Microsoft Edge, etc.

Step 2: Press the “Download for Windows” button on the website to start the
download of the Visual Studio Code Application.

32
Step 3: When the download finishes, then the Visual Studio Code icon appears in the
downloads folder.

Step 4: Click on the installer icon to start the installation process of the Visual Studio
Code.
Step 5: After the Installer opens, it will ask you for accepting the terms and conditions of
the Visual Studio Code. Click on “I accept the agreement” and then
click the Next button.

33
Step 6: Choose the location data for running the Visual Studio Code. It will then ask you
for browsing the location. Then click on Next button.

34
Step 7: Then it will ask for beginning the installing setup. Click on the Install button.

35
Step 8: After clicking on Install, it will take about 1 minute to install the Visual Studio
Code on your device.

36
Step 9: After the Installation setup for Visual Studio Code is finished, it will show a
window like this below. Tick the “Launch Visual Studio Code” checkbox and then
click Next.

37
Step 10: After the previous step, the Visual Studio Code window opens successfully.
Now you can create a new file in the Visual Studio Code window and choose a
language of yours to begin your programming journey!

38
So this is how we successfully installed Visual Studio Code on our Windows system.

Setting up Python Programming Environment in mobile phone

39
40
Setting Up Python Programming Environment in PC

41
42
Setting up Python Programming Environment: VS Code IDE

Search results - Python IntelliSense Microsoft | Visual Studio Code , Visual Studio Marketplace click this
link to install all python extension below

43
44
Python Keywords
Every scripting language has designated words or keywords, with particular definitions
and usage guidelines. Python is no exception.
Introducing Python Keywords
Python keywords are unique words reserved with defined meanings and functions that
we can only apply for those functions. You'll never need to import any keyword into your
program because they're permanently present.
Assigning a particular meaning to Python keywords means you can't use them for other
purposes in our code. You'll get a message of SyntaxError if you attempt to do the
same. If you attempt to assign anything to a built-in method or type, you will not receive
a SyntaxError message; however, it is still not a smart idea.
Python contains thirty-five keywords in version 3.8. Here we have shown a complete list
of Python keywords for the reader's reference.
False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield


In distinct versions of Python, the preceding keywords might be changed. Some extras
may be introduced, while others may be deleted. By writing the following statement into
the coding window, you can anytime retrieve the collection of keywords in the version
you are working on.
Code
1 # import keyword library
2 import keyword
3 list = keyword.kwlist
4 print("No. of keywords present in current version :",
5 len(list))
6 print(list)
Output:
No. of keywords present in current version : 35

45
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Code

Analysis of basic problem-solving methods,

Problem Solving: Steps, Methods, and Tools for Effective Solutions


Problem-solving is a crucial skill that enables individuals and organizations to overcome
challenges and achieve desired outcomes. Whether you're facing a complex issue at
work or trying to resolve a personal dilemma, having a structured approach can greatly
enhance your problem-solving abilities. Here we will explore the steps, methods, and
tools that can help us tackle problems effectively and find optimal solutions.
1. Define the Problem:
The first step in problem-solving is to clearly define the problem at hand. Take the time
to understand the root cause, identify the desired outcome, and gather relevant
information. This step sets the foundation for the entire problem-solving process.
2. Analyze the Situation:
Once the problem is defined, it's important to analyze the situation thoroughly. Break
down the problem into smaller components, examine any patterns or trends, and
consider any constraints or limitations. This analysis will help you gain a deeper
understanding of the problem and its underlying factors.
3. Generate Possible Solutions:

46
With a clear understanding of the problem, it's time to brainstorm potential solutions.
Encourage creativity and consider all possible options, even if they seem
unconventional. This step is about quantity, not quality, so aim to generate as many
ideas as possible.
4. Evaluate and Select the Best Solution:
After generating a list of potential solutions, it's time to evaluate each option based on
its feasibility, effectiveness, and alignment with the desired outcome. Consider the pros
and cons of each solution and weigh them against each other. Select the solution that
appears to be the most viable and likely to solve the problem effectively.
5. Implement the Solution:
Once you have chosen the best solution, it's time to put it into action. Develop a detailed
plan, allocate necessary resources, and communicate the plan to relevant stakeholders.
Ensure that everyone involved understands their roles and responsibilities in
implementing the solution.
6. Monitor and Evaluate:
Implementing the solution is not the end of the problem-solving process. Continuously
monitor the progress and evaluate the effectiveness of the solution. If necessary, make
adjustments or modifications to improve the outcome. Learning from the process is
crucial for future problem-solving endeavors.

Methods and Tools for Problem Solving:


- Root Cause Analysis: A method used to identify the underlying cause of a problem by
asking "why" repeatedly.
- SWOT Analysis: A tool that helps analyze the strengths, weaknesses, opportunities,
and threats related to a problem or situation.
- Fishbone Diagram: A visual tool that helps identifies potential causes of a problem by
categorizing them into different branches.
- Decision Matrix: A tool that helps evaluate and compare different options based on
predefined criteria.
- Pareto Analysis: A technique that prioritizes problems or causes based on their impact
and frequency.
Conclusion:
Problem-solving is a skill that can be developed and honed with practice. By following a
structured approach, utilizing various methods and tools, and continuously learning from
the process, you can become a more effective problem solver. Remember, problem-
solving is not just about finding solutions; it's about understanding the problem deeply
and making informed decisions to achieve the desired outcome .

47
Basic Concept of Software Development
What is computer best definition?
A computer is a device that accepts information (in the form of digitalized data) and
manipulates it for some result based on a program, software, or sequence of
instructions on how the data is to be processed.
Problem Solving Using Computer (Steps)
Computer based problem solving is a systematic process of designing, implementing
and using programming tools during the problem solving stage. This method enables
the computer system to be more intuitive with human logic than machine logic. Final
outcome of this process is software tools which is dedicated to solve the problem under
consideration.
The following six steps must be followed to solve a problem using computer system.
1. Problem Analysis
2. Program Design - Algorithm, Flowchart and Pseudocode
3. Coding
4. Compilation and Execution
5. Debugging and Testing
6. Program Documentation

Problem Analysis
Problem analysis is the process of defining a problem and decomposing overall system
into smaller parts to identify possible inputs, processes and outputs associated with the
problem. This task is further subdivided into six subtasks namely:
1. Specifying the Objective :
First, we need to know what problem is actually being solved. Making a clear statement
of the problem depends upon the size and complexity of the problem. Smaller problems
not involving multiple subsystems can easily be stated.
2. Specifying the Output :
Before identifying inputs required for the system, we need to identify what comes out of
the system. The best way to specify output is to prepare some output forms and
required format for displaying result. The best person to judge an output form is the end
user of the system i.e. the one who uses the software to his benefit.
3. Specifying Input Requirements :
After having specified the outputs, the input and data required for the system need to be
specified as well. One needs to identify the list of inputs required and the source of data.
For example, in a simple program to keep student‟s record, the inputs could be the

48
student‟s name, address, roll-numbers, etc. The sources could be the students
themselves.
4. Specifying Processing Requirements :
When output and inputs are specified, we need to specify process that converts
specified inputs into desired output.
5. Evaluating the Feasibility :
After the successful completion of all the above four steps one needs to see whether
the things accomplished so far in the process of problem solving are practical and
feasible. To replace an existing system one needs to determine how the potential
improvements out performs existing system or other similar system.
6. Problem Analysis Documentation
Before concluding the program analysis stage, it is best to record whatever has been
done so far in the first phase of program development. The record should contain the
statement of program objectives, output and input specifications, processing
requirements and feasibility.
Program Design
The second stage in software development or problem solving using computer cycle is
program design. This stage consists of preparing algorithms, flowcharts and
pseudocodes.
i) Algorithms (Characteristics, Guidelines & Advantages)
An algorithm is an effective step-by-step procedure for solving a problem in a finite
number of steps. In other words, it is a finite set of well-defined instructions or step-by-
step description of the procedure written in human readable language for solving a
given problem. An algorithm itself is division of a problem into small steps which are
ordered in sequence and easily understandable. Algorithms are very important to the
way computers process information, because a computer program is basically an
algorithm that tells computer what specific tasks to perform in what specific order to
accomplish a specific task.

An algorithm must possess the following characteristics:


1. Finiteness: An algorithm should have finite number of steps and it should end
after a finite time.
2. Input: An algorithm may have many inputs or no inputs at all.
3. Output: It should result at least one output.
4. Definiteness: Each step must be clear, well-defined and precise. There should
be no any ambiguity.
5. Effectiveness: Each step must be simple and should take a finite amount of
time.

49
Guidelines for Developing an Algorithm
1. An algorithm will be enclosed by START (or BEGIN) and STOP (or END).
2. To accept data from user, generally used statements are INPUT, READ, GET or
OBTAIN.
3. To display result or any message, generally used statements are PRINT,
DISPLAY, or WRITE.
4. Generally, COMPUTE or CALCULATE is used while describing mathematical
expressions and based on situation relevant operators can be used.

Example of an Algorithm
Algorithm : Calculation of Simple Interest
Step 1: Start
Step 2: Read principal (P), time (T) and rate (R)
Step 3: Calculate I = P*T*R/100
Step 4: Print I as Interest
Step 5: Stop

Advantages of an Algorithm
1. Effective Communication: Since algorithm is written in English like language, it
is simple to understand step-by-step solution of the problems.
2. Easy Debugging: Well-designed algorithm makes debugging easy so that we
can identify logical error in the program.
3. Easy and Efficient Coding: An algorithm acts as a blueprint of a program and
helps during program development.
4. Independent of Programming Language: An algorithm is independent of
programming languages and can be easily coded using any high level language.
Disadvantages of an algorithm
1. Developing algorithm for complex problems would be time consuming and
difficult to understand.
2. Understanding complex logic through algorithms can be very difficult.
ii) Flowcharts (Guidelines, Advantages & Disadvantages)
Flowchart is basically a pictorial or diagrammatic representation of an algorithm using
standard symbols.
In other words, flowchart is a graphical representation that explains the sequence of
operations to be performed in order to solve a problem under consideration.
Standard Flowchart Symbols
To express different operations in the flowchart various standard symbols are used. All
symbols are connected among themselves in order to show the flow of information and

50
processing. Different symbols as prescribed by American National Standard Institute
(ANSI) which are frequently required while drawing flowchart are tabulated below:

Figure: Flowchart Symbols


Guidelines for Preparing Flowchart
1. Standard symbols should be used while drawing flowchart.
2. Ensure that flowchart has START (or BEGIN) and STOP (or END).
3. Flowchart should be neat, clean and easy to follow. There should be no
ambiguity.
4. The usual direction of flowchart is from top to bottom or from left to right.
5. The terminal symbol, that is, START/BEGIN or STOP/END should have only one
flow line.
6. Only one flow line should come out from process symbol.
7. Only one flow line should enter a decision symbol, but two or three flow-lines,
one for each possible answer, can leave the decision symbol.
51
8. If the flowchart is lengthy and complex connector symbol should be used to
reduce the number of flow lines.
9. Avoid intersection of flow lines.
10. Use annotation symbol to describe steps more clearly.

Example of Flowchart
Flowchart example for calculating simple interest is shown below:

Figure: Flowchart for calculating simple interest

Advantages of Flowchart
1. Effective Communication : Flowcharts are better way of communicating the
logic of the system.
2. Effective Analysis: Using flowchart, problem can be analyzed more efficiently.
3. Easy Debugging and Efficient Testing: The Flowchart helps in debugging and
testing process.
4. Efficient Coding: The flowcharts are very useful during program development
phase.
5. Proper Documentation: Flowcharts serves as a good program documentation,
which is needed for various purposes.
6. Efficient Program Maintenance: Maintenance of operating programs becomes
easy with the help of flowchart.
Disadvantages of Flowchart
1. Complex Logic: For complicated logic, flowchart becomes complex and clumsy.
2. Difficulty in Modifications: If change is required in the logic then flowchart needs
to be redrawn and requires a lot of time.

52
Pseudocodes: Guidelines, Advantages & Disadvantages
Pseudocode is structured English for describing algorithms concisely. It is made up of
two words, namely, pseudo meaning imitation and code meaning instructions. As the
name suggests, pseudocode does not obey the syntax rules of any particular
programming language i.e. it is not a real programming code. It allows the designer to
focus on main logic without being distracted by programming languages syntax.

Guidelines for Preparing Pseudocode


1. Pseudocode will be enclosed by START (or BEGIN) and STOP (or END).
2. Pseudocode should be concise so ignore unnecessary details.
3. To accept data from user, generally used statements are INPUT, READ, GET or
OBTAIN.
4. To display result or any message, generally used statements are PRINT,
DISPLAY, or WRITE.
5. Generally used keywords are capitalized while preparing pseudocode.

Example of Pseudocode
Pseudocode: Calculation of Simple Interest
Step 1: START
Step 2: READ P, T, R
Step 3: I = P*T*R/100
Step 4: PRINT I
Step 5: STOP
Advantages of Pseudocode
1. It allows the designer to focus on main logic without being distracted by
programming languages syntax.
2. Since it is language independent, it can be translated to any computer language
code.
3. It allows designer to express logic in plain natural language.
4. It is easier to write actual code using pseudocode.
5. Unlike algorithms, pseudocodes are concise so pseudocodes are more readable
and easier to modify.
Disadvantages of Pseudocode
1. There are no accepted standards for writing pseudocodes and designer use their
own style while writing pseudocodes.
2. Pseudocode cannot be compiled and executed so its correctness cannot be
verified by using computers.

53
Coding (Programming)
At this stage, process of writing actual program takes place. A coded program is most
popularly referred to as a source code. The coding process can be done in any
language (high level and low level). The actual use of computer takes place in this stage
in which the programmer writes a sequence of instructions ready for execution. Coding
is also known as programming.
Good program possess the following characteristics:
1. Comment clauses in the program help to make the program readable and
understandable by people other than the original programmer.
2. It should be efficient.
3. It must be reliable enough to work under all reasonable conditions to provide a
correct output.
4. It must be able to detect unreasonable error conditions and report them to the
end user or programmer without crashing the system.
5. It should be easy to maintain and support after installation.
Compilation and Execution Process
Generally coding is done in high level language or low level language (assembly
language). For the computer to understand these languages, they must be translated
into machine level language. The translation process is carried out by a
compiler/interpreter (for high level language) or an assembler (for assembly language
program). The machine language code thus created can be saved and run immediately
or later on.
Compilation Process
A source code must go through several steps before it becomes an executable
program. In the first step the source code is checked for any syntax errors. After the
syntax errors are traced out a source file is passed through a compiler which first
translates high level language into object code (A machine code not ready to be
executed). A linker then links the object code with pre-compiled library functions, thus
creating an executable program. This executable program is then loaded into the
memory for execution.

54
General compilation process is shown in Figure below:

Figure: Compilation Process

Debugging and Testing (Error and Types Included)


To understand debugging and testing more intuitively, let‟s first consider different types
of error that occurs while programming.
Error
Error means failure of compilation and execution of the computer program or not getting
expected results after execution.
Debugging and testing are systematic process during program development cycle to
avoid errors in the program.
Different types of error that we encounter while programming are listed below:

55
Types of Error:
1. Syntax Error : Syntax error is a violation of programming rules while writing it. A
syntax error does not allow the code to run. Syntax error can be easily detected
during the compilation process using compiler.
2. Logical Error : Logical error occurs when a programmer has applied incorrect
logic for solving problem or left out a programming procedure. When logical error
occurs program executes but fails to produce a correct result.
3. Run Time Error: Run time error occurs during the execution of program. Stack
overflow, divide by zero, floating point error etc. are examples of runtime error.

Debugging
Debugging is the process of finding errors and removing them from a computer
program; otherwise they will lead to failure of the program.
Testing
Testing is performed to ensure that the completed software package functions or works
according to the expectations defined by the requirements. Testing is generally
performed by testing team which repetitively executes program with intent to find error. .

Major differences between debugging and testing:


Debugging Testing
It is the process of fixing errors. It is the process of finding as many errors
as possible.
Debugging is done during program Testing is done during testing phase which
development phase. comes after development phase
Debugging is done by program developer. Testing is generally carried out by
separate testing team rather than program
developer

Program (Programmer's and User's) Documentation


The program documentation is the process of collecting information about the program.
The documentation process starts from the problem analysis phase to debugging and
testing. There are two types of documentation, they are:
1. Programmer's Documentation
2. User's Documentation

Programmer's Documentation
Programmer‟s documentation contains all the technical details. Without proper
documentation it is very difficult even for the original programmer to update and
maintain the program. A programmer‟s documentation contains the necessary

56
information that a programmer requires to update and maintain the program. This
information includes:
1. Program analysis document, with a concise statement of program‟s objectives,
outputs and processing procedures.
2. Program design documents with appropriate flowcharts and diagrams.
3. Program verification documents for outlining, checking, testing and correction
procedures along with the list of sample data and results.
4. Log used to document future program revision and maintenance activity.

User's Documentation
User documentation is required for the end user who installs and uses the program. It
consists instructions for installation of the program and user manual.

Python Program to demonstrate coding/Problem Solving Stages


Problem Description
Write a Python program that calculates simple interest based on the principal amount,
interest rate, and time period provided.
Problem Solution
1. Take in the values for principal amount, rate and time.
2. Using the formula, compute the simple interest.
3. Print the value for the computed interest.
4. Exit.

Formula to Calculate Simple Interest:


Simple Interest = (P × R × T)/100
Here, P = Principal Amount, R = Rate of Interest and T = Time.
Example:
Find the Simple Interest on Rs. 200 for 5 years at 5% per annum compounded annually.
Solution:
Given, P = 200, R = 5 and T = 5.
Simple Interest (SI) = (P * R * T)/100
SI = (200 * 5 * 5)/100
SI = 5000/100
SI = 50
Hence, the Simple Interest on Rs.200 at the rate of 5% for 5 years is Rs. 50
Program/Source Code
Here is source code of the Python Program to compute simple interest given all the
required values. The program output is also shown below.

57
1 principal=float(input("Enter the principle amount:"))
2 time=int(input("Enter the time(years):"))
3 rate=float(input("Enter the rate:"))
4 simple_interest=(principle*time*rate)/100
5 print("The simple interest is:",simple_interest)

Ms-word version
principle=float(input("Enter the principle amount:"))
time=int(input("Enter the time(years):"))
rate=float(input("Enter the rate:"))
simple_interest=(principle*time*rate)/100
print("The simple interest is:",simple_interest)

Program Explanation
1. User must enter the values for the principal amount, rate and time.
2. Calculate the simple interest using the formula: (principal*time*rate)/100
3. Print the calculated simple interest.
Time Complexity: O(1)
The time complexity of the given program is O(1) because the execution time is
constant and does not depend on the input size.
Space Complexity: O(1)
The space complexity of the program is O(1) as well because the amount of memory
used by the program remains constant regardless of the input size.
Runtime Test Cases
Testcase 1: In this case, enter P=200, R=5, and T=5 as the parameters to calculate
simple interest.
Enter the principle amount:200
Enter the time(years):5
Enter the rate:5.0
The simple interest is: 50.0
Testcase 2: In this case, enter P=70000, R=4, and T=1 as the parameters to calculate
simple interest.
Enter the principle amount: 70000
Enter the time(years):1
Enter the rate:4.0
The simple interest is: 2800.0

58
Python Literals
Python Literals can be defined as data that is given in a variable or constant.
Python supports the following literals:
1. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single
as well as double quotes to create a string.
Example:
1. "Aman" , '12345'
Types of Strings:
There are two types of Strings supported in Python:
a) Single-line String- Strings that are terminated within a single-line are known as
Single line Strings.
Example:
1. text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple
lines string.
There are two ways to create multiline strings:
1) Adding black slash at the end of each line.
Example:
1. text1='hello\
2. user'
3. print(text1)
'hellouser'
2) Using triple quotation marks:-
Example:
1. str2='''''welcome
2. to
3. SSSIT'''
4. print str2
Output:
welcome
to
SSSIT
II. Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to the following four
different numerical types.

59
Int(signed integers) Long float(floating point) Complex
(long integers) (complex)

Numbers( can be both Integers of unlimited Real numbers with both In the form of a+bj
positive and negative) size followed by integer and fractional where a forms the
with no fractional lowercase or part eg: -26.2 real part and b
part.eg: 100 uppercase L eg: forms the imaginary
87032845L part of the complex
number. eg: 3.14j

Example - Numeric Literals


1. x = 0b10100 #Binary Literals
2. y = 100 #Decimal Literal
3. z = 0o215 #Octal Literal
4. u = 0x12d #Hexadecimal Literal
5.
6. #Float Literal
7. float_1 = 100.5
8. float_2 = 1.5e2
9.
10. #Complex Literal
11. a = 5+3.14j
12.
13. print(x, y, z, u)
14. print(float_1, float_2)
15. print(a, a.imag, a.real)
Output:
20 100 141 301
100.5 150.0
(5+3.14j) 3.14 5.0

III. Boolean literals:


A Boolean literal can have any of the two values: True or False.
Example - Boolean Literals
1. x = (1 == True)
2. y = (2 == False)
3. z = (3 == True)
4. a = True + 10

60
5. b = False + 10
6.
7. print("x is", x)
8. print("y is", y)
9. print("z is", z)
10. print("a:", a)
11. print("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
IV. Special literals.
Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for the end of lists
in Python.
Example - Special Literals
1. val1=10
2. val2=None
3. print(val1)
4. print(val2)
Output:
10
None
V. Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals, Dict
literals, and Set literals. We will see that later as we progress.

Python as interpreted Language


Python is an interpreted programming language, this means that as a developer you
write Python (.py) files in a text editor like note pad and then put those files into the
python interpreter to be executed.
The way to run a python file is like this on the command line:
Execute Python Syntax
Python syntax can be executed by writing directly in the Command Line:
>>> print("Hello, World!")
Hello, World!

61
or by creating a python file on the server, using the .py file extension, and running it in
the Command Line
Congratulations, you have written and executed your first Python program.
Whenever you are done in the python command line, you can simply type the following
to quit the python command line interface:
exit()
Then press enter key on the key board
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only,
the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!") # there is indentation before the word print
output: Five is greater than two!
CODE IT OUT »
Python will give you an error if you skip the indentation:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!") #the if & print are on the same line without indentation.
output: File "demo_indentation_test.py", line 2
print("Five is greater than two!")
^
IndentationError: expected an indented block
CODE IT OUT »
The number of spaces is up to you as a programmer, the most common use is four, but
it has to be at least one space.
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
output:
Five is greater than two!
Five is greater than two!
CODE IT OUT »

62
You have to use the same number of spaces in the same block of code, otherwise
Python will give you an error like the one below:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
output:
File "demo_indentation2_error.py", line 3
print("Five is greater than two!")
^
IndentationError: unexpected indent
NB: If you run the program in command line without indentation, see your result below:
>>> if 10 > 2:
... print("it is true") # no indentation for Python reserve word print
File "<stdin>", line 2
print("it is true")
^
IndentationError: expected an indented block after 'if' statement on line 1
CODE IT OUT »

Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with #, and Python will render the rest of the line as a comment:
Example

Comments in Python:

#This is a comment.
print("Hello, World!")
Output: Hello, World!
CODE IT OUT »
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:
Example

63
#This is a comment
print("What is the name of you HOD!")
Output: What is the name of you HOD!
CODE IT OUT »
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example
print("My HOD‟s name is Dr. Computer!") #This is a comment
output: My HOD‟s name is Dr. Computer!
CODE IT OUT »
A comment does not have to be text that explains the code, it can also be used to
prevent Python from executing code:
Example
#print("Hello, World!")
print("DOU, FACULTY OF COMPUTING!")
Output: DOU, FACULTY OF COMPUTING!

Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("What is you name: Juliet Okafor Ebube!")
Output: What is you name: Juliet Okafor Ebube!
CODE IT OUT »
or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to a variable, you can add a
multiline string (triple quotes) in your code, and place your comment inside it:
Example

"""
Dannis Osadebay
University Students
are doing very well
"""
print("Faculty of Computing is leading in DOU!")
Output: Faculty of Computing is leading in DOU!

CODE IT OUT »

64
As long as the string is not assigned to a variable, Python will read the code, but then
ignore it, and you have made a multiline comment.

Variables
Python Variables
In Python, variables are created when you assign a value to it:
Variables are containers for storing data values.
Let‟s now create variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.

Example
x=5
y = "Hello, World!"
print(x)
print(y)
output:
5
Hello, World!
CODE IT OUT »
NB: Python has no command for declaring a variable.

Example
a = 100
b = "Charles"
print(a)
print(b)
output:
100
Charles
CODE IT OUT »

Variables do not need to be declared with any particular type, and can even change
type after they have been set.
Example
x = 200 # x is of type int
x = "DOU" # x is now of type str
print(x)
output: DOU
CODE IT OUT »

65
String variables
Single or Double Quotes?
String variables can be declared either by using single or double quotes:
Example
x = "DOU….Dennis Osadebay University"
# is the same as
y = ' DOU….Dennis Osadebay University '
print(x,y)
output: DOU….Dennis Osadebay University DOU….Dennis Osadebay University
CODE IT OUT »

Case-Sensitivity
Variable names are case-sensitive.
Example
This will create two variables:
a = 35
A = "Female Hostel"
#A will not overwrite a
print(a , A)
output: 35 Female Hostel
CODE IT OUT »

Variable Names Description


A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for Naming Python variables:
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)
Example
Valid variable names:
myvar = "DOU"
my_var = " DOU "
_my_var = " DOU "
myVar = " DOU "

66
MYVAR = " DOU "
myvar2 = " DOU "
CODE IT OUT »
Example
Invalid variable names:
2myvar = "John"
my-var = "John"
my var = "John"
#This example will produce an error in the result
Output:
Traceback (most recent call last):
File "/usr/lib/python3.7/py_compile.py", line 143, in compile
_optimize=optimize)
File "<frozen importlib._bootstrap_external>", line 791, in source_to_code
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "./prog.py", line 1
2myvar = "John"
^
SyntaxError: invalid syntax
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python3.7/py_compile.py", line 147, in compile
raise py_exc
py_compile.PyCompileError: File "./prog.py", line 1
2myvar = "John"
^
SyntaxError: invalid syntax
CODE IT OUT »
Note : Variable names are case-sensitive

Multi Words Variable Names


Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "Okoro"

Pascal Case
Each word starts with a capital letter:
MyVariableName = "Okoro"

67
Snake Case
Each word is separated by an underscore character:
my_variable_name = "Okoro"

Python Variables - Assign Multiple Values


Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example
a, b, c = "Orange", "Banana", "Mango"
print(a , b , c)
output: Orange Banana Mango

CODE IT OUT »

Note: Make sure the number of variables matches the number of values, or else you will get an
error.

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:
Example
a = b = c = "Eba & fufu"
print(a , b , c)
output: Eba & fufu Eba & fufu Eba & fufu
CODE IT OUT »

Python - Output Variables


Output Variables
The Python print() function is often used to output variables.
Example
a = "DOU is a first class university"
print(a)
output: DOU is a first class university
CODE IT OUT »

In the print() function, you output multiple variables, separated by a comma:


Example
a = "DOU"
b = "is"
c = "a good school"
print(a, b, c)
output: DOU is a good school

68
CODE IT OUT »

You can also use the + operator to output multiple variables:


Example
x = "DOU "
y = "is "
z = "a good school, that is why I chose to study here"
print(x + y + z)
output: DOU is a good school, that is why I chose to study here
CODE IT OUT »

Notice the space character after "DOU " and "is ", without the “+” result would be "DOUis a good
school, that is why I chose to study here ".
For numbers, the + character works as a mathematical operator:
Example
x = 15
y = 25
print(x + y)
output: 40
CODE IT OUT »

In the print() function, when you try to combine a string and a number with the + operator,
Python will give you an error:
Example
a = 19
b = "DOU"
print(a + b)
output:
Traceback (most recent call last):
File "./prog.py", line 3, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

CODE IT OUT »

The best way to output multiple variables in the print() function is to separate them with
commas, which even support different data types:
Example
a = 19
b = "Coka Cola Village DOU Asaba"
print(a , b)
output: 19 Coka Cola Village DOU Asaba

69
CODE IT OUT »

Python - Global Variables


Global Variables
Variables that are created outside of a function (as in all of the examples above) are
known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "I have cheched and confirm that it is true"

def myfunc():
print("DOU is a standard University in Africa. " + x)
myfunc()
output: DOU is a standard University in Africa. I have cheched and confirm that it is true
CODE IT OUT »

If you create a variable with the same name inside a function, this variable will be local,
and can only be used inside the function. The global variable with the same name will
remain as it was, global and with the original value.
Example
Create a variable inside a function, with the same name as the global variable

a = "Dannis Osadebay University"


def myfunc():
a = "SCHOOL"
print("Dennis Osadebay is " + a)

myfunc()

print("DOU means " + a)


output:
Dennis Osadebay is SCHOOL
DOU means Dannis Osadebay University
CODE IT OUT »

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can
only be used inside that function.
To create a global variable inside a function, you can use the global keyword.

70
Example
If you use the global keyword, the variable belongs to the global scope:

def myfunc():
global b

b = "important"

myfunc()

print("My guy eating good food is very" + b)


output: My guy eating good food is very important
CODE IT OUT »

Also, use the global keyword if you want to change a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using
the global keyword:

c = "Good"

def myfunc():
global c
c = "important"

myfunc()

print("Food is " + c)
output: Food is important

CODE IT OUT »

Python Numbers
There are three numeric types in Python:
 int
 float
 complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 2 + 1j # complex

71
To verify object type in Python, use the type() function:
Example
x = 1 # int
y = 2.8 # float
z = 2 + 1j # complex
print(type(x), type(y), type(z))
output: <class 'int'> <class 'float'> <class 'complex'>
CODE IT OUT »

Integer
Int, or integer, is a positive or negative whole number without decimals and has an
unlimited length.
Example
Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x), type(y), type(z))
output: <class 'int'> <class 'int'> <class 'int'>
CODE IT OUT »

Float
Float, or "floating point number" is a positive or negative number containing one or more
decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x), type(y), type(z))
output: <class 'float'> <class 'float'> <class 'float'>
CODE IT OUT »

Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x), type(y), type(z))
72
output: <class 'float'> <class 'float'> <class 'float'>
CODE IT OUT »
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x), type(y), type(z))
output: <class 'complex'> <class 'complex'> <class 'complex'>
CODE IT OUT »

Type Conversion
You can convert from one number type to another with the int(), float(),
and complex() methods:
Example
Convert from one number type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)

#convert from int to complex:


c = complex(x)

print(a , b , c)
print(type(a), type(b), type(c))
output:
1.0 2 (1+0j)
<class 'float'> <class 'int'> <class 'complex'>
CODE IT OUT »
Note: You cannot convert complex numbers into another number type.

73
Python Casting
Specifying a Variable Type
There are times when you want to specify a type on a variable. This can be done with
casting. Casting, also known as type conversion, is a process that converts a variable's
data type into another data type. These conversions can be implicit (automatically
interpreted) or explicit (using built-in functions). Python is an object-orientated language,
and as such it uses classes to define data types, including its primitive types. Casting in
python is therefore done using constructor functions:
1. int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (provided the string represents a whole number)
2. float() - constructs a float number from an integer literal, a float literal or a string literal
(provided the string represents a float or an integer)
3. str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals

74
Implicit Type Conversion in Python
In this, method, Python converts the data type into another data type automatically. Users
don‟t have to involve in this process.
Python program to demonstrate
# implicit type Casting
# Python automatically converts
# a to int
a=7
print(type(a))
output: <class 'int'>

# Python automatically converts


# b to float
b = 3.0
print(type(b))
output: <class 'float'>

# Python automatically converts


# c to float as it is a float addition
a=7
b = 3.0
c=a+b
print(c)
print(type(c))

output:
10.0
<class 'float'>
# Python automatically converts
# d to float as it is a float multiplication
a=7
b = 3.0

d=a*b
print(d)
print(type(d))
Output:
21.0

75
<class 'float'>

Type Casting in Python ---- Examples


Mainly, type casting can be done with these data type functions:
1. Int(): Python Int() function take float or string as an argument and returns int type object.
2. float(): Python float() function take int or string as an argument and return float type object.
3. str(): Python str() function takes float or int as an argument and returns string type object.

Python Convert Int to Float


Here, we are Converting Int to Float in Python with the float() function.

# Python program to demonstrate


# type Casting
# int variable
a=5
# typecast to float
n = float(a)

print(n)
print(type(n))

Output:
5.0
<class 'float'>

Python Convert Float to Int


Here, we are Converting Float to int data type in Python with int() function.

# Python program to demonstrate


# type Casting
# int variable
a = 5.9
# typecast to int
n = int(a)
print(n)
print(type(n))

Output:
5
<class 'int'>

76
Python Convert int to String
Here, we are Converting int to String datatype in Python with str() function.

# Python program to demonstrate


# type Casting
# int variable
a=5
# typecast to str
n = str(a)
print(n)
print(type(n))

Output:
5
<class 'str'>

Python Convert String to float


Here, we are casting string data type into float data type with float() function.

# Python program to demonstrate


# type Casting
# string variable
a = "5.9"
# typecast to float
n = float(a)
print(n)
print(type(n))

Output:
5.9
<class 'float'>

Python Convert string to int


Here, we are Converting string to int data type in Python with int() function. If the given
string is not number, then it will throw an error.

# string variable
a = "5"
b = 't'
# typecast to int

77
n = int(a)
print(n)
print(type(n))
print(int(b))
print(type(b))

Output:
5
<class 'int'>
ValueError Traceback (most recent call last)
print(n)
print(type(n))
--->print(int(b))
print(type(b))

ValueError: invalid literal for int() with base 10: 't'

Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
output:
Hello
Hello
CODE IT OUT »

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign
and the string:
Example
a = "Hello"
print(a)
output: Hello

78
CODE IT OUT »

Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """This DOU is a very
good school
our lecturers are trying . they give very good
course materials"""
[

print(a)
Output:
This DOU is a very
good school
our lecturers are trying . they give very good
course materials
CODE IT OUT »

Or three single quotes:


Example
a = ''' This DOU is a very
good school
our lecturers are trying . they give very good
course materials.'''
print(a)

output:
This DOU is a very
good school
our lecturers are trying . they give very good
course materials.
CODE IT OUT »
Note: in the result, the line breaks are inserted at the same position as in the code.

Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "banana":

79
for x in "banana":
print(x)
output:
b
a
n
a
n
a
CODE IT OUT »

String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Dennis Osadebay University!"
print(len(a))
output: 27
CODE IT OUT »

Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.
Example
#Check if "Hostel" is present in the following text:
txt = " Male Hostel in DOU!"
print("Hostel" in txt)
output: True
CODE IT OUT »

Use it in an if statement:
Example
#Print only if "Hostel" is present:
txt = " Male Hostel in DOU!"
if "Hostel" in txt:
print("Yes, 'Hostel' is present.")
output: Yes, 'Hostel' is present.
CODE IT OUT »

80
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
Example
Check if "school" is NOT present in the following text:
txt = "Our vice chancellor is trying to build DOU!"
print("school" not in txt)
output: True
CODE IT OUT »

Use it in an if statement:
Example
print only if "school" is NOT present:
txt = " Our vice chancellor is trying to build DOU!"
if "school" not in txt:
print("No, 'school' is NOT present.")
output: No, 'school' is NOT present.
CODE IT OUT »

Slicing Strings
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the
string.
Example
Get the characters from position 2 to position 5 (not included):
z = " Faculty of Computing DOU!"
print(z[2:5])
output: acu

CODE IT OUT »

Note: The first character has index 0.

Slice from the start


By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
z = " Faculty of Computing DOU!"
print(z[:5])
output: Facu
CODE IT OUT »
81
Slice To the End
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = " Faculty of Computing DOU!"
print(b[2:])
output: aculty of Computing DOU!
CODE IT OUT »

Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
output: orl
CODE IT OUT »

Modify Strings
Python has a set of built-in methods that you can use on strings.

Upper Case
Example
The upper() method returns the string in upper case:
z = "Faculty of Computing DOU!"
print(z.upper())
output: FACULTY OF COMPUTING DOU!
CODE IT OUT »

Lower Case
Example
The lower() method returns the string in lower case:
z = "Faculty of Computing DOU!"
print(z.lower())
output: faculty of computing dou!
CODE IT OUT »

Remove Whitespace (blank space or gap)

82
Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
x = " Faculty of Computing DOU! "
print(x.strip()) # returns "Faculty of Computing DOU!"
output: Faculty of Computing DOU!
CODE IT OUT »

Replace String
Example
The replace() method replaces a string with another string:
a = "Faculty of Computing DOU!"
print(a.replace("Faculty", "School"))
output: School of Computing DOU!
CODE IT OUT »

Split String
The split() method returns a list where the text between the specified separator becomes
the list items.
Example
The split() method splits the string into substrings if it finds instances of the separator:
a = "Faculty of Computing, DOU!"
print(a.replace("Faculty", "School"))
print(a.split(",")) # returns [' Faculty of Computing ', ' DOU!']
output:
School of Computing, DOU!
['Faculty of Computing', ' DOU!']
CODE IT OUT »

String Concatenation
To concatenate, or combine two or more strings you can use the + (plus) operator.
Example
Merge variable a with variable b into variable c:
x = "Faculty of "
y = "Computing"
z=x+y
print(z)
output: Faculty of Computing
CODE IT OUT

83
Example
To add a space between them, add a " ":
x = "Faculty of"
y = "Computing"
z=x+""+y
print(z)
output: Faculty of Computing
CODE IT OUT f »

String Format
As we learned earlier in Python Variables, we cannot combine strings and numbers like
this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
output: Traceback (most recent call last):
File "demo_string_format_error.py", line 2, in <module>
txt = "My name is John, I am " + age
TypeError: must be str, not int
CODE IT OUT »

Python Booleans
Booleans represent one of two values: True or False.
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the
Boolean answer:
print(10 > 9)
print(10 == 9)
print(10 < 9)
output:
True
False
False
CODE IT OUT »

When you run a condition in an if statement, Python returns True or False:


Example

84
Print a message based on whether the condition is True or False:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
output: b is not greater than a
CODE IT OUT »

Evaluate Values and Variables


The bool() function allows you to evaluate any value, and give you True or False in return,
Example
Evaluate a string and a number:

Evaluate two variables:


x = "Hello"
y = 15
print(bool(x))
print(bool(y))
output:
True
True
CODE IT OUT »

Most Values are True


Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.
Example
The following will return True:
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
output:
True
True
True

85
CODE IT OUT »

Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
CODE IT OUT »

Python divides the operators in the following groups:


 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical
operations:
ASSIGNMENT: RUN CODES BELOW BY SUBSTITUTING THE VARIABLES WITH
VALUES
Operator Name Example DECODE

+ Addition x+y Try it »

- Subtraction x-y Try it »

* Multiplication x*y Try it »

/ Division x/y Try it »

% Modulus x%y Try it »

** Exponentiation x ** y Try it »

// Floor division x // y Try it »

86
Python Assignment Operators
Assignment operators are used to assign values to variables:
ASSIGNMENT: RUN CODES BELOW BY SUBSTITUTING THE VARIABLES WITH
VALUES
Operator Example Same As DECODE

= x=5 x=5 Try it »

+= x += 3 x=x+3 Try it »

-= x -= 3 x=x-3 Try it »

*= x *= 3 x=x*3 Try it »

/= x /= 3 x=x/3 Try it »

%= x %= 3 x=x%3 Try it »

//= x //= 3 x = x // 3 Try it »

**= x **= 3 x = x ** 3 Try it »

&= x &= 3 x=x&3 Try it »

|= x |= 3 x=x|3 Try it »

^= x ^= 3 x=x^3 Try it »

>>= x >>= 3 x = x >> 3 Try it »

<<= x <<= 3 x = x << 3 Try it »

Python Comparison Operators


Comparison operators are used to compare two values:
ASSIGNMENT: RUN CODES BELOW BY SUBSTITUTING THE VARIABLES WITH
VALUES
Operator Name Example DECODE

== Equal x == y Try it »

!= Not equal x != y Try it »

87
> Greater than x>y Try it »

< Less than x<y Try it »

>= Greater than or equal to x >= y Try it »

<= Less than or equal to x <= y Try it »

Python Logical Operators


Logical operators are used to combine conditional statements:
Example:
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
ASSIGNMENT: RUN CODES BELOW BY SUBSTITUTING THE VARIABLES WITH
VALUES
Operator Description Example DECODE

and Returns True if both statements are true x < 5 and x < 10 Try it »

or Returns True if one of the statements is true x < 5 or x < 4 Try it »

not Reverse the result, returns False if the result is not(x < 5 and x < 10) Try it »
true

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have the same content
print(x == y)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True because
x is equal to y
ASSIGNMENT: RUN CODES BELOW BY SUBSTITUTING THE VARIABLES WITH
VALUES
88
Operator Description Example DECODE

is Returns True if both variables are the same object x is y Try it »

is not Returns True if both variables are not the same x is not y Try it »
object

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:
Example:
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
ASSIGNMENT: RUN CODES BELOW BY SUBSTITUTING THE VARIABLES WITH
VALUES
Operator Description Example DECODE

in Returns True if a sequence with the specified value is present x in y Try it »


in the object

not in Returns True if a sequence with the specified value is not x not in y Try it »
present in the object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:
Example:
print(6 & 3)
"""
The & operator compares each bit and set it to 1 if both are 1, otherwise it is set to 0:

6 = 0000000000000110
3 = 0000000000000011
--------------------
2 = 0000000000000010
====================
Decimal numbers and their binary values:
0 = 0000000000000000
1 = 0000000000000001
2 = 0000000000000010

89
3 = 0000000000000011
4 = 0000000000000100
5 = 0000000000000101
6 = 0000000000000110
7 = 0000000000000111
"""
ASSIGNMENT: RUN CODES BELOW BY SUBSTITUTING THE VARIABLES WITH
VALUES
Operator Name Description Example DECODE

& AND Sets each bit to 1 if both bits are 1 x&y Try it »

| OR Sets each bit to 1 if one of two bits is 1 x|y Try it »

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y Try it »

~ NOT Inverts all the bits ~x Try it »

<< Zero fill left shift Shift left by pushing zeros in from the right x << 2 Try it »
and let the leftmost bits fall off

>> Signed right Shift right by pushing copies of the leftmost x >> 2 Try it »
shift bit in from the left, and let the rightmost bits
fall off

Operator Precedence
Operator precedence describes the order in which operations are performed.
Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must
be evaluated first:
print((6 + 3) - (6 + 3))
output: 0
CODE IT OUT »
Example
Multiplication * has higher precedence than addition +, and therefor multiplications are evaluated
before additions:
print(100 + 5 * 3)
output: 115
CODE IT OUT »

90
SEQUENCE OF PRECEDENCE
The precedence order is described in the table below, starting with the highest
precedence at the top:
Operator Description DECODE

() Parentheses Try it »

** Exponentiation Try it »

+x -x ~x Unary plus, unary minus, and bitwise NOT Try it »

* / // % Multiplication, division, floor division, and modulus Try it »

+ - Addition and subtraction Try it »

<< >> Bitwise left and right shifts Try it »

& Bitwise AND Try it »

^ Bitwise XOR Try it »

| Bitwise OR Try it »

== != > >= < <= is is Comparisons, identity, and membership operators Try it »
not in not in

not Logical NOT Try it »

and AND Try it »

or OR Try it »

If two operators have the same precedence, the expression is evaluated from left to
right.
Example
Addition + and subtraction - has the same precedence, and therefor we evaluate the expression
from left to right:
print(5 + 4 - 7 + 3)
output:
CODE IT OUT »

Python Data Types


There are four collection data types in the Python programming language:

91
 List is a collection which is ordered and changeable. Allows duplicate members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No
duplicate members.
 Dictionary is a collection which is ordered** and changeable. No duplicate
members.
*Set items are unchangeable, but you can remove and/or add items whenever you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security.

Python Lists
mylist = ["apple", "banana", "cherry"]
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the
other three are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example

Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
output: ['apple', 'banana', 'cherry']
CODE IT OUT »

List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order
of the items will not change.

92
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
output: ['apple', 'banana', 'cherry', 'apple', 'cherry']
CODE IT OUT »

List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
output: 3
CODE IT OUT »

List Items - Data Types


List items can be of any data type:
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
print(list1, list2, list3)
output: ['apple', 'banana', 'cherry'] [1, 5, 7, 9, 3] [True, False, False]
CODE IT OUT »

A list can contain different data types:


Example
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
print(list1)
output: ['abc', 34, True, 40, 'male']
CODE IT OUT »

93
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
output: <class 'list'>
ODE IT OUT »

Python - Access List Items


Access Items
List items are indexed and you can access them by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
output: banana
CODE IT OUT »
Note: The first item has index 0.

Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
output: cherry
CODE IT OUT »

Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the
range.
When specifying a range, the return value will be a new list with the specified items.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
output: ['cherry', 'orange', 'kiwi']
#This will return the items from position 2 to 5.
#Remember that the first item is position 0,

94
#and note that the item in position 5 is NOT included
CODE IT OUT »

Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:

Example
This example returns the items from the beginning to, but NOT including, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
output: ['apple', 'banana', 'cherry', 'orange']
#This will return the items from index 0 to index 4.
#Remember that index 0 is the first item, and index 4 is the fifth item
#Remember that the item in index 4 is NOT included
CODE IT OUT »

By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
output: ['cherry', 'orange', 'kiwi', 'melon', 'mango']
#This will return the items from index 2 to the end.
#Remember that index 0 is the first item, and index 2 is the third
CODE IT OUT »

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list:
Example
This example returns the items from "orange" (-4) to, but NOT including "mango" (-1):
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
output: ['orange', 'kiwi', 'melon']
CODE IT OUT »

#Negative indexing means starting from the end of the list.


#This example returns the items from index -4 (included) to index -1 (excluded)
#Remember that the last item has the index -1,

95
Checking if Item Exists on a list
To determine if a specified item is present in a list use the in keyword:
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list very sweetooo")
output: Yes, 'apple' is in the fruits list very sweetooo
CODE IT OUT »

Change List Items


Change Item Value
To change the value of a specific item, refer to the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
output: ['apple', 'blackcurrant', 'cherry']
CODE IT OUT »

Changing Range of Item Values


To change the value of items within a specific range, define a list with the new values,
and refer to the range of index numbers where you want to insert the new values:
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
output: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
CODE IT OUT »

If you insert more items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example
Change the second value by replacing it with two new values:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
output: ['apple', 'blackcurrant', 'watermelon', 'cherry']

96
CODE IT OUT »
Note: The length of the list will change when the number of items inserted does not match the
number of items replaced.

If you insert less items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example
Change the second and third value by replacing it with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
output: ['apple', 'watermelon']
CODE IT OUT »

Inserting Items on a list


To insert a new list item, without replacing any of the existing values, we can use
the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert "watermelon" as the third item:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
['apple', 'banana', 'watermelon', 'cherry']
CODE IT OUT »
Note: As a result of the example above, the list will now contain 4 items.

Python - Add List Items


Append Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
output: ['apple', 'banana', 'cherry', 'orange']
CODE IT OUT »

Using Insert method


To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:

97
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
output: ['apple', 'orange', 'banana', 'cherry']
CODE IT OUT »
Note: As a result of the examples above, the lists will now contain 4 items.

Extending a List
To append elements from another list to the current list, use the extend() method.
Example
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
CODE IT OUT »
The elements will be added to the end of the list.

Python - Remove List Items


Remove Specified Item
The remove() method removes the specified item.
Example
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
output: ['apple', 'cherry']
CODE IT OUT »

Remove Specified Index


The pop() method removes the specified index.
Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
output: ['apple', 'cherry']
CODE IT OUT »

98
When index is not specified
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
output: ['apple', 'cherry']
CODE IT OUT »

The del keyword also removes the specified index:


Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
output: ['banana', 'cherry']
CODE IT OUT »

The del keyword can also delete the list completely.


Example
Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
output: Traceback (most recent call last):
File "demo_list_del2.py", line 3, in <module>
print(thislist) #this will cause an error because you have succsesfully deleted "thislist".
NameError: name 'thislist' is not defined
CODE IT OUT »

Clear the List


The clear() method empties the list.
The list still remains, but it has no content.
Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
output: [ ]

99
CODE IT OUT »

Python - Loop Lists


Loop Through a List
You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
output:
apple
banana
cherry
CODE IT OUT »

Loop through the Index Numbers


You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
Example
Print all items by referring to their index number:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
output:
apple
banana
cherry
CODE IT OUT »
The iterable created in the example above is [0, 1, 2].

Using a While Loop


You can loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your
way through the list items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
Example
Print all items, using a while loop to go through all the index numbers
thislist = ["apple", "banana", "cherry"]
i=0

100
while i < len(thislist):
print(thislist[i])
i=i+1
output:
apple
banana
cherry
CODE IT OUT »

Looping Using List Comprehension


List Comprehension offers the shortest syntax for looping through lists:
Example
A short hand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
output:
apple
banana
cherry
CODE IT OUT »

Python - List Comprehension


List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a"
in the name.
Without list comprehension you will have to write a for statement with a conditional test
inside:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [ ]

for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
output: ['apple', 'banana', 'mango']
CODE IT OUT »
101
With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]


print(newlist)
output: ['apple', 'banana', 'mango']

The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.

Condition
The condition is like a filter that only accepts the items that valuate to True.
Example
Only accept items that are not "apple":
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"]
print(newlist)
output: ['banana', 'cherry', 'kiwi', 'mango']
CODE IT OUT »

The condition if x != "apple" will return True for all elements other than "apple", making
the new list contain all fruits except "apple".
The condition is optional and can be omitted:
Example
With no if statement:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits]
print(newlist)
output: ['apple', 'banana', 'cherry', 'kiwi', 'mango']
CODE IT OUT »

Python - Sort Lists


Sort List Alphanumerically
List objects have a sort() method that will sort the list alphanumerically, ascending, by
default:
Example

102
Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
output: ['banana', 'kiwi', 'mango', 'orange', 'pineapple']
CODE IT OUT »

Sort the list numerically:


Example
Sort the list numerically:
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
output: [23, 50, 65, 82, 100]
CODE IT OUT »

Sort in Descending order


To sort in descending order, use the keyword argument reverse = True:
Example
Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
output: ['pineapple', 'orange', 'mango', 'kiwi', 'banana']
CODE IT OUT »

Reverse Order
What if you want to reverse the order of a list, regardless of the alphabet?
The reverse() method reverses the current sorting order of the elements.
Example
Reverse the order of the list items:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
output: ['cherry', 'Kiwi', 'Orange', 'banana']
CODE IT OUT »

103
Python - Copy Lists
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
output: ['apple', 'banana', 'cherry']
CODE IT OUT »

Another way to make a copy is to use the built-in method list().


Example
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
output: ['apple', 'banana', 'cherry']
CODE IT OUT »

Python - Join Lists


Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
output:
CODE IT OUT »
Another way to join two lists is by appending all the items from list2 into list1, one by
one:
Example
Append list2 into list1:

104
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
CODE IT OUT »
or you can use the extend() method, where the purpose is to add elements from one list
to another list:
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
output: ['a', 'b', 'c', 1, 2, 3]
CODE IT OUT »

Python Tuples
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other
3 are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
output: ('apple', 'banana', 'cherry')
CODE IT OUT »

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.
Unchangeable

105
Tuples are unchangeable, meaning that we cannot change, add or remove items after
the tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
output: ('apple', 'banana', 'cherry', 'apple', 'cherry')
CODE IT OUT »

Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
output: 3
CODE IT OUT »

Create Tuple with one Item


To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
output: <class 'tuple'>
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
output: <class 'str'>
CODE IT OUT »

Tuple Items - Data Types


Tuple items can be of any data type:
Example
String, int and boolean data types:

106
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1, tuple2, tuple3)
output:
('apple', 'banana', 'cherry') (1, 5, 7, 9, 3) (True, False, False)
CODE IT OUT »

A tuple can contain different data types:


Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
print(tuple1)
output: ('abc', 34, True, 40, 'male')
CODE IT OUT »

From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
output: <class 'tuple'>
CODE IT OUT »

Access Tuple Items


Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:

Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
output: banana
CODE IT OUT »
Note: The first item has index 0.

Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
Example
107
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
output: cherry
CODE IT OUT »

Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the
range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
output: ('cherry', 'orange', 'kiwi')
CODE IT OUT »
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
output: ('apple', 'banana', 'cherry', 'orange')
CODE IT OUT »

By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])
output: ('cherry', 'orange', 'kiwi', 'melon', 'mango')
CODE IT OUT »

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
output: ('orange', 'kiwi', 'melon')

108
CODE IT OUT »
#Negative indexing means starting from the end of the tuple.
#This example returns the items from index -4 (included) to index -1 (excluded)
#Remember that the last item has the index -1,

Checking if Item Exists in a turple


To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple and I love eating itoooo")
output: Yes, 'apple' is in the fruits tuple and I love eating itoooo
CODE IT OUT »

Updating a Tuples
Tuples are unchangeable, meaning that you cannot change, add, or remove items once
the tuple is created.
But there are some workarounds.

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples are unchangeable
or immutable as it is also called.
But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.

Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)
output: ("apple", "kiwi", "cherry")
CODE IT OUT »

Add Items to tuple


Since tuples are immutable, they do not have a built-in append() method, but there are
other ways to add items to a tuple.

109
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it
into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
print(thistuple)
output: ('apple', 'banana', 'cherry', 'orange')
CODE IT OUT »

Add tuple to a tuple.


You are allowed to add tuples to tuples, so if you want to add one item, (or many),
create a new tuple with the item(s), and add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",) # add comma after orange to make it a turple
thistuple += y
print(thistuple)
output: ('apple', 'banana', 'cherry', 'orange')
CODE IT OUT »

Note: When creating a tuple with only one item, remember to include a comma after the item,
otherwise it will not be identified as a tuple.

Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can use the
same workaround as we used for changing and adding tuple items:

Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)
output: ('banana', 'cherry')

110
CODE IT OUT »

otherwise you can delete the tuple completely:


Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
output:
Traceback (most recent call last):
File "demo_tuple_del.py", line 3, in <module>
print(thistuple) #this will raise an error because the tuple no longer exists
NameError: name 'thistuple' is not defined
CODE IT OUT »

Unpack Tuples
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:
Example
Packing a tuple:
fruits = ("apple", "banana", "cherry")

print(fruits)
output: ('apple', 'banana', 'cherry')
CODE IT OUT »

But, in Python, we are also allowed to extract the values back into variables. This is
called "unpacking":
Example
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green, yellow, red)
output: apple banana cherry

CODE IT OUT »

Note: The number of variables must match the number of values in the tuple, if not, you must
use an asterisk to collect the remaining values as a list.

111
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the
variable name and the values will be assigned to the variable as a list:
Example
Assign the rest of the values as a list called "red":
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
output:
apple
banana
['cherry', 'strawberry', 'raspberry']
CODE IT OUT »

If the asterisk is added to another variable name than the last, Python will assign values
to the variable until the number of values left matches the number of variables left.
Example
Add a list of values the "tropic" variable:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
output:
apple
['mango', 'papaya', 'pineapple']
Cherry
CODE IT OUT »

Loop through a Tuple


You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)

112
output:
apple
banana
cherry
CODE IT OUT »

Loop through the Index Numbers


You can also loop through the tuple items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.

Example
Print all items by referring to their index number:
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
output:
apple
banana
cherry
CODE IT OUT »

Using a While Loop


You can loop through the tuple items by using a while loop.
Use the len() function to determine the length of the tuple, then start at 0 and loop your
way through the tuple items by referring to their indexes.
Remember to increase the index by 1 after each iteration.

Example
Print all items, using a while loop to go through all the index numbers:
thistuple = ("apple", "banana", "cherry")
i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1
output:
apple
banana
cherry
CODE IT OUT »
.
Joining Tuples
113
Join Two Tuples
To join two or more tuples you can use the + operator
Example
Join two tuples
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
output: ('a', 'b', 'c', 1, 2, 3)
CODE IT OUT »

Multiplication of Tuples
If you want to multiply the content of a tuple a given number of times, you can use
the * (multiplication) operator:
Example
Multiply the fruits tuple by 2:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
output: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
CODE IT OUT »

Python Sets
*Set items are unchangeable, but you can remove items and add new items.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security.
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
Example
Creating a Set:
thisset = {"apple", "banana", "cherry"}

print(thisset)

114
output: {'apple', 'cherry', 'banana'}
CODE IT OUT »
Note: that set list is unordered, meaning: the items will appear in a random order
Also, you cannot be sure in which order the items will appear.

Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.

Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has
been created.
Once a set is created, you cannot change its items, but you can remove items and add
new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
output: {'banana', 'cherry', 'apple'}
CODE IT OUT »
Note: The values True and 1 are considered the same value in sets, and are treated as
duplicates:

Example
True and 1 is considered the same value:
thisset = {"apple", "banana", "cherry", True, 1, 2}
print(thisset)
output: {True, 2, 'banana', 'cherry', 'apple'}
CODE IT OUT »

Getting the Length of a Set


To determine how many items a set has, use the len() function.

115
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
output: 3
CODE IT OUT »

Set Items - Data Types


Set items can be of any data type:
Example
String, int and boolean data types:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1, set2, set3)
output:
{'banana', 'apple', 'cherry'} {1, 3, 5, 7, 9} {False, True}
CODE IT OUT »

A set can contain different data types:


Example
A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}


print(set1)
output: {True, 34, 40, 'male', 'abc'}
CODE IT OUT »

From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
Example
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))
output: <class 'set'>
CODE IT OUT »

Accessing Set Items


You cannot access items in a set by referring to an index or a key.

116
But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
output:
apple
banana
cherry
CODE IT OUT »
Example
Check if "banana" is present in the set:

thisset = {"apple", "banana", "cherry"}


print("banana" in thisset)
output: True
CODE IT OUT »

Change Items
Once a set is created, you cannot change its items, but you can add new items.

Adding Items to Set


Add Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.
Example
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
output: {'banana', 'cherry', 'orange', 'apple'}
CODE IT OUT »

Add Sets
To add items from another set into the current set, use the update() method.
Example
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}

117
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
output: {'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}
CODE IT OUT »

Removing Set Items


To remove an item in a set, use the remove(), or the discard() method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
output: {'apple', 'cherry'}
CODE IT OUT »
Note: If the item to remove does not exist, remove() will raise an error.
Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
output: {'cherry', 'apple'}
CODE IT OUT »
Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop() method to remove an item, but this method will remove a
random item, so you cannot be sure what item that gets removed.
The return value of the pop() method is the removed item.
Example
Remove a random item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
output:
banana
{'cherry', 'apple'}
CODE IT OUT »

118
Note: Sets are unordered, so when using the pop() method, you do not know which item that
gets removed.

Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
output: set()
CODE IT OUT »

Example
The del keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset) # this will raise an error because the set no longer exists
output: Traceback (most recent call last):
File "demo_set_del.py", line 5, in <module>
print(thisset) #this will raise an error because the set no longer exists
NameError: name 'thisset' is not defined
CODE IT OUT »

Loop Sets
You can loop through the set items by using a for loop:
Example
Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x)
output:
apple
banana
cherry
CODE IT OUT »

Python - Join Sets


Joining Two Sets
There are several ways to join two or more sets in Python.

119
You can use the union() method that returns a new set containing all items from both
sets, or the update() method that inserts all the items from one set into another:
Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union (set2)
print(set3)
output: {1, 'c', 3, 2, 'a', 'b'}
CODE IT OUT »
Example
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
output: {'b', 1, 'c', 2, 'a', 3}
CODE IT OUT »
Note: Both union() and update() will exclude any duplicate items.

Keep ONLY the Duplicates


The intersection_update() method will keep only the items that are present in both sets.
Example
Keep the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)

print(x)
output: {'apple'}
CODE IT OUT »
The intersection() method will return a new set, that only contains the items that are
present in both sets.
Example
Return a set that contains the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}

120
z = x.intersection(y)
print(z)
output: {'apple'}
CODE IT OUT »

Keep All, But NOT the Duplicates


The symmetric_difference_update() method will keep only the elements that are NOT
present in both sets.
Example
Keep the items that are not present in both sets:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.symmetric_difference_update(y)

print(x)
output: {'google', 'banana', 'microsoft', 'cherry'}
CODE IT OUT »
The symmetric_difference() method will return a new set, that contains only the elements
that are NOT present in both sets.
Example
Return a set that contains all items from both sets, except items that are present in both:
x = {"apple", "banana", "cherry"}

y = {"google", "microsoft", "apple"}


z = x.symmetric_difference(y)

print(z)
output: {'google', 'banana', 'microsoft', 'cherry'}
CODE IT OUT »
Note: The values True and 1 are considered the same value in sets, and are treated as
duplicates:
Example
True and 1 is considered the same value:
x = {"apple", "banana", "cherry", True}
y = {"google", 1, "apple", 2}

z = x.symmetric_difference(y)
output: {2, 'google', 'cherry', 'banana'}
CODE IT OUT »

121
Python Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Toyota",
"model": "Camry",
"year": 1998
}
print(thisdict)
output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
CODE IT OUT »

Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the
key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
CODE IT OUT »

Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an
item by using an index.

122
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after
the dictionary has been created.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:
thisdict = {
"milk": "powder",
"Type": "pick",
"year": 2022,
"year": 2023
}
print(thisdict)
output: {'milk': 'powder', 'Type': 'pick', 'year': 2023}
CODE IT OUT »

Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary above:
print(len(thisdict))
output: 3
CODE IT OUT »

Dictionary Items - Data Types


The values in dictionary items can be of any data type:
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(thisdict)
output: {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}
CODE IT OUT »

123
Access Dictionary Items
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:
Example
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
x = thisdict["model"]
print(x)
output: Tango
CODE IT OUT »
There is also a method called get() that will give you the same result:
Example
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
x = thisdict.get("model")
print(x)
output: Tango
CODE IT OUT »

Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}

x = thisdict.keys()
print(x)
output: dict_keys(['brand', 'model', 'year'])

124
CODE IT OUT »

The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.
Example
Add a new item to the original dictionary, and see that the keys list gets updated as well:
car = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}

x = car.keys ()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
output: dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])
CODE IT OUT »

Get Values
The values() method will return a list of all the values in the dictionary.
Example
Get a list of the values:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}

x = thisdict.values()

print(x)
output: dict_values(['Ford', 'Tango', 1964])
CODE IT OUT »

The list of the values is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the values list.
Example
Make a change in the original dictionary, and see that the values list gets updated as well:

125
car = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
output:
dict_values(['Ford', 'Tango', 1964])
dict_values(['Ford', 'Tango', 2020])
CODE IT OUT »
Example
Add a new item to the original dictionary, and see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
output:
dict_values(['Ford', 'Tango', 1964])
dict_values(['Ford', 'Tango', 1964, 'red'])
CODE IT OUT »

Get Items
The items() method will return each item in a dictionary, as tuples in a list. It prints both
the keys and the values
Example
Get a list of the key:value pairs
thisdict = {
"brand": "Ford",
"model": "Tango",

126
"year": 1964
}

x = thisdict.items()

print(x)
output: dict_items([('brand', 'Ford'), ('model', 'Tango'), ('year', 1964)])
CODE IT OUT »

The returned list is a view of the items of the dictionary, meaning that any change done
to the dictionary will be reflected in the items list.
Example
Make a change in the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}

x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
output:
dict_items([('brand', 'Ford'), ('model', ' Tango '), ('year', 1964)])
dict_items([('brand', 'Ford'), ('model', ' Tango '), ('year', 2020)])
CODE IT OUT »

Example
Add a new item to the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Tango ",
"year": 1964
}

x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
output:

127
dict_items([('brand', 'Ford'), ('model', ' Tango '), ('year', 1964)])
dict_items([('brand', 'Ford'), ('model', ' Tango '), ('year', 1964), ('color', 'red')])
CODE IT OUT »

Check if Key Exists


To determine if a specified key is present in a dictionary use the “in” keyword:
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": " Tango",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
output: Yes, 'model' is one of the keys in the thisdict dictionary
CODE IT OUT »

Python - Change Dictionary Items


You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
thisdict["year"] = 2018
CODE IT OUT »

Update Dictionary
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
thisdict.update({"year": 2020})
128
output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
CODE IT OUT »

Add Dictionary Items


Adding an item to the dictionary is done by using a new index key and assigning a value
to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
CODE IT OUT »

Remove Dictionary Items


There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
output: {'brand': 'Ford', 'year': 1964}
CODE IT OUT »

Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead):
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}

129
thisdict.popitem()
print(thisdict)
output: {'brand': 'Ford', 'model': 'Tango'}
CODE IT OUT »
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
del thisdict["model"]
print(thisdict)
output: {'brand': 'Ford', 'year': 1964}
CODE IT OUT »
Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Output: Traceback (most recent call last):
File "demo_dictionary_del3.py", line 7, in <module>
print(thisdict) #this will cause an error because "thisdict" no longer exists.
NameError: name 'thisdict' is not defined
CODE IT OUT »
Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
thisdict.clear()
print(thisdict)
output: {}
CODE IT OUT »

130
Loop through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but
there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
for x in thisdict:
print(x)
output:
brand
model
year
CODE IT OUT »

Example
Print all values in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
output:
Ford
Tango
196
CODE IT OUT »
Example
You can also use the values() method to return values of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

131
}
for x in thisdict.values():
print(x)
output:
Ford
Tango
1964
CODE IT OUT »
Example
You can use the keys() method to return the keys of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.keys():
print(x)
output:
brand
model
year
CODE IT OUT »
Example
Loop through both keys and values, by using the items() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)
output:
brand Ford
model Tango
year 1964
CODE IT OUT »

Copy Dictionaries
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

132
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
output: {'brand': 'Ford', 'model': 'Tango', 'year': 1964}
CODE IT OUT »

Another way to make a copy is to use the built-in function dict().


Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Tango",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
output: {'brand': 'Ford', 'model': 'Tango', 'year': 1964}
CODE IT OUT »

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contains three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
133
"year" : 2011
}
}
output: {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}
CODE IT OUT »
Or, if you want to add three dictionaries into a new dictionary:
Example
Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

print(myfamily)
output:
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3':
{'name': 'Linus', 'year': 2011}}
CODE IT OUT »

Control Structures: Conditional Statements


If ... Else
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
 Equals: a == b
 Not Equals: a != b

134
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and
loops.
An "if statement" is written by using the if keyword.
Example
If statement:
Year3 = 300
year4 = 400
if year4 > year3:
print("year4 is greater than year3")
Output: year4 is greater than year3
CODE IT OUT »
In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200
is greater than 33, and so we print to screen that "b is greater than a".

Indentation in if statement
Python relies on indentation (whitespace (gap) at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for this
purpose.
Example
If statement, without indentation (will raise an error):
Year3 = 300
year4 = 400
if year4 > year3:
print("year4 is greater than year3") # you will get an error. The print suppose to be
indented

output:
File "demo_if_error.py", line 4
print("year4 is greater than year3")
^
IndentationError: expected an indented block
CODE IT OUT »

135
elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then
try this condition".
Example
Year3 = 300
year3 = 300
if year3 > year3:
print("year3 is greater than year3")
elif year3 == year3:
print("year3 and year3 are equal")
output: year3 and year3 are equal
CODE IT OUT »
In this example a is equal to b, so the first condition is not true, but the elif condition is
true, so we print to screen that "a and b are equal".

Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
year2 = 200
year1 = 100
if year1 > year2:
print("year1 is greater than year2")
elif year2 == year1:
print("year2 and year1 are equal")
else:
print("year2 is greater than year1")
output: year2 is greater than year1
CODE IT OUT »
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to screen that "a is
greater than b".
You can also have an else without the elif:
Example
year2 = 200
year1 = 100
if year2 > year1:
print("year2 is greater than year1")
else:

136
print("year2 is not greater than year1")
output: year2 is greater than year1
CODE IT OUT »

Short Hand If
If you have only one statement to execute, you can put it on the same line as the if
statement.
Example
One line if statement:
year2 = 200
year1 = 100
if year2 > year1: print("year2 is greater than year1")
output: year2 is greater than year1
CODE IT OUT »

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all
on the same line:
Example
One line if else statement:
year1 = 100
year3 = 300
print("YEAR1") if year1 > year3 else print("YEAR3")
output: YEAR3
CODE IT OUT »
This technique is known as Ternary Operators, or Conditional Expressions.
You can also have multiple else statements on the same line:
Example
One line if else statement, with 3 conditions:
year1 = 100
year1 = 100
print("YEAR1") if year1 > year1 else print("=") if year1 == year1 else print("YEAR1")
output: =
CODE IT OUT »

And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:

137
year2 = 200
year1 = 100
year3 = 300
if year2 > year1 and year3 > year2:
print("Both conditions are True")
output: Both conditions are True
CODE IT OUT »

Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
output: At least one of the conditions is True
CODE IT OUT »

Not
The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:
Example
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
output: a is NOT greater than b
CODE IT OUT »

Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41

if x > 10:
print("DOU passed accreditation test")
if x > 20:

138
print("DOU is accreditated!")
else:
print("but not above 20.")
output:
DOU passed accreditation test
DOU is accreditated!
CODE IT OUT »

The pass Statement


ifstatements cannot be empty, but if for some reasons you have an if statement with no
content, put in the pass statement to avoid getting an error.
Example
a = 33
b = 200

if b > a:
pass
# having an empty if statement like this, would raise an error without the pass statement
CODE IT OUT »

Python Loops
Python has two primitive loop commands:
a) while loops
b) for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1 # i = i + 1
output:
1
2
3
4
5

139
CODE IT OUT »
Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to
define an indexing variable, i, which we set to 1.

The break Statement


With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
output:
1
2
3
CODE IT OUT »

Python for Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary,
a set, or a string).
This is less like the for keyword in other programming languages, and works more like
an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
output:
apple
banana
cherry
CODE IT OUT »
NB: The for loop does not require an indexing variable to set beforehand.

140
The break Statement
With the break statement we can stop the loop before it looped through all the items:
Example
Exit the loop when x is " onwusa paul ":
students = ["john okafor", "onwusa paul", "jerimiah abigirl"]
for x in students:
print(x)
if x == "onwusa paul":
break
output:
john okafor
onwusa paul
CODE IT OUT »

Example
Exit the loop when x is "onwusa paul", but this time the break comes before the print:
students = ["john okafor", "onwusa paul", "jerimiah abigirl"]
for x in students:
if x == "onwusa paul":
break
print(x)
output: john okafor
CODE IT OUT »

The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue
with the next:
Example
Do not print onwusa paul:
students = ["john okafor", "onwusa paul", "jerimiah abigirl"]
for x in students:
if x == "onwusa paul":
continue
print(x)
output:
john okafor
jerimiah abigirl
CODE IT OUT »

141
The range() Function
To loop through a set of code a specified number of times, we can use
the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Example
Using the range() function:
for x in range(3):
print(x)
output:
0
1
2
CODE IT OUT »
Note that range(3) is not the values of 0 to 3, but the values 0 to 2.
The range() function defaults to 0 as a starting value, however it is possible to specify
the starting value by adding a parameter: range(2, 5), which means values from 2 to 5
(but not including 5):
Example
Using the start parameter:
for x in range(2, 5):
print(x)
output:
2
3
4
CODE IT OUT »
The range() function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 15, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 15, 3):
print(x)
output:
2
5
8
11
14
CODE IT OUT »

142
else in for Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Example
Print all numbers from 0 to 3, and print a message when the loop has ended:
for x in range(4):
print(x)
else:
print("Finally finished!")
output:
0
1
2
Finally finished!
CODE IT OUT »
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(4):
if x == 2: break
print(x)
else:
print("Finally finished!")
output:
0
1
CODE IT OUT »

Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every student:
adj = ["smart", "brelliant", "intelligent"]
students = ["john", "dumebi", "onyeka"]
for x in adj:
for y in students:
print(x, y)

143
output:
smart john
smart dumebi
smart onyeka
brelliant john
brelliant dumebi
brelliant onyeka
intelligent john
intelligent dumebi
intelligent onyeka
CODE IT OUT »

The pass Statement


forloops cannot be empty, but if for some reasons you have a for loop with no content,
put in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
# having an empty for loop like this, would raise an error without the pass statement
CODE IT OUT »

Python Functions
A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from DOU")

Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from DOU")

my_function()
output: Hello from DOU
CODE IT OUT »

144
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full
name:
Example
def my_function(fname):
print(fname + " Okafor")
my_function("Julius")
my_function("Tobechukwu")
my_function("Emmanuel")
output:
Julius Okafor
Tobechukwu Okafor
Emmanuel Okafor
CODE IT OUT »
Arguments are often shortened to args in Python documentations.

Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are
passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning
that if your function expects 2 arguments, you have to call the function with 2
arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Julius", "Okafor")
output: Julius Okafor

145
CODE IT OUT »
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Julius")
output:
Traceback (most recent call last):
File "./prog.py", line 4, in <module>
TypeError: my_function() missing 1 required positional argument: 'lname'
CODE IT OUT »

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function, add
a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items
accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Julius", "Tobechukwu", "Emmanuel")


output: The youngest child is Emmanuel
CODE IT OUT »
Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Julius", child2 = "Tobechukwu", child3 = "Emmanuel")
output: The youngest child is Emmanuel
CODE IT OUT »
The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

146
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Example
def my_function(state = "Delta"):
print("I am from " + state)

my_function("Edo")
my_function("Kogi")
my_function()
my_function("Lagos")
output:
I am from Edo
I am from Kogi
I am from Delta
I am from Lagos
CODE IT OUT »

Passing a List as an Argument


You can send any data type of argument to a function (string, number, list, dictionary
etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
output:
apple
banana
cherry
CODE IT OUT »

Return Values
To let a function return a value, use the return statement:
Example

147
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
output:
15
25
45
CODE IT OUT »

The pass Statement


definitions cannot be empty, if for some reasons you have a function definition
function
with no content, put in the pass statement to avoid getting an error.
Example
def myfunction():
pass
CODE IT OUT »

Arrays
Note: This page shows you how to use LISTS as ARRAYS, however, to work with
arrays in Python you will have to import a library, like the NumPy library.
Arrays are used to store multiple values in one single variable:
Example
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]
CODE IT OUT »

What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
However, what if you want to loop through the cars and find a specific one? And what if
you had not 3 cars, but 300?

148
The solution is an array!
An array can hold many values under a single name, and you can access the values by
referring to an index number.

Access the Elements of an Array


You refer to an array element by referring to the index number.
Example
Get the value of the first array item:
x = cars[0]
CODE IT OUT »
Example
Modify the value of the first array item:
cars[0] = "Toyota"
CODE IT OUT »

The Length of an Array


Use the len() method to return the length of an array (the number of elements in an
array).
Example
Return the number of elements in the cars array:
x = len(cars)
CODE IT OUT »
Note: The length of an array is always one more than the highest array index.
Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
Example
Print each item in the cars array:
for x in cars:
print(x)
CODE IT OUT »

Adding Array Elements


You can use the append() method to add an element to an array.
Example
Add one more element to the cars array:
cars.append("Honda")
CODE IT OUT »

Removing Array Elements


You can use the pop() method to remove an element from the array.
Example

149
Delete the second element of the cars array:
cars.pop(1)
CODE IT OUT »
You can also use the remove() method to remove an element from the array.
Example
Delete the element that has the value "Volvo":
cars.remove("Volvo")
CODE IT OUT »
Note: The list's remove() method only removes the first occurrence of the specified value.

Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x=5
CODE IT OUT »

Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
CODE IT OUT »

The __init__() Function


The examples above are classes and objects in their simplest form, and are not really
useful in real life applications.
To understand the meaning of classes we have to understand the built-in __init__()
function.
All classes have a function called __init__(), which is always executed when the class is
being initiated.
Use the __init__() function to assign values to object properties, or other operations that
are necessary to do when the object is being created:

150
Example
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
CODE IT OUT »

151
Bibliography

1 G. Polya, How to Solve It: A New Aspect of Mathematical Method, 2nd ed. NJ:
Princeton University Press, 1973.
ISBN 0-691-02356-5
ISBN 0-691-08097-6
https://publish.illinois.edu/augmentedlistening/tutorials/music-processing/tutorial-1-
introduction-to-audio-processing-in-python/
2 Eric Matthes, Python Crash Course: A Hands-On, Project-Based Introduction to
Programming, 2nd ed. San Francisco, CA: No Starch Press, 2016.
ISBN-10: 1-59327-928-0
ISBN-13: 978-1-59327-928-8
https://www.amazon.com/Python-Crash-Course-2nd-Edition/dp/1593279280/
https://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm
4 Ian Sommerville, Software Engineering, 10th ed. UK: Pearson Education, 2016.
ISBN 10: 1-292-09613-6
ISBN 13: 978-1-292-09613-1
5 Diego Lopez Yse, Essential Programming | Control Structures
https://towardsdatascience.com/essential-programming-control-structures-
2e5e73285df4
6 AMZ Publishing, Python Programming for Beginners: The Ultimate Guide for
Beginners to Learn Python Programming, 2021.
7 Paul Barry & David Griffiths, Head First Programming, 1st ed. O‟Reilly, 2009.
ISBN-13: 978-0596802370
ISBN-10: 0596802374
https://www.amazon.com/Head-First-Programming-learners
rogramming/dp/0596802374/ Paul Barry, Head First Python: A Brain-Friendly Guide,
2nd ed. O‟Reilly, 2017.
ISBN-13: 978-1491919538
ISBN-10: 1491919531
https://www.amazon.com/Head-First-Python-Brain-Friendly-Guide/dp/1491919531/
Other Materials
1. YouTube video tutorials
2. Numerous online tutorials

152

You might also like