New Dou-Csc111 Introduction To Programing - Python February 2024
New Dou-Csc111 Introduction To Programing - Python February 2024
using Python
By
Faculty of Computing
Department of Computer Science
Dennis Osadebay Universuty,
(DOU)
Awai, Asaba, Delta State
1
Introduction to Computer Programming I ............................................................................................... 1
Definitions: .................................................................................................................................................... 6
2
Python Keywords ........................................................................................................................................ 45
Compilation Process.................................................................................................................................... 54
Error ............................................................................................................................................................ 55
Types of Error:............................................................................................................................................. 56
3
Comments ................................................................................................................................................... 63
Variables ..................................................................................................................................................... 65
String variables............................................................................................................................................ 66
Integer ........................................................................................................................................................ 72
Float ............................................................................................................................................................ 72
Complex ...................................................................................................................................................... 73
Type Conversion.......................................................................................................................................... 73
Strings ........................................................................................................................................................ 78
4
Python Tuples ......................................................................................................................................... 105
5
Introduction to Programming: Computer in Many Forms
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.
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.
9
The comedy series was creative and well random. It talks about everything. Thus it is
slow and unpredictable, which made it very interesting.
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.
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.
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.}
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
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.
27
--upgrade flag
The --upgrade flag can be used to upgrade an already existing package in your system.
pip install --upgrade <package_name>
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.
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.
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.
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.
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
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
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.
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.
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:
Example of Flowchart
Flowchart example for calculating simple interest is shown below:
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.
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:
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. .
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.
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
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.
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 »
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
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"
CODE IT OUT »
Note: Make sure the number of variables matches the number of values, or else you will get an
error.
68
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 »
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
myfunc()
70
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global b
b = "important"
myfunc()
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)
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'>
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'>
print(n)
print(type(n))
Output:
5.0
<class 'float'>
Output:
5
<class 'int'>
76
Python Convert int to String
Here, we are Converting int to String datatype in Python with str() function.
Output:
5
<class 'str'>
Output:
5.9
<class 'float'>
# 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))
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 »
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 »
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.
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 »
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 »
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 »
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 »
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 »
** Exponentiation 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 += 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 »
== Equal x == y Try it »
87
> Greater than x>y Try it »
and Returns True if both statements are true x < 5 and x < 10 Try it »
not Reverse the result, returns False if the result is not(x < 5 and x < 10) Try it »
true
is not Returns True if both variables are not the same x is not y Try it »
object
not in Returns True if a sequence with the specified value is not x not in y Try it »
present in the object
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 »
^ XOR Sets each bit to 1 if only one of two bits is 1 x^y 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 »
| Bitwise OR Try it »
== != > >= < <= is is Comparisons, identity, and membership operators Try it »
not in not in
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 »
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 »
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 »
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 »
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 »
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 »
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.
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 »
99
CODE IT OUT »
100
while i < len(thislist):
print(thislist[i])
i=i+1
output:
apple
banana
cherry
CODE IT OUT »
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"]
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 »
102
Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
output: ['banana', 'kiwi', 'mango', 'orange', 'pineapple']
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 »
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 »
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 »
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 »
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 »
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,
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.
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 »
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 »
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 »
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 »
112
output:
apple
banana
cherry
CODE IT OUT »
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 »
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.
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 »
115
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
output: 3
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 »
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:
Change Items
Once a set is created, you cannot change its items, but you can add new items.
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 »
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:
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.
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:
120
z = x.intersection(y)
print(z)
output: {'apple'}
CODE IT OUT »
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"}
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.
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 »
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 »
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 »
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 »
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 »
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 »
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 »
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
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.
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 »
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 »
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 »
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 »
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 »
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.
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 »
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