Python Programming

INTRODUCTION

There are others programming languages like Java and C++.

Python is a general-purpose, high-level interpreted language with easy syntax and dynamic semantics.

It was developed by Guido Van Russum in 1989


Who uses Python?


What is Python used for?


Why use Python?

• It works on different platforms such as Windows or Mac, or even Linux, Raspberry Pi

• The syntax is close to English language and contains no semicolons or curly brackets. Compare the two ways of printing a simple statement using C++ and Python as shown below. Which is easier?

• Developers like Python because they achieve same results as other languages but with fewer lines of code


How do you use Python?

To begin coding in python, download the software from www.python.org

OPERATORS

Arithmetic Operators

MathsPython
2 + 3 = 52 + 3
5 x 65 * 6
17 / 617 / 6
quotient of 17 / 317 // 3
remainder of 17 / 317 % 3

divmod (24, 6) will return (4, 0), that is, the quotient and the remainder.  It is similar to (a//b, a % b)



Assignment Operators

a = 3 assign or equate 3 to a  

a += 3 add and assign to a  

a -= 3 subtract and assign to  

a *= 3 multiply and assign to  

a /= 3 divide and assign to

a %= 3 get the remainder and assign to a



Comparison Operators

> is greater than

< is less than

== is equal to

!= is not equal to

>= greater than or equal to

<= less than or equal to




Logical Operators: and/or/not

OR operator

AND Operator

NOT Operator

Logical operators are usually used with conditional statements



Absolute and Boolean Operators

abs means

absolute value abs (-43) = 43

bool (0) and bool (none) returns False. All others return True


Membership operators: in / not in

They are used to check if an element belongs to a given set. 

The values returned are True or False


DATA TYPES

• Numbers: integer, float, complex

• Boolean

• String

• List

• Tuples

• Dictionaries

• Sets


STRINGS

Strings can be counted, with the first character having index = 0.

Length = 6



We use square brackets to slice strings

str[index]

str[start : stop]: returns the string between the startindex and stop index

str[start : stop : step]: returns the string between the start and stop index in  steps


Strings

str.replace (“string”, “replacement”) will replace a string with another string

str.title() returns the string where each word begins with a capital letter  str.upper() returns the string where each word is in uppercase

str.swapcase() returns a copy of the string with uppercase characters converted to lowercase and vice versa



str.format() will perform a formatting operation on replacement fields delimited by {}.

Each replacement field contains either the numeric index of a positional argument or the name of a keyword argument

“The sum of 1 + 2 is {0}”.format (1+2)

str.format(age) will insert the age andreturn result as a string  str = “Dipo is{age} years old” *show these codes*

Multiple formating is allowed

qty = 8

price = 500

myorder = “I want {}pieces of items for {}”  print (myorder.format(qty, price)


We can count the number of  times a character appears in a string within a given a range

“James is too good”.count(“o”) returns 5  “James is too good”.count (“o”, 1,15) returns 3

We can also find the position of  the first time a given character appears in  a string by using the .find() or.index() methods

“James is too good”.find(“o”, 0, 20) returns 10

If  we want to split the words in a string, we use the.split() and use sep as the delimeter string

“James is too good”.split(sep = “ ”) returns [“James”,“is”, “too”, “good”]

Working backwards, we can use the “seperator”.join(iterable)” to convert a list to a string and puts the separator string in between the items

“ ”.join([“James”, “is”, “too”, “good”]) will return “James is too good”

str.strip() removes whitespace before and after the string or whatever is specified in the bracket

“  removes whitespace  ”.strip() will return ‘removeswhitespace’



LISTS

The list is probably the most versatile datatype in Python.  Characteristics

• Ordered: they can be indexed

• Mutable: the elements can be modified after it is created

• Homogenous (or heterogenous) data: they can contain numbers, strings,  or even another list

• Allows duplicate

List may be thought of like a plate rack. They can be created using

[ ], list (iterable), [x for x in range(10)]




Look at this list we created

L = [15, “Mike”, 23.75, [20, 40, 60]]

Length = 4

list.append (x): add an item to the end of a list equivalent to a[list(a):] = [x]  

list.extend (t): extends list with the contents of another list t

You can also add any iterable such as tuples, sets and dictionaries using this extend

list [i : j] = iterableT slice of list from i to j is replaced by the contents of the  iterable T



You can change the items in a list by referring to a range

fruits[2:3] = [‘apple’, ‘pawpaw’, ‘orange’, ‘pineapple’] will insert the new list in the third position

fruits[2:3] = ‘mango’ will put it as [‘apple’, ‘pawpaw’, ‘orange’, ‘m’,’a’,’n’,’g’,’o’,  ‘pineapple’]

list.insert (i, x): insert an item in a given position. Thei is the position of the element before which to insert

list.remove (x): remove the first item from the list whose value is x. 

list.copy(): creates ashallow copy of list. newList =oldList.copy()

list.pop(i): remove the item from the list and return it. Ifno index is specified, it  removes the last item

list.clear () empties the list. The list still remains but has no contents










The .sort() method can take two arguments – key and reverse  

fruits.sort(key = None, reverse = True)

You can also reverse a list using .reverse()

list.index (x[, start[, end]]) index of the first occurence of x in list (at or after start index and before end index

list.count (x) total number of occurences of x in list  list.sort(key = none, reverse = False)

e.g. numbers = [2, 6, 3, 18]

numbers.sort(reverse = True) will give 18, 6, 3, 2

e.g2

def myfunc(n):  

return abs(n)

numbers = [100, 50, 65, 82, 23]

numbers.sort(key = myfunc)  print(numbers)

RESULT: [50, 65, 23, 82, 100]

By default, the listName.sort() is case sensitive, that is, it will sort out items that  begin will a capital letter before items in small case. if you want it to be case  insensitive, use the key = str.lower

list.reverse (): reverses the items of  list in place

list comprehension consists of brackets containing an expression followed by a ‘for’ clause, then zero or more for or if clauses

fruits = [‘apple’, ‘banana’, ‘pawpaw’]

[print (x) for x in fruits]

[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if  x!=y]

newlist = [expression FOR item IN iterable IF condition == True]


TUPLES

• They are immutable: You cannot change them but only redefine them.

• They do not support item assignment

•T hey are usually used to store heterogenous data

They can be constructed using ( ), (a, b, c), tuple(iterable)

Tuples don’t have the inbuilt .append( ) function. However, if you want to add items to a tuple, you can

1. convert it to a list, add, and convert back to tuple

2. add tuple to tuple 

unpacking a tuple

fruits = (‘apple’, ‘orange’, ‘cherry’) 

(green, yellow, red) = fruits


DICTIONARY

Dictionaries are ordered, changeable datatypes that do not allow duplicates

Ordered means the items have a defined order and can be referenced by an index.

car = {‘brand’ :‘Toyota’, ‘model’ : ‘Corolla’}  Notice the use of curly braces

So you can construct a dictionary using {key : value} like the example  above, or

car = dict([(‘brand’, ‘Toyota’), (‘model’,‘Corolla’)])

car[‘colour’] = ‘black’ will add a new item to the dictionary

.items() will return each item in a dictionary as a list

Use DictName.update (DictName2) to add items to a dictionary

car.pop (‘model’) will remove the item specified by the key  car.popitem() removes the last item

VarName = {‘Var1’:15, ‘Var2’:20}. DictName.values(), DictName.keys (),  Using for loop will return just the keys

for x in car:

print (x)

for x, y in car, items():

This will loop through keys and values

print (x, y)

for b in car:

print (car[x]) will return values





Nested Dictionaries


SETS

A set in Python is

• an unordered collection, which means you can’tindex them

• unique with no duplicate elements.

• changeable.

Sets can be used to test for membership and removing duplicates

Curly brackets {} or the set ( )function can be used to create sets.


Did you notice the duplicate element was removed when it printed set A?

You can add an element to a set using .add( ). For example, A.add (‘purple’) will add  purple to the set A

CONDITIONAL STATEMENTS

IF/ELSE Statements

These usual coding statements are used to make decisions only if a certain condition is satisfied

if test expression

statement(s)

comparison operators (>  <  >=  <=  ==  !=) are very often used with if/else statements.

A colon is added at the end of the if, elif  and else statements

Also, you will see that Python relies on indentation to define the scope of a code just the way other programming languages use curly brackets.





You can combine multiple conditions using elif keyword

if test expression:

statement  

elif  test expression:

statement(s) 

else:

statement


FOR – WHILE loops

while loop executes as long as the condition remains true

while condition:

statement(s)


For loops execute a sequence of statements multiple times depending on the iterable (range, list, string, tuple, dictionary):


Range Function

The range ( ) function generates an arithmetic progression

range (n)

range (start, stop, step)  

Note that the last number is never printed

list (range(4)) gives you the values [0, 1, 2, 3]

sum (range(4)) finds the sum of the first 4 numbers starting from 0, and it gives 10


Loop Control Statements

break tells the machine to leave the loop enclosing for or while loop

continue goes on with the next iteration of the loop. It will bypass any code written under it

pass is like a filler statement – it doesn’t do anything

next (iterable, default)

default is an optional parameter. It is returned when there is no next item and the iterator is exhausted


With the ‘else’ statement in a while/for loop, we can continue with a block of  code once the condition is no longer true or when the loop has ended.

Nested loops

You can have a loop within a loop. The inner loop will be executed first before the outer loop



try and except

The try block allows you to test a block of code for errors.  The except block lets you handle the error

They can be used to check the user hasn’t typed anything wrong.


It may be used to check internet connection

The raise statement allows the programmer to force a specified exception to occur

FUNCTIONS

A function is a block of code that runs when it is called. The keyword def  introduces a function definition.

It must be followed by the function name and the list of  parameters in bracket, then a colon(:).



The parameter is the variable inside a function while an argument is the value sent to the function.

A function definition looks like

A function must be called with the correct number of  arguments

You can have

but you cannot have a positional argument after a keyword argument.

If  the number of  keywords are unknown, add * before the parameter  

If you call a function without an argument, it uses the default value  (specified by the parameter).

A function can call itself (recursion)

Global and Local Variables

Variables that are created outside of a function are called global variables. Local variable cannot be called outside a function

To create a global variable inside a function, use the global keyword  




Python Lambda Function

It is quick way to write a small, one-line function

lambda arguments:

expression

It may be used as an anonymous function inside another function  

is equivalent to




CLASSES

A class is used to define the characteristics of an object (fields and properties) and the things it can do (methods).

It is collection of  methods and variables under a common name. Class  provide a means of  bundling data and functionality together.

A namespace is a mapping from names to objects

class ClassName:

statement1

statement2

Class objects supports two kinds of  operation: attributes references and  instantiation

An attribute may simply be any name following a dot. E.g.

real is an attribute of the object z.

often the first argument of a method is self

Class variables are for attributes and methods shared by all instances of the class

instance variables are unique to each instance.

An instance is the class object that is created at run time. It can be called the physical manifestation of a class. An instance is created when a class is assigned to a variable.

An object is the actual thing made using the blueprint (class) and the instance is the virtual copy of that object.

A method is a function that belongs to an object. A constructor (init) is a special type of method that Python calls when it creates an object/instance.

If  you create a class called student, you expect it to have related variables  like Serial_No, School, Age. Stock price, average rainfall will ruin the point  of  having a class.

Classes help with reusability. You can call the same methods defined in  another class

They also help with maintainability because you use less lines making it  easier to debug. You can make custom exceptions to your classes

Inheritance is the concept of  having a class inherit properties from  another class.

Encapsulation

This is the concept of  restricting the direct access of  variables and  methods. It only allows the object itself  to change its variable, just to avoid  any accidental change. We call such variables private or protected.

PROTECTED – can only be accessed by the class itself, or its sub-classes.  You declare a protected member by using a single underscore _ as preficx

PRIVATE – only accessed by the main class itself. You use a double underscore as prefix.

MODULES

Modules are libraries that hold functions, Python definitions and  statements.

It can contain executable statements

The file name is the module name with the suffix .py appended and saved  in the current directory.

To use a module, you need to import the contents


Random module

It provides tools for making random choices

random.sample / random.choice / random.randrange/random.random

Randint

Randbytes

Shuffle

uniform


math module

sin/cos/tan/pi/radians/degree/log

Statistics

Mean/median/mode/quantiles, variance, correlation

Time, datetime

os module

This module allows us to use the functionalities of the operating system.


json module

Json stands for JavaScript Object Notation) is a lightweight data interchange format

stands for dump string. This will modify a Python dictionary to a JSON string

Note that keys in key-value pairs of JSON are always of the type str.

json.load() accepts the file object, parses the JSON data, populates a Python dictionary with the data

json.loads(given_json) stands for load string. It takes in the file content and not the file path as a string and returns a Python dictionary


csv module

Comma Separated values format is the most common file type for spreadsheets and databases

with open(‘csv_name.csv’, newline =‘’) as variable_name:

  reader_name = csv.reader (variable_name, delimiter =‘’, quotechar = ‘|’))

  #for loop

with open(‘csv_name.csv’, ‘w’, newline =‘’) as variable_name:

  writer_name = csv.writer (variable_name, delimiter =‘’)

  writer_name.writerow(string)

DictReader: after reading the file,

  #for row in reader:

  print (row[‘first_name’], row[‘last_name’])

DictWriter : after writing

  columns_list = [column_names]

  writer = csv.DictWriter(csvfile, fieldnames = column_list)

  writer.writeheader()

  writer.writerow({‘first_name’: ‘James’, ‘last_name’: ‘Bond’})


turtle module


tkinter module


Third Party Modules

pandas, numpy, matplotlib are commonly used packages for data analysis, manipulation and presentation

Django, flask are used to create websites and develop web software

Pygame is used to create video games

NLTK (Natural language tool kit) is used for processing language data

WHAT’S NEXT?

With Python you are equipped to gain understanding in

Scroll to Top