Chapter2 Intro To Python
Chapter2 Intro To Python
Chapter2 Intro To Python
2.1 What is python It is consistently rated as one of the world's most popular
programming language. It has a lower learning curve.
Python is a very popular general-purpose interpreted,
Many schools, Colleges and Universities are teaching
interactive, object-oriented, and high-level programming
Python as their primary programming language.
language. It is dynamically-typed and garbage-collected
programming language. Other good reasons which make Python the top choice of
any programmer include:
It supports multiple programming paradigms, including
Procedural, Object Oriented and Functional programming i). Python is Open Source which means it’s available
paradigms. The Python design philosophy emphasizes at no cost at all.
code readability with the use of significant indentation. ii). It works on different platforms (Windows, Mac,
Linux, Raspberry Pi, etc.).
Python was created by Guido van Rossum between 1985-
iii). Has a less steep learning curve
1990 at the National Research Institute for Mathematics
iv). Its versatile and can be used to create many
and Computer Science in the Netherlands. It was later
different kinds of applications
released in 1991. It’s now maintained by a core
v). Python has powerful development inbuilt libraries
development team at the institute though Guido van
including those for Artificial Intelligence (AI),
Rossum still holds a vital role in directing its progress.
Machine Learning (ML), etc.
Python is derived from many other languages, including vi). Python is Interpreted meaning it’s processed at
ABC, Modula-3, C, C++, Algol-68, Smalltalk, Unix shell and runtime by the interpreter. You therefore do not
other scripting languages. need to compile your program before executing it
2.2 Why python? which makes it faster to execute your programs
1
INTRODUCTION TO PYTHON
2
INTRODUCTION TO PYTHON
Python is used extensively to develop web applications. It help to build the command-line apps. There are also
provides libraries to handle internet protocols such as advanced libraries that can develop independent console
HTML, XML, JSON, Email processing, request. apps.
2.3.2 Desktop GUI Applications o Buildbot and Apache Gumps are used for
automated continuous compilation and testing.
Python provides a GUI library to develop user interfaces.
o Round or Trac for bug tracking and project
Some popular GUI libraries are: management.
o Tkinter or Tk
2.3.5 Scientific and Numeric Applications
o wxWidgetM
Python is the most suitable language for Artificial
o Kivy (used for writing multitouch applications)
intelligence or machine learning. It consists of many
o PyQt or Pyside
scientific and mathematical libraries, which make it easy
2.3.3 Console-based Applications to solve complex calculations.
3
INTRODUCTION TO PYTHON
Python libraries used for data analysis, scientific exposed by python include Gstreamer, Pyglet, QT
computing, and machine learning include SciPy, Scikit- Phonon
learn, NumPy, Panda, Matplotlib, Pandas, , etc.
2.3.8 3D CAD Applications
Python can create a 3D CAD application by using the
following functionalities Fandango (Popular), CAMVOX,
2.3.6 Business Applications
HeeksCNC, AnyCAD, RCAM
E-commerce and ERP are examples of business
applications. These kinds of applications require 2.3.9 Enterprise Applications
extendibility, scalability and readability which Python
provides. Python can be used to create applications that can be
used within an Enterprise or an Organization. Some real-
Oddo is an example of the all-in-one Python-based time applications are OpenERP, Tryton, Picalo, etc.
application which offers a range of business applications.
Python provides the Tryton platform which is used to 2.3.10 Image Processing Applications
develop the business application.
Python contains many libraries that are used to work
2.3.7 Audio or Video-based Applications with images. Some libraries used for image processing
include OpenCV, Pillow and SimpleITK
Python can used to perform multiple tasks and can be
used to create multimedia applications. Example of 2.4 Python versions and IDEs
multimedia applications made by using Python include The most recent major version of Python is Python3,
TimPlayer, cplay, etc. The few multimedia libraries which we shall be using in this module. However, Python
4
INTRODUCTION TO PYTHON
2, although not being updated with anything other than 2.6 Python Identifiers
security updates, is still quite popular. An identifier refers to the name we give to various
programming elements such as variables, functions,
It is possible to write Python in an IDE such as Thonny,
classes, modules, objects, etc.
Pycharm, Netbeans or Eclipse which are particularly
useful when managing larger collections of Python files. Rules for naming identifies in python
Python uses new lines to complete a command, as iv). Class names start with an uppercase letter. All
opposed to other programming languages which often other identifiers start with a lowercase letter.
5
INTRODUCTION TO PYTHON
Python keywords are in lowercase. Some include python Whereas in other programming languages the
reserved words are shown in the table below: indentation in code is for readability only, the indentation
in Python is very important.
Example:
if a>b:
else:
6
INTRODUCTION TO PYTHON
print "B is greater than A" quotes to denote string literals, as long as the same type
of quote starts and ends the string.
You have to use the same number of spaces in the same
Triple quotes are used to span the string across multiple
block of code, otherwise Python will give you a syntax
error lines. For example, all the following are legal
7
INTRODUCTION TO PYTHON
#This is a comment statement saying “Press the enter key to exit”, and waits
for the user to take action −
print("Hello, World!")
To add a multiline comment, you could insert a # for each Once the user presses the key, the program ends. This is a
line: nice trick to keep a console window open until the user is
done with an application.
You can as well use a multiline string as shown in the
example below. Python will ignore any string literal that 2.13 Python Variables
This is a comment
They are containers for storing data values.
written on
In python, you do NOT need to declare a variable first
more than just one line before using it (i.e. python is dynamically typed).
"""
8
INTRODUCTION TO PYTHON
a=5
a = 10 #integer variable print(5)
name= "joe" #string variable
To print multiple values, we separate variables with
present=”yes” #boolean variable
commas as shown below
salary=10000.50 #floa variable
2.13.1 Assigning variables values Car1 = "Benz"
9
INTRODUCTION TO PYTHON
10
INTRODUCTION TO PYTHON
11
INTRODUCTION TO PYTHON
a = complex(1j) complex
Table 2.1Data type constructor methods
cars = tuple(("benz", "passat")) tuple There are three numeric types in Python; int, float and
complex
a = range(8) range
Example
person = dict(name="joe", age=18) dict
a= 5 # int
salary = 100000.98 # float
cars= set(("benz", "passat")) set c = 1j # complex
12
INTRODUCTION TO PYTHON
a = 7+5j
b = 4j
c = -2j a = """This is a example of a string,
Specify a Variable Type which spans more than one line."""
There may be times when you want to specify a type on to print(a)
a variable. Python being object-orientated language uses
we can also use three single quotes as shown below
classes to define data types, including its primitive types.
a = ‘’’This is a example of a string,
a = int(1) # x will be 1
which spans more than one line.’’’
b= int(5.9) # y will be 5
c= int("8") # z will be 3 print(a)
d = float(7) # x will be 7.0
x = str("str1") # x will be 'str1'
y = str(10) # y will be '10' Manipulating strings in Python
z = str(5.8) # z will be '5.8'
2.16 Strings
13
INTRODUCTION TO PYTHON
Just like many other popular programming languages, 2.16.3 String Length
strings in Python are arrays of bytes representing
To get the length of a string in python, we
Unicode characters.
the len() function. The following return the length of a
string known a name
There are a number of operations we can perform on
strings as discussed below
name = "Hello, World!"
print(len(name))
2.16.1 Accessing string element
2.16.4 Check for a String
We use square brackets can be used to access elements of
To check if a certain phrase or character is present in a
the string i.e., name[index]. The following example
string, we can use the keyword in.
accesses and displays the third element of array known a
name. str1 = 'The best things in life is when you love what you
are doing'
name = "Hello, World!" print("best" in str1)
print(name[2])
we can also use python if statement:
2.16.2 String Concatenation
str1= " The best things in life is when you love what
To combine, two strings in python, we you can use the + you are doing'"
if "best" in str1:
operator as show in the following basic example print("Yes, 'best' is present.")
2.16.5 Check if NOT
first = "Joe"
otherNames = "Chris"
fullNames = first + " " + otherNames In python, we use keyword NOT IN To check if a certain
print(fullNames)
phrase or character is present in a string or not
14
INTRODUCTION TO PYTHON
For example, to check if "programming " is NOT present 2.16.7 slicing from start
in the following text, we can use the following python
By leaving out the start index, the range will start at the
code
first character. The following example slices the string
from start up to character seven
str1 = 'The best things in life is when you love what you
are doing'
print("programming" not in str1) str1 = 'The best things in life is when you
love what you are doing'
we can also use an if statement as shown below print(str1[:7])
15
INTRODUCTION TO PYTHON
2. To convert a string into upper case, we use lower The following example will generate an error if you use
() method e.g.
double quotes inside a string that is surrounded by
Str1 = "Hello" double quotes:
print(Str1.lower())
replace() in python. An example is presented below Other escape characters used in Python:
16
INTRODUCTION TO PYTHON
if x > y:
\t Tab print("x is greater than y")
else:
\b Backspace print("y is not greater than x")
2.19 Python Collections (Arrays)
\f Form Feed
There are four collection data types supported by Python
2.18 Python Boolean programming language:
Booleans represent one of two values: True or False. List is a collection which is ordered and
When writing your programs, you may need to if an changeable and allows duplicate members.
expression is True or False. Anytime you compare two Tuple is a collection which is ordered and
values, the expression is evaluated and Python returns unchangeable but allow duplicate members.
the Boolean answer Set is a collection which is unordered,
unchangeable/immutable, and unindexed. It
Simple example are presented below
doesn’t allow duplicate members.
Dictionary is a collection which is ordered and
print(10 > 9)
print(10 == 9) changeable. No duplicate members.
print(10 < 9)
*Set items are unchangeable, but you can remove and/or
consequently, if run a condition in an if statement, Python add items whenever you like.
returns True or False:
**As of Python version 3.7, dictionaries are ordered. In
Python 3.6 and earlier, dictionaries are unordered.
x = 101
y = 100
17
INTRODUCTION TO PYTHON
When choosing a collection type, it is useful to Items in a list item can be of data any type; string, int,
understand the properties of that type. Choosing the right Boolean, float e.t.c. A list can contain values of different
type for a particular data set could mean retention of data types as shown below
meaning, and, it could mean an increase in efficiency or
student = ["Chris Joe", "Male", 20, 6.2,
security. True]
print(student)
2.19.1 Python List
Operations on list
To create a list in python, we use square brackets as
shown in the example below 1. To determine how many items a list has, use
the len() function as shown in example below
cars = ["volvo", "benz", "passat"]
print(cars)
cars = ["volvo", "benz", "passat"]
we can also use the list () Constructor when creating a as print(len(cars))
shown below
2. Accessing List Items
cars = list(["volvo", "benz", "passat"]) o To access an individual item in a list, we use the
print(cars) index number e.g. to display the third element in
Items in a list are ordered, changeable(mutable), and our list cars, we can use the following python code
allow duplicate values.
cars = list(["volvo", "benz",
"passat"])
To reference to items in a list, we use item e.g. the first print(cars[2])
item has index [0], the second item has index [1] etc.
19
INTRODUCTION TO PYTHON
remaining items will move accordingly as shown the append () method as shown in example below
by example below
20
INTRODUCTION TO PYTHON
6. Extend List o we can also use the del keyword as shown below
To append elements from another list to the current list, cars = list(["volvo", "benz",
"passat"])
use the extend() method as shown in the following del cars[2]
print(cars)
python code
o to remove the last item, we use the pop() method
cars = list(["volvo", "benz", "passat"])
cars2 = ["probox", "Nissan", "Toyotta"] without specifying the index as shown below
cars.extend(cars)
print(cars)
cars = list(["volvo", "benz", "passat"])
cars.pop()
print(cars)
The elements will be added to the end of the list.
8. To delete a list, we use del keyword as shown below
7. Remove List Items
o To remove Specified Item, we use cars = list(["volvo", "benz", "passat"])
the remove() method as shown in example below. del cars[]
print(cars)
cars = list(["volvo", "benz",
"passat"]) 9. Clear the List
cars.remove("benz")
print(cars)
We use the clear () method to empty the list. However,
o To remove an item based on specified Index, we the list still remains but with no content. An example is
use pop() method as shown below presented below
21
INTRODUCTION TO PYTHON
22
INTRODUCTION TO PYTHON
o We can access tuple items by referring to the index The above code returns the second, third and
number, inside square brackets. An example is fourth item in the tuple
presented below which prints the second item in
Note: The search will start at index 1 (included)
our tuple
and end at index 4 (not included).
mypc = tuple(("Hp", "16 GB RAM", Remember that the first item has index 0.
"500TB", "Icore 7", 98000.00, True))
print(mypc[1]) o By leaving out the start value, the range will start
Note: The first item has index 0. at the first item:
o We can also use negative indexing whereby the mypc = tuple(("Hp", "16 GB RAM",
"500TB", "Icore 7", 98000.00, True))
items are accessed from the end. To print the last print(mypc[:4])
item on the tuple, we can use the following python
The above example returns the items from the
code
beginning with index 4 not included
mypc = tuple(("Hp", "16 GB RAM", o By leaving out the end value, the range will go on
"500TB", "Icore 7", 98000.00, True))
print(mypc[-1]) to the end of the list as demonstrated in example
below
o We can also specify a range of indexes by
specifying start and end range. The result shall be mypc = tuple(("Hp", "16 GB RAM",
a new tuple with the specified items. "500TB", "Icore 7", 98000.00, True))
print(mypc[1:])
mypc = tuple(("Hp", "16 GB RAM", "500TB", The above example returns the items from index
"Icore 7", 98000.00, True))
print(mypc[1:4]) one up to the end the end of the list
23
INTRODUCTION TO PYTHON
mypc = tuple(("Hp", "16 GB RAM", "500TB", "Icore Tuples being immutable, they do not have a build-
7", 98000.00, True))
searchvar=input("Enter HDD specs in TB\n") in append () method. However, there other ways to add
if searchvar in mypc:
print("A pc with such specs has been found") items to a tuple.
else:
print("No pc with this spec matches your
search criteria") o We can convert tuple into a list: Just like the
workaround for changing a tuple, you can convert
Tuples are unchangeable, meaning that you cannot
it into a list, add your item(s), and convert it back
change, add, or remove items once the tuple is created.
into a tuple.
But there are some workarounds.
24
INTRODUCTION TO PYTHON
mypc = tuple(("Hp", "16 GB RAM", Set items can be of any data type. A set can also contain
"500TB", "Icore 7", 98000.00, True))
mypc2 = tuple(("silver",)) different data types
mypc += mypc2
print(mypc) shoppingList = set({"apple", 5, 25.00, True})
and unindexed. Set doesn’t allow duplicate values hence To determine how many items a set has, use
duplicate values will always being ignored the len() function. An example is presented below
print(len(myWishList))
* Note: Set items are unchangeable, but you can remove
items and add new items. 2. Access Set Items
To create a set-in python, we use the following code in It’s not possible to access items in a set by referring using
python: an index/ key. You can however use
wishlist = {"fridge", "car", "fees"}
print(wishlist) o for loop to loop through the items, or ask if a
specified value is present in a set,
It is also possible to use the set() constructor to make a
set as shown below
shoppingList = set({"apple", 5, 25.00,
True})
myWishList = set({"apple", "banana", "cherry", for i in shoppingList:
"apple"}) print(i)
25
INTRODUCTION TO PYTHON
shoppingList = set({"apple", 5, 25.00, o You can also use the pop() method to remove an
True})
print("apple" in shoppingList) item, but this method will remove the last item.
3. Add items
shoppingList = set({"apple", 5, 25.00, True})
Once a set is created, you cannot change its items, but you x = shoppingList.pop()
print(x)
can add new items using the add() method. An example is print(shoppingList)
shown below 2. The clear() method empties the set:
shoppingList = set({"apple", 5, 25.00, True}) shoppingList = set({"apple", 5, 25.00, True})
shoppingList.add("22/09/2022") shoppingList.clear()
print(shoppingList) print(shoppingList)
26
INTRODUCTION TO PYTHON
27
INTRODUCTION TO PYTHON
28
INTRODUCTION TO PYTHON
x = mypc.items()
print(x)
mypc["price"] = 120000.00
print(x)
mypc = {
Every time the dictionary is updated, the items list gets "model": "hp",
"RAM": "16GB",
updated as well
"HDD": "500TB",
"price": 90000.00,
6. Check if Key Exists "CPU speed": "Icore 7"
}
mypc["model"] = "lenovo"
To determine if a specified key is present in a dictionary print(mypc)
use the in keyword. An example has been presented 8. Update Dictionary
below
update() method will update the dictionary with the
mypc = { items from the given argument. An example is presented
"model": "hp",
"RAM": "16GB", below
"HDD": "500TB",
"price": 90000.00,
"CPU speed": "Icore 7" mypc = {
} "model": "hp",
searchvar=input("Enter key to search for\n") "RAM": "16GB",
if searchvar in mypc: "HDD": "500TB",
print(searchvar+"\t" + 'has been found') "price": 90000.00,
else: "CPU speed": "Icore 7"
print(searchvar + "\t" + 'has not been }
found') mypc.update({"HDD": "1TB"})
print(mypc)
7. Change Values
9. Python - Add Dictionary Items
You can change the value of a specific item by referring to
This is done by Adding by using a new index key and
its key name as shown below
assigning a value to it. An example is presented below
29
INTRODUCTION TO PYTHON
mypc = {
"model": "hp",
"RAM": "16GB",
"HDD": "500TB",
"price": 90000.00,
"CPU speed": "Icore 7"
} mypc = {
mypc["color"] = "black" "model": "hp",
print(mypc) "RAM": "16GB",
"HDD": "500TB",
10. Removing Items "price": 90000.00,
"CPU speed": "Icore 7"
There are several methods to remove items from a }
mypc.popitem()
dictionary: print(mypc)
mypc = {
mypc = { "model": "hp",
"model": "hp", "RAM": "16GB",
"RAM": "16GB", "HDD": "500TB",
"HDD": "500TB", "price": 90000.00,
"price": 90000.00, "CPU speed": "Icore 7"
"CPU speed": "Icore 7" }
} del mypc['HDD']
mypc.pop("model") print(mypc)
print(mypc)
11. The del keyword deletes the entire the dictionary
o The popitem() method removes the last inserted completely:
item (in versions before 3.7, a random item is mypc = {
"model": "hp",
removed instead): "RAM": "16GB",
"HDD": "500TB",
"price": 90000.00,
30
INTRODUCTION TO PYTHON
+ Addition a+b
2.20 Python Operators
- Subtraction a-b
Operators are used to perform operations on variables
and values e.g. + operator is used to add together two
* Multiplication A*b
values
/ Division a/b
Python divides the operators in the following 8 categories
% Modulus A%b
1. Arithmetic operators
2. Assignment operators ** Exponentiation A**b
3. Comparison operators
4. Logical operators
31
INTRODUCTION TO PYTHON
//= a //= 8 a = a // 3
Table 2:4 Assignment operators in Python
32
INTRODUCTION TO PYTHON
2.20.4 Python Logical Operators They are used to compare the objects to confirm if they
are actually the same object, with the same memory
They are category of operators used to combine
location
conditional statements
or Returns True if one of the Score==0 or is not Returns True if both x is not y
statements is true score<=39 variables are not the same
object
33
INTRODUCTION TO PYTHON
34
INTRODUCTION TO PYTHON
35