You are on page 1of 35

INTRODUCTION 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

vii). Python is Interactive meaning you can actually sit


at a Python prompt and interact with the
interpreter directly to write your programs.
viii). Python is Object-Oriented meaning the
programmers can benefit from OOP concepts such
as inheritance, abstraction, polymorphism and
encapsulation
2.3 What python can do

Being a general-purpose language, software engineers


can make applications in almost every domain of
software development. Python makes its presence in
every emerging field. It is the fastest-growing
programming language and can develop any application.

Fig 1.0-Different types of python applications

2.3.1 Web Applications

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.

The language provides useful frameworks, such as:


2.3.4 Software Development
o Django & Pyramid framework (Use for heavy It works as a support language and can be used to build
applications)
control, management, testing, etc.
o Flask and Bottle (Micro-framework)
o Plone and Django-CMS o SCons is used to build control.

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.

These are applications that run from the command-line/


shell. It provides many free libraries or modules which

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

i). An identifier starts with a letter A to Z or a to z or

2.5 Python Syntax an underscore (_) followed by zero or more letters,


underscores and digits (0 to 9).
Python Syntax compared to other programming
ii). Python does not allow punctuation characters
languages
such as @, $, and % within identifiers.
Python was designed for readability, and has some iii). Python is a case sensitive programming language.
similarities to the English language with influence from Thus, Camel and camel are two different
mathematics. identifiers 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.

use semicolons or parentheses. 2.7 Reserved Words


These are words that have a special/inbuilt meaning in a
Python relies on indentation, using whitespace, to define
programming language and cannot be used as a constant
scope; such as the scope of loops, functions and classes.
name, variable name or any other identifier name. All the
Other programming languages often use curly-brackets
for this purpose.

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:

Consider the code snippet below

if a>b:

print "A is greater than B"

else:

print "B is greater than A"

Python will give you a syntax error if you skip the


indentation and write all the lines of code in a straight
line as shown below:
2.8 Lines and Indentation
Python provides no braces like other programming if a>b:
languages to indicate blocks of code for class and function
print "A is greater than B"
definitions or flow control. Blocks of code are denoted by
line indentation, which is strictly enforced. else:

print "B is greater than A"

6
INTRODUCTION TO PYTHON

The number of spaces is up to you as a programmer, the fullNames = firs_name + \


most common use is four, but it has to be at least one.
middle_name+ \
if a>b:
last_name
print "A is greater than B"
2.10 Quotation in Python
else: Python accepts single ('), double (") and triple (''' or """)

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

if a>b: word = 'paragraph'

print "welcome to python programming " sentence = "This is a paragraph."

paragraph = """This is a paragraph. It is


print "B is greater than A"
made up of multiple lines and sentences."""
2.9 Multi-Line Statements
Statements in Python characteristically end with a new 2.11 Python comments
line. Python does, however, allow the use of the line The Python interpreter ignores comments which in
continuation character (\) to denote that the line should programming are used to:
continue as shown below
i). Document/explain code.

7
INTRODUCTION TO PYTHON

ii). Make the code more readable. print("Hello, World!")


iii). Prevent execution when testing code.
2.12 Waiting for the User
Comments starts with a #as shown below: The line of python code below displays a prompt, the

#This is a comment statement saying “Press the enter key to exit”, and waits
for the user to take action −
print("Hello, World!")

Python does not really have a syntax for multi-line


comments as other programming languages raw_input("\n\nPress the enter key to exit.")

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

hasn’t been assigned to a variable


A variable is a named in the computer’s memory that can
""" hold different values at different times.

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

In python, a variable is created the moment you first x, y, z = "benz”


assign a value to it. You do not need to specify any print (x ,y ,z)
particular type when declaring a variable in python, and
2.13.2 printing out variable values
can even change type after they have been set.
We use the Python print ( ) function to output variables
Examples of variable declarations are shown below: as shown in the example below:

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"

Python allows you to assign values to multiple variables Car2 = "Passat"

in one line as shown below Car3= "Prado"


print(Car1,Car2,Car3)
x, y, z = "crown", "Benz", "Passat"
2.13.3 Global Variables
print (x ,y ,z)
These are variables created outside of a function hence they
Always make sure the number of variables matches the
can be accessed by everyone i.e. both inside of functions and
number of values, or else you will get an error.
outside. An example is shown below

We can also assign the same value to multiple variables in x=5


one line as shown below
def myfunc():

9
INTRODUCTION TO PYTHON

y=6 def myfunc():


print ("The sum is " + (x+y)) global x=”5”
myfunc() myfunc()

If a variable with the same name is created inside a function,


this variable will be local, and can only be used inside that print("Python is " + x)
function. The global variable with the same name will
You can also use the global keyword if you want to
remain as it was, global and with the original value. An
change a global variable inside a function. As shown in the
example is shown below
example below
x = "5"
x = "5"
def myfunc():
def myfunc():
x= "7"
global x
print("Value of x is " + x)
x = "5"
print("X= " + x)
myfunc()
myfunc()
print("Value of x is " + x)
print("x= " + x)
2.13.4 Using global Keyword
2.14 Python data Types
A variable declared inside a function is local and can
therefore only be used inside that function. To create a In every programming language, data type is such an
global variable inside a function, we use the global essential concept. Datatypes specify the type of data a
keyword. An example is presented below:

10
INTRODUCTION TO PYTHON

variable can hold plus the operations allowed on that


variable.

Below is a table showing the python datatypes:

Fig 2.0-Python data types

The above are Python built-in datatypes

Table 1.0 Python primitive/inbuilt data types

In python, a data type is set when you assign a value to a


variable. If you want to specify the data type, you can use
the following constructor functions

11
INTRODUCTION TO PYTHON

Example Data Type Example Data Type

a = str("hello") str a= bytes(5) bytes

a = int(5) int a = bytearray(5) bytearray

a = float(100.7) float a = memoryview(bytes(5)) memoryview

a = complex(1j) complex
Table 2.1Data type constructor methods

cars = list(("benz", "passat",)) list 2.15 Python Numbers

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

cars = frozenset(("benz", "prado")) frozenset


2.15.1 Integers
They are used to store whole number, positive or
a = bool(5) bool
negative, without decimals, of unlimited length.

12
INTRODUCTION TO PYTHON

2.15.2 Float In python, strings are surrounded by either single/double


They are used to store a number, positive or negative, quotation marks as shown below
containing one or more decimals. Floats can also be
scientific numbers with an "e" to indicate the power of 10. print("Hello")
print('Hello')
2.15.3 Complex
They are numbers written with a "j" as the imaginary To assign a string multiline string to a variable, we use
part. Some examples are shown below three quotes as shown below

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])

2.16.8 Slice To the End


str1= " The best things in life is when you love what
you are doing'" By leaving out the end index, the range will go to the end.
if "programming" not in str1: The following example slices the string from position 11
print("Yes, 'programming ' is absent.")
up to end
2.16.6 String slicing
str1 = 'The best things in life is when you love
It’s possible to return a range of characters by using the what you are doing'
print(str1[10:])
slice syntax. We specify the start and end index separated
2.16.9 Python string built-in methods
by a colon, to return a part of the string.
1. To convert a string into upper case, we use upper
() method e.g.
For example, to return characters from 3 to position 8 of a
Str1 = "Hello"
string known as str1, we can use the following code print(Str1.upper())

str1 = 'The best things in life is when you love


what you are doing'
print(str1[2:8])

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())

String1 = "Python is “general” purpose programming


3. To remove whitespace before and/or after the actual
language."
text, we use strip() in python e.g.
We can fix the problem using the escape character \" as
Str1 = " Hello, welcome "
shown below
print(Str1.strip())
String1 = "Python is \“general”\ purpose programming
4. To replace a string with another string we use language."

replace() in python. An example is presented below Other escape characters used in Python:

str1 = "Hello, Welcome to python"


print(str1.replace("Hello", "Hi")
Code Result
5. The split () method splits the string into substrings if
it finds instances of the separator: \' Single Quote

str1 = "Hello/ Welcome to python" \\ Backslash


print(str1.split("/"))
2.17 Escape Character
\n New Line
An escape character in python are preceded by a
\r Carriage Return
backslash \ followed by the character you want to insert.

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.

Note: The first item has index 0.


18
INTRODUCTION TO PYTHON

o We can also use negative Indexing whereby cars = list(["volvo", "benz",


"passat"])
indexing start from the end with -1 refers to the print(cars[:2])
last item, -2 refers to the second last item etc. To
o By leaving out the end value, the range will go on
print the second last item in our list, we can use
to the end of the list. The following will return the
the following code
second item until the last item in our list

cars = list(["volvo", "benz",


"passat"]) cars = list(["volvo", "benz",
print(cars[-1]) "passat"])
print(cars[1:])

o We can also specify range of index from start to


3. Check if Item Exists
end. The result shall always be a new list with the
o To determine if a specified item is present in a list,
specified items e.g. to return the second third
we can use in keyword as shown in example below
items in our list we can use the following code
cars = list(["volvo", "benz",
cars = list(["volvo", "benz", "passat"]) "passat"])
print(cars[1:3]) print("benz" in cars)
Note: The search will start at index 1 (included) and end
o We can also use the if keyword in python as shown
at index 3 (not included).
below
1. Remember that the first item has index 0.
o By leaving out the start value, the range will start
at the first item. Example below returns the first
Example
two items in our list
cars = list(["volvo", "benz", "passat"])
search = input("Enter item to search for\n")

19
INTRODUCTION TO PYTHON

if search in cars: cars = list(["volvo", "benz", "passat"])


print("item found in the list") cars[1:2] = ['prado', 'audi'] # update
else: second and third item
print("item not found in the list") print(cars)

4. Change Item Value


o To change the value of a specific item, we use the
Note: The length of the list will change when the number
index number as shown below
of items inserted does not match the number of items

cars = list(["volvo", "benz", "passat"]) replaced.


cars[0] = 'subaru' # update first item
with subaru
print(cars) 5. Insert Items
o To insert a new list item, without replacing any of
o To change the value of items within a specific
the existing values, we can use
range, define a list with the new values, and refer
the insert() method. The item shall be inserted at
to the range of index numbers where you want to
the specified index as shown below
insert the new values as shown in example below
cars = list(["volvo", "benz",
cars = list(["volvo", "benz", "passat"])
"passat"]) cars.insert(1, "BmW")
cars[1:3] = ['prado', 'audi'] # update print(cars)
second and third item Note: As a result of the example above, the list will
now contain 4 items.
o If you insert more items than you replace, the new
items will be inserted where you specified, and the o To add an item to the end of the list, we use

remaining items will move accordingly as shown the append () method as shown in example below

by example below

20
INTRODUCTION TO PYTHON

cars = list(["volvo", "benz", cars = list(["volvo", "benz",


"passat"]) "passat"])
cars.append("bmw") cars.pop(0)
print(cars) print(cars)

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

cars = list(["volvo", "benz", "passat"]) countries = ("Kenya",)


cars.clear() print(countries)
print(cars)
2.19.2 Python and Tuple
It is also possible to use the tuple () constructor to make a
Tuples are used to store multiple items in a single
tuple. as demonstrated below
variable and are defined using round brackets. An
example is shown below mypc = tuple(("Hp", "16 GB RAM", "500TB", "Icore
7", 98000.00, True))
print(mypc)
countries = ("Kenya", "United Kingdom", "United Tuple Items - Data Types
States", "Congo")
print(countries)
Tuple items can be of any data type and a tuple can
Items in a tuple are ordered, unchangeable/immutable, contain different data type just like a list as shown below
and allow duplicate values. Tuple items are indexed, the
mypc = ("Hp", "16 GB RAM", "500TB", "Icore 7",
first item has index [0], the second item has index [1] etc. 98000.00, True)
print(mypc)
Since tuples are , we can have items with the same value
Tuple operations
countries = ("Kenya", "United Kingdom",
"United States", "Congo", "Kenya") 1. Tuple Length
print(countries)
To determine tuple Length, we use the len() function as
Create Tuple with One Item
shown below
To create a tuple with only one item, you have to add a
countries = ("Kenya", "United Kingdom", "United
comma after the item, otherwise Python will not States", "Congo", "Kenya")
print(len(countries))
recognize it as a tuple.
2. Access Tuple Items

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

3. Check if Item Exists mylist[1] = "32 GB RAM" # modify item 3


mypc = tuple(mylist) # convert the list to tuple
print(mypc)
To determine if a specified item is present in a tuple use 5. Add Items
the in keyword as shown in example below

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.

mypc = tuple(("Hp", "16 GB RAM", "500TB",


4. Change Tuple Values "Icore 7", 98000.00, True))
mylist = list(mypc) # convert tuple into
tuple
Once we create a tuple, we cannot change its values since mylist.append("Silver") # add a new item
at the end
they ate unchangeable/ immutable mypc = tuple(mylist) # convert the list to
tuple
print(mypc)
But there is a workaround. You can convert the tuple into
a list, change the list, and convert the list back into a tuple. o Add tuple to a tuple. You are allowed to add tuples
to tuples, so if you want to add one item, (or
mypc = tuple(("Hp", "16 GB RAM", "500TB", "Icore
7", 98000.00, True))
many), create a new tuple with the item(s), and
mylist = list(mypc) # convert tuple into tuple add it to the existing tuple:

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})

2.19.3 Python and Set print(len(shoppingList))

A set is a collection which is unordered, unchangeable*, 1. Get the Length of a Set

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

myWishList = set({"apple", "banana",


Sets are defined with curly brackets. "cherry", "apple"})

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)

print(myWishList) o use in keyword.

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)

3. The del keyword will delete the set completely


1. Remove Item shoppingList = set({"apple", 5, 25.00, True})
o To remove an item in a set, use the remove()/ del shoppingList
the discard() method. Remove apple using remove print(shoppingList)
()
2.19.4 Dictionary
shoppingList = set({"apple", 5, 25.00, True})
shoppingList.remove("apple")
Dictionaries are used to store data values in key: value
print(shoppingList)
Note: If the item to remove does not exist, remove pairs. It is ordered*, changeable and do not allow
() will raise an error.
duplicates.
o Remove "25.00" by using the discard() method:
Dictionaries cannot have two items with the same key.
shoppingList = set({"apple", 5, 25.00, True})
shoppingList.remove(25.00) Creating dictionary in python
print(shoppingList)
Note: If the item to remove does not Dictionaries are written with curly brackets, and have
exist, discard() will NOT raise an error.
keys and values. An example is defined below

26
INTRODUCTION TO PYTHON

mypc = { o You can access the items of a dictionary by


"model": "hp",
"RAM": "16GB", referring to its key name, inside square brackets.
"HDD": "500TB", To get your PC speed, we can use the following
"price": 90000.00,
"CPU speed": "Icore 7" python code
}
print(mypc) mypc = {
"model": "hp",
Dictionary Items - Data Types "RAM": "16GB",
"HDD": "500TB",
"price": 90000.00,
"CPU speed": "Icore 7"
The values in dictionary items can be of any data type i.e., }
string, int, Boolean, and list data types: print(mypc["CPU speed"])

o We can also use the get() as shown below


Dictionary Length
mypc = {
"model": "hp",
We use the len () function to determine how many items a "RAM": "16GB",
dictionary has. An example is presented below. "HDD": "500TB",
"price": 90000.00,
mypc = { "CPU speed": "Icore 7"
"model": "hp", }
"RAM": "16GB", x = mypc.get("CPU speed")
"HDD": "500TB", print(x)
"price": 90000.00,
"CPU speed": "Icore 7" 2. Get Keys
}
print(len(mypc)) The keys() method returns a list of all the keys in the
dictionary operations dictionary.
1. Access Dictionary Items

27
INTRODUCTION TO PYTHON

mypc = { "price": 90000.00,


"model": "hp", "CPU speed": "Icore 7"
"RAM": "16GB", }
"HDD": "500TB", x = mypc.values()
"price": 90000.00, print(x)
"CPU speed": "Icore 7"
} If any changes is done on the dictionary, changes will
x = mypc.keys()
print(x) reflect on the values list. An example is presented below
3. Add new item to Dictionary
mypc = {
Add a new item to the original dictionary, and see that the "model": "hp",
"RAM": "16GB",
keys list gets updated as well: "HDD": "500TB",
"price": 90000.00,
"CPU speed": "Icore 7"
mypc = { }
"model": "hp", x = mypc.values()
"RAM": "16GB", print(x)
"HDD": "500TB", mypc["price"] = 120000.00
"price": 90000.00, print(x)
"CPU speed": "Icore 7"
} 5. Get Items
x = mypc.keys()
print(x)
mypc["color"] = "silver"
Items() method will return each item in a dictionary, as
print(x) tuples in a list inform of key: value pairs. An example is
4. Get Values presented below

The values() method will return a list of all the values in


mypc = {
the dictionary. "model": "hp",
"RAM": "16GB",
"HDD": "500TB",
mypc = {
"price": 90000.00,
"model": "hp",
"RAM": "16GB",
"CPU speed": "Icore 7"
"HDD": "500TB", }

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)

o The del keyword removes the item with the


o The pop () method which removes the item with
specified key name e.g.
the specified key name:

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

"CPU speed": "Icore 7" 5. Identity operators


}
del mypc 6. Membership operators
print(mypc)
7. Bitwise operators
2.20.1 Python Arithmetic Operators
12. The clear() method empties the dictionary:
mypc = {
"model": "hp",
These are category of operators used to in conjunction
"RAM": "16GB", with numeric values to perform common mathematical
"HDD": "500TB",
"price": 90000.00, operations:
"CPU speed": "Icore 7"
}
mypc.clear()
print(mypc) Operator Name Example

+ 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

// Floor division a//b **= a **= 9 a = a** 3

Table 2:2 Arithmetic operators in Python


Table 2:3 Assignment operators in Python
2.20.2 Python Assignment Operators
2.20.3 Python Comparison Operators
They are category of operators used to assign values to
They are set of operators used to compare two values
variables:

Operator Name Example


Operator Example Same As
== Equal a == b
= a = 10 a= 10
!= Not equal a!= b
+= a+= 10 a = a+ 10
> Greater than a>b
-= a-= 7 a = a-7
< Less than a<b
*= a *= 6 a=a*6
>= Greater than or equal a >= b
/= a /= 8 a=8/3 to

%= a %= 2 a = 2% 3 <= Less than or equal to a <= b

//= 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

Operator Description Example Operator Description Example

is Returns True if both x is y


and Returns True if both Score>70 and
variables are the same
statements are true score < 100
object

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

not Negates a Boolean result, not(a < 5 and b<


returns False if the result 10) Table 2:6 Identity operators in Python
is true

2.20.6 Python Membership Operators


Table 2:5 logical operators in Python
Membership operators are used to test if a sequence is
2.20.5 Python Identity Operators
presented in an object:

33
INTRODUCTION TO PYTHON

o int () – converts a value into an integer number


Operator Description Example
from an integer literal, a float literal (by removing
in Returns True if a sequence x in y all decimals), or a string literal (providing the
with the specified value is string represents a whole number)
present in the object
o float () – converts a value to float number from an
integer literal, a float literal or a string literal
not in Returns True if a sequence x not in y
(providing the string represents a float or an
with the specified value is
integer)
not present in the object

o str () – converts a value to a string from a wide


Table 2:7 Identity operators in Python variety of data types, including strings, integer
literals and float literals

2.21 Python & Casting # type casting using integers


x = int(1) # x will be 1
Type casting refers to the process a of converting variable y = int(2.8) # y will be 2
z = int("3") # z will be
from one data type to another. Python is an object- # float type casting
x = float(1) # x will be 1.0
orientated language, and as such it uses classes to define y = float(5.4) # y will be 2.8
z = float("6") # z will be 6.0
data types, including its primitive types. w = float("4.2") # w will be 4.2

Casting in python is therefore done using constructor


functions:

34
INTRODUCTION TO PYTHON

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

35

You might also like