COM 400 Lesson 1 Introduction
COM 400 Lesson 1 Introduction
COMPUTER PROGRAMMING.
(ACS, AST)
BY SAMWEL TARUS
CONTENTS
Basic terms in programming.
Introduction to python programming language.
Basic concepts of Python programming
Basic terms in programming
Data
Program
Software
Code
Database
Structured/Modular programming
Differences:
Modular programing and OOP.
Addition features to each of them.
Improvements on each language.
INTRODUCTION TO PYTHON PROGRAMMING
HISTORY:
Python is a popular HLL programming language created by Guido van Rossum,
and released in 1991 (version 0.9.0).
1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce
Python 2.0 added new features such as list comprehensions, garbage collection
systems.
2008, Python 3.0 (also called "Py3K") released. It was designed to rectify the
fundamental flaw of the language.
Check on newer versions from version 3.0 to the Python 3.11.1
FEATURES OF PYTHON PROGRAMMING LANGUAGE
Easy to Learn and Use
Straight forward syntax, few keywords, similar to English.
No semicolon, curly bracket.
Expressive Language
Perform complex tasks using a few lines of code.
Consider: print("Hello World"). (compare C, C++, JAVA with Python)
Interpreted Language
Python program is executed one line at a time.
Advantage of being interpreted language; makes debugging easy and portable.
Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX,
and Macintosh, etc. (Python is a portable language.)
This enables programmers to develop the s/w for several competing platforms.
Free and Open Source
Freely available for everyone on its official website www.python.org.
Anyone can download its source code without paying.
Object-Oriented Language
Supports concepts of class, objects, inheritance, polymorphism, encapsulation.
OOP aid programmers write re-usable codes hence develop apps faster with
fewer code.
GUI Programming Support
Used for the developing Desktop application.
PyQT5, Tkinter, Kivy are the libraries which are used for developing the web
application.
Extensible
You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Large Standard Library
provides a vast range of libraries for the various fields such as machine
learning, web developer, and also for the scripting.
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.
Integrated
Easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Pto…
Embeddable
Code of the other programming language can be used in the Python source
code.
Python source code can be used in another programming language as well.
Dynamic Memory Allocation
No 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.
Applications / Uses of Python
Desktop Applications
Web Applications
Data Science
Artificial Intelligence
Machine Learning
Scientific Computing
Robotics
Internet of Things
Gaming
Mobile Apps
Data Analysis and Preprocessing
Web Applications
Python provides libraries to handle internet protocols such as HTML and
XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc.
Django, a Python web-framework is used on Instagram.
Frameworks provided by Python:
Django and Pyramid framework(Use for heavy applications)
Flask and Bottle (Micro-framework)
Plone and Django CMS (Advance Content management)
Desktop GUI Applications
Tk GUI library to develop a user interface.
Popular GUI libraries are:
Tkinter or Tk
wxWidgetM
Kivy (used for writing multitouch applications )
PyQt or Pyside
Console-based Application
Applications that run from the command-line or shell.
E.g. as used in DOS, C,
Software Development
Works as a support language and can be used to build control and
management, testing, etc.
SCons is used to build control.
Buildbot and Apache Gumps are used for automated continuous
compilation and testing.
Round or Trac for bug tracking and project management.
Audio or Video-based Applications
Used to create multimedia applications e.g. TimPlayer, cplay, Gstreamer,
Pyglet, and QT Phonon
Scientific and Numeric
Most suitable language for Artificial intelligence or machine learning.
Has / consists of many scientific and mathematical libraries, which makes it
easy to solve complex calculations.
Libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-
learn, etc. are imported to the code.
Popular frameworks of machine libraries are:
SciPy, Scikit-learn, NumPy, Pandas, Matplotlib.
matplotlib for data visualization and NumPy for mathematical operations.
Pandas acts as a wrapper over these libraries, allowing you to access many
of matplotlib's and NumPy's methods with less code.
Scikit-Learn library to implement machine learning models and statistical
modelling.
SciPy is a scientific computation library that uses NumPy underneath
to provide more utility functions for optimization, stats and signal
processing.
Business Applications.
collection of components that provides a business functionality that you can
use internally, externally, or with other business applications.
any application that is important to running your business.
any Product that is designed to be deployed into or to call into an End
Customer’s cloud (not on-premises) implementation of a Defined
Environment as a commercially available packaged and distributed solution
or API Equivalent, excluding Products (i) that are only Power BI extensions
or (ii) when deployed as part of Dynamics 365 Business Central solution. For
clarity, Business Applications include commercially available packages and
distributed PowerApps.
E.g: E-commerce and ERP systems, inventory s/w, communication s/w,
accounting s/w, reservation s/w, HRIS s/w etc.
Enterprise Applications
used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
Why computer language innovation?
Introduction to Python: Language Semantics
Two ways to run a program:
Interactive interpreter prompt
Feature to execute the Python statement one by one at the interactive prompt.
preferable in the case where we are concerned about the output of each line
of program.
Cmd: type print(“Hello word”), print(3+7) etc.
Dis: not suitable to write multiple lines of code.
We cannot write the code every-time on the terminal.
Using a script file (Script Mode Programming)
Write multiple lines code into a file which can be executed later.
For this purpose, open an editor like notepad, create a file named and save it
with .py extension. (open pycharm, create a project folder, then create
python files)
Run also on cmd.
Basic Syntax of Python
Indentation
Adding whitespaces before the statement when it is needed.
Importance:
Proper use of indentation informs Python which statement to be executed to
next.
Defines which statements belong to which block.
Nb:
Improper indentation displays "IndentationError" and interrupt the code.
Com4001.py
Comments:
Explain the code
• Restrict code execution
• To add resources to the code
Not executable
Syntax: #
• E.g. name = “james” #assigning a string value to the name variable
• E.g. sum = 80 #assigning an integer value to a variable
Types of Comment
• Single-Line Comment #single line comment
• Multi-line comment
“””
This is an example
Of multi-line comment
Using triple-quotes
Simple Python Programs
Addition of two numbers
Subtraction of numbers
Area of a circle
Perimeter of a rectangle
Simple interest
Basic Fundamentals of Python:
Tokens:
The tokens can be defined as a punctuator mark, reserved words, and each
word in a statement.
The token is the smallest unit inside the given program.
Except True, False and None, all other keywords must in lower case.
Examples: int continue, break, float, False, else, if, finally, for, return, is, while,
try, global, def, del, and, assert, class, import, await, not, with, lambda, is, in etc
keywordDemo.py
print(name)
print(age)
print(marks)
NB:
Multi_word variable names follows Camel case, Pascal case, or Snake case
convention.
Multiple Assignment
Assigning a value to multiple variables in a single statement.
Two ways to provide multiple assignments:
assigning a single value to multiple variables e.g:
• x=y=z=50
Assigning multiple values to multiple variables: e.g.,
• a,b,c=5,10,15
a,b,c=5,10,15
print(a)
print(b)
print(c)
Types of variables in Python
Local Variable
Variables that declared inside the function and have scope within the
function.
variabletype.py
Global variables
Variables that are used throughout the program, and its scope is in the entire
program.
Variables declared outside the any function
Local variables can be made global by use of the keyword global.
variableType2.py
Delete a variable
Use del keyword.
Syntax:
del <variable_name>
E.g., del x
variableDelete.py
Literals
Defined as data that is given in a variable or constant.
Python supports the following literals:
1. String literals: e.g., “James”, ‘ruth’, ‘34’
Two types of Strings supported in Python:
Single-line String- Strings that are terminated within a single-line. E.g.,
text1='hello'
Python is a dynamically typed language; hence we do not need to define the type
of the variable while declaring it.
Consider: a=5
The variable a holds integer value 5 and we did not define its type. Python
interpreter will automatically interpret variables a as an integer type.
To check the type of the variable used in the program, use type() function. (returns
the type of the variable passed). variableType1.py
Standard data types
A variable can hold different types of values. At one point it can store an integer,
a string etc.
Python provides various standard data types that define the storage method on
each of them. They are:
Numbers
Sequence Type
Boolean
Set
Dictionary
Numbers
Includes integer, float, and complex values.
To store numeric values.
Nb: use:
type() function to know the data-type of the variable.
isinstance() function to check if an object belongs to a particular class.
NUMBERSdEMO.py
Pto…
• Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an integer. Its value belongs to int
• Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc.
• Accurate upto 15 decimal points.
• NUMBERSdEMO.py
Sequence Type
1. String: string1Demo.py
Sequence of characters represented in the quotation marks.
Use single, double, or triple quotes to define a string.
String handling is a straightforward task. (built-in functions and operators to
perform operations in the string). Ie.,
+ is used to concatenate two strings. ("hello"+" python") = “hello python”
* is known as a repetition operator. ("Python" *2 returns 'Python Python’)
2. List: string2Demo.py
Similar to arrays in C / C++.
List can contain data of different types.
Items stored in the list are separated with a comma (,) and enclosed within
square brackets []
Use slice [:] operators to access the data of the list.
Concatenation operator (+) and repetition operator (*) works with the list in the
same way as they were working with the strings.
3. Tuple: TupleDemo.py
Contain collection of items of different data types. (similar to List)
Items are separated with a comma (,) and enclosed in parentheses ().
Read-only data structure. (i.e., size and value of the items cannot be modified).
4. Dictionary: dictDemo.py
An unordered set of a key-value pair of items.
Like an associative array or a hash table where each key stores a specific value.
Key can hold any primitive data type, whereas value is an arbitrary Python object.
Items are separated with the comma (,) and enclosed in the curly braces {}.
5. Boolean: booleanDemo.py
Provides two built-in values, True and False.
These values are used to determine the given statement true or false.
Denoted by the class bool.
True can be represented by any non-zero value or 'T' whereas false can be represented by
the 0 or 'F'.
6. Set: setDemo.py
Unordered collection of the data type.
It is iterable, mutable(can modify after creation), and has unique elements.
Order of the elements is undefined; (may return the changed sequence of the
element)
Created by using a built-in function set(), or a sequence of elements is passed
in the curly braces and separated by the comma.
Nb:
Since everything is an object in Python programming, data types are actually
classes and variables are instances(object) of these classes.
Python Type Conversion
The process of converting data of one type to another.
E.g., converting int data to str.
There are two types of type conversion in Python.
Implicit Conversion - automatic type conversion. typeCoversion1.py
Python converts smaller data types to larger data types to avoid the loss of
data.
Explicit Conversion - manual type conversion
Users convert the data type of an object to required data type.
Use the built-in functions like int(), float(), str(), etc to perform explicit
type conversion.
Also called typecasting because the user casts (changes) the data type of
the objects.
typeConversion2.py
Key Points to Remember about Typecasting
Type Conversion is the conversion of an object from one data type to another
data type.
Implicit Type Conversion is automatically performed by the Python interpreter.
Python avoids the loss of data in Implicit Type Conversion.
Explicit Type Conversion is also called Type Casting, the data types of objects
are converted using predefined functions by the user.
In Type Casting, loss of data may occur as we enforce the object to a specific
data type.