Sie sind auf Seite 1von 82

Table

of Contents

Overview
1 First Program
2 Variables
3 Expressions
4 Conditions
5 Loops
6 Functions
7 List
8 Time
9 Files
10 Database
Overview

Python is a great language for gamers and programmers. This book is for those
who are new to this language and such the book will go through the
fundamentals of writing a program using Python.

The book starts with writing a basic program and goes through the normal
sections of a program such variables, conditions, loops, lists, functions, files and
database elements.

Prior knowledge of programming in any language will be helpful but really not
required.

Before we start:

The first thing to do is to get an editor for writing the programs. There are two
ways to get an editor. One an online editor and the other to install the software.

The second option is recommended because to understand a language it is best to
install the software or editor that goes with it. Online editors have limitations
depending upon the provider and does require the programmer to be online.

The editor to install is available at http://www.python.org and the version this
book uses 3.6.3 even though python does release new versions comparatively
frequently.

Install the version appropriate for computer. The examples in this book were
done on a Windows 10 64-bit machine.

Download and install the version for your computer. Note there are two versions
(64 bit and 32 bit) for Windows machines.

Installation can be the suggested default directories.

The best way to learn programming is through pencil and paper before typing
into an editor. It is an old way of learning in a time of tablets and touch screens
but it has proven to always work.

The website for this book is http://www.beam.to/fjtbooks or type fjt books in
google search.
Chapter 1. First Program

The first program written in every programming class is one to display the words
"Hello World". It is an unwritten tradition. In this regard start the Python editor
from windows apps.


The editor can be started with by clicking the IDLE Python option as shown in
the above picture. The editor looks like a notepad file with a menu on top.

Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit
(AMD64)] on win32
>>> greetings ="Hello World!!"
>>> print(greetings)
Hello World!!
>>> print("Hello World")
Hello World

In the code above there are two ways to print Hello World to the screen. The first
is to start with a variable called greetings which has the string value of "Hello
World" followed by a print statement that prints the values of the variable. Note
the brackets in the print statement.

The second method is a direct print statement where the string is inside the
brackets within double quotes.

Thus the tradition of printing Hello World has been completed using Python.
This method will work irrespective of the version of python interpreter
downloaded.

The above code was written directly into the editor a line at a time. Suppose an
entire code (two or more lines at a time) has to be written before running the
execute command.

In this case go to File in the editor and click on New File. This will open a
notepad like page. Write the entire code here and hit Run. Choose F5 Run. The
editor will prompt for the program to be saved.

The next step in the process of making a Python program is to save the program
written.



The default location will come up. This location can be chosen or any other
folder on the computer.

The next time the same code is to be run, open the editor and choose open under
File option on the menu and choose the file by its name.

It is advisable to use the default location until one becomes more conversant
with the editor and the Python language.

The editor allows for code to copied and pasted into other documents especially
word documents. This makes it easier for those working on projects.

Never forget to save changes when modifying code. It is best to get the habit of
saving frequently as that would save a lot of pain in the long run. This is from
experience.

The editor configuration such as font used, highlights, indentation used as
standard can be changed by going under the options menu above.

Generally, for starters such a change is not required.

Workshop:

1. Print the words "My First Python Program" using a variable.

2. Print the words "My First Python Program" using a direct print statement.

3. Note and write down the version of Python editor on the machine you are
using.

4. Python uses a compiler to compile programs - True / False.

5. Python can be used for all types of programs just like any other programming
language. True / False

6. The extension of a python file is _____.

7. What is the difference between a compiler and an interpreter?

X-X-X
Chapter 2. Variables

Variables in programming languages are considered temporary storages of data.
It is common to use the alphabets as variables but more meaningful names will
greatly help the programmer in the long run.

Variables can have data types. The usual data types are:

Integer
Float
Long
Double
String
Array
Boolean- True/False

Python is no different in having variables but what makes it stand out is that
these variables can be stated dynamically.

In a programming language such as Java, C++ etc. a common way to introduce a
variable would be as follows.

Int x
x = 2;

Here in Python it will be written as follows.

x= 2
x= "Hello"
x= False
x= True
x= 1.5

Notice that the use of double quotes makes the value a variable a string. Thus x
= 2 and x ="2" are not the same.

Numbers whether integer or double can be printed to the screen as follows:

print (4)

print (4.54)

The printing of the string to the screen was seen in the previous chapter.

print (False)

print (True)

Note that capital letters for the Boolean values.

In built into python the int function can convert a string representation to an
integer number format and str function can convert a number into string format.

Example:

>>>str(4)
>>> '4'
>>> int('4')
>>> 4

Not all strings have integer equivalents.

For numbers the basic operations on them are:

+ for addition

- for subtraction

/ for divide

* for multiplication

** for exponent

Example:

>>> 4**4
>>> 256
>>> 2/2
>>> 1.0

But for a string the plus (+) sign means concatenate.

Example:

>>>"ABC" + "123"
>>> 'ABC123'
>>> '5' + '4'
>>>'54'
>>> int('5') + int('4')
>>> 9
>>>'5' + str(4)
>>>'54'

The type function can determine the type of an expression.

Example:

>>> type (3 +4)
>>><class 'int'>
>>>type ('3' + '4')
>>><class 'str'>

No commas can be used with numbers in Python. For example 4,15 cannot be
used but 415 is okay.

Python integers can be as large as possible. The memory of the computer sets the
limits of the size of the integers.

As seen in the last chapter variables can be assigned values either numbers or
strings or Boolean.

The assignment operator is the equal to (=).

The assignment statement is read such that the variable on the left hand side of
the equation (=) takes on the value or the value of the variable on the right hand
side.

x= y

means x takes on the value of y.

Example:

>>>x = 5
>>>print(x)
>>> 5
>>>print('x')
>>> x
>>> print("x is:" + str(x))
>>> x is: 5

x is an integer but the string to concatenate needs a string variable. Thus in the
above last line x was converted to string for concatenation.

To avoid this and print variables of different types on a single line use a comma
separated list as follows:

>>> print ("x is:" , x)
>>> x is: 5

Such a comma separated list of variables is referred to as a tuple assignment.

>>> x =0
>>> y= "Hello"
>>> z = 45
>>> print (x,y,z)
>>> 0 Hello 45

The value and type of a variable can change within a program.

Example:

>>>x=10
>>>print (x)
>>>10
>>>x="ABC"
>>>print (x)
>>> ABC

Alphabets can be good variable names but when programs get bigger it will
become confusing. Thus descriptive names such as total, sum etc can take the
place of alphabets as variables.

Python has reserved words that cannot be used as variable names just like other
programming languages.

and del from None try
as elif global nonlocal True
assert else if not while
break except import or with
class False in pass yield
continue finally is raise
def for lambda return

are examples of reserved words in Python. These cannot be used as variables.

In addition to these reserved words the following rules must be followed when
choosing variable names.

1. A variable must contain at least one character.

2. The first character must be an alphabetical character of upper or lower case or
an underscore.

3. The remaining must be alphabetical characters of upper or lower case or digits
or
underscore.

4. Spaces are not acceptable as identifiers.

Floating point numbers are those numbers whose decimals points can move or
float depending on the calculations on them.

Example:

>>>x = 3.45
>>>x= x *20
>>>print (x)
>>> 69.0

The characters that can appear within strings include letters of the alphabet (A-Z,
a-z), digits (0-9), punctuation (., :, ,, etc.), and other printable symbols (#, &, %,
etc.).

Control codes control the way text is rendered in a console window or paper
printer. The backslash symbol (\) signifies that the character that follows it is a
control code, not a literal character.

The \n control code represents the newline control code which moves the text
cursor down to the next line in the console window.

Other control codes include \t for tab, \f for a form feed (or page eject) on a
printer, \b for backspace, and \a for alert (or bell).
Listing 2.8: specialchars.py
Example:
>>>print("A\nB")
A
B
>>>print ("A\tB")
A B
>>>print ("A\bB")
A

A string can be included within a double or single quote. If a double quote is
used, then single code can be included within it and vice versa. The choice is up
to the programmer.

Since the backlash is used as a control code a double backlash (\\) has to be used
if trying to write a path or web link

>>> x= ("C:\\User\\Users\\Desktop")
>>> print("Print file location is:" + x)
>>> Print file location is: C:\\User\\Users\\Desktop

Up to now the values of various variables used in the examples has been hard
coded. This is not practical all the time. If the Python program needs an input
from outside the program such as from the keyword the input function can be
used.

Example:

print("Please enter a number")
x=input()
print(x)
print(type(x))


Now run the program and one will the type is given as string.

The input function will give only strings. Use the int function to convert the
input into number if needed.

Example:
print("Please enter a number")
x=input()
print(x)
print(type(x))
x=int(x)
print(type(x))
x= x+1
print(x)

This will give the output as follows:

Please enter a number
1
1
<class 'str'>
<class 'int'>
2

The above program can be modified to include the prompt within the input()
function as follows:

x=input("Please enter a number")
print(x)
print(type(x))
x=int(x)
print(type(x))
x= x+1
print(x)

Like the int function the float function can be used to convert the input into a
float. Python provides the eval function that attempts to evaluate a string in the
same way that the interactive shell would evaluate it.

Example:
x1 = eval(input('Entry x1? '))
print('x1 =', x1, ' type:', type(x1))

Run the code and enter various types of values-integer, float or string.

Example:

print('A', end='')
print('B', end='')
print('C', end='')
print()
print('X')
print('Y')
print('Z')

The output will be as follows:

ABC
X
Y
Z

The print statement accepts an additional argument with the end='' that allows
the cursor to remain on the same line as the printed text.

The string x= "Hello World" can be represented by indices.

x[0] = H
x[1] = e
x[2] = l
and so forth. This feature of Python and string can prove very useful.

x= "Hello World"
print (len(x))

This will give the length of the string which is 11 including the space.

Workshop:

1. Write a program the will prompt the user to give his or her name and give
back the length of the name.
2. Will the following lines of code print the same thing? Explain why or why
not.
x = 10
print(x)
print("x")

3. Which of the following are not correct variable names in Python?

(a) John
(b) if
(c) 2x
(d) 15+
(e) sum_total
(f) x2
(g) Private
(h) _pass
(i) pa sword123
(j) +_if
(k) a_none

4. Write a program in Python that will take two numbers and multiply them. Use
the input method and convert into float.

5. Write a Python program that will give the following output.

A
B
C
XY
12
10 11 12

6. How is definition of variables in Python different from that in other languages
such as C++, or Java etc?

7. Is the following operation allowed in Python?

x= 5
x= x + 5
z= 1
y= z + x
x =y
Chapter 3. Expressions

The term expressions can be best associated with mathematics. These are used to
manipulate inputs for a certain objective.

Look at the following expressions in Python.

a + b means a is added to b if both are numbers. If they are string, then a and b
are concatenated.

a - b means a take away b if both are numbers.

a * b means a multiplication between two numbers if both are numbers.
However, if a is a string and b is a number then it means that a will be
concatenated with itself b times. If b is a string and a is a number, then b will be
concatenated with itself a times.

a / b means a divided by b if both a and b are numbers.

a //b means floor of a divided by b if both a and b are numbers. Gives a truncated
number. For example, 10//3 will give 3 and 5//10 will give 0.

a % b means remainder of the division by b if both a and b are numbers. This
may be referred to as mod. For example, 10%3 will give 1.

a ** b means exponent or a raised to the power of b. Like 23 .

In math there is a precedence order. Precedence is important when an expression
has a mixed set of mathematical operations and the question arises which should
go first.

2 + 5 * 4

This can be interpreted in two ways.

2 + 5 = 7

7 * 4 = 28

or

2 + 20 = 22

The two results are different.

The multiplicative operators (*, \, %,\\,**) have equal with each other and the
additive operators (+, -) have equal precedence with each other.

The multiplicative operators have higher precedence than additive operators.

The brackets are used to over ride precedence order. Therefore, a programmer
should note this when making expressions.

Binary operators (+, -, *, \, %,\\,**) are left associative while assignment
operator is right associative.

2 -5 -7

All are the same operators above. So do we start with the second subtraction or
the first? The operator being left associative the first subtraction is done first.

-3 -7 = -10

Brackets can again make a difference.

x = y = z

means give the value of z to y and then give the value of y to x.

In python comments are placed by the # sign.

# This is my first Python program

print ("Hello World")

It is very important to comment written code in any programming language. The
importance will be realized when programs become longer. Comments often
remind the programmer why a particular way of programming was used when
the program was initially written. Useful comments might give the programmer
a window into the algorithm used to make the program. This is very useful if the
programmer is looking at a code after a long time.

Errors

There are three types of errors that can take place when writing a program. This
is not specific to Python but to all programming languages.

Syntax errors - These are due typing mistakes or missing of a colon or a bracket
or a quote etc.

Run Time errors - These occur when the program runs. The program may not
have any syntax errors yet, run time errors can happen.

For example:

x= y * 2

but value of y has not been assigned.

Logical errors - These errors occur when the logic or algorithm intended has not
been properly programmed. The program may run without any errors but the
answer given might be wrong.

These errors are very important because ultimately every program bought or sold
depends on a reliable algorithm that is expected to give the correct result or
perform in accordance with specification.

Logical errors are harder to find than the two previous type of errors. It is best
for an independent programmer to check out the logic in a project once the
programmer submits his or her program into the test phase.

Division by 0 is a classical example of a logical error.

Increment and other Operators

In Python an increment can be done as follows:

x= x + 1

or

x+ = 1

x = x -1

or
x- = 1
x = x +5

or

x+ = 5

x = x * 5

or

x* = 5

x= x /5

or

x/ = 5

x = x * (y+z)

or

x * = (y+z)

Algorithm

The term algorithm was used when defining the errors earlier in the chapter. An
algorithm is the basis of any program. It is defined as a finite sequence of steps,
each step taking a finite length of time, to solve a problem or compute a result.

Thus every programming challenge has to be broken down into its tiniest steps
that can be managed. Then the programmer has to program each step integrating
each step to get the final result.

This type of methodology (waterfall type) may be slow down development in an
age of agile programming and rapid application development. However, the
good old method does work.

Let us write a program that will accept two numbers from the keyboard and add
them.

Algorithm:

1. Write a program to accept input in float format.

2. Add the two numbers.

3. Output the result.

The program will look like the one below:

print ("This progam will take two numbers and add them and show the result")
x= float(input("Please enter the first number\t"))
y= float(input("Please enter the secont number\t"))
sum = x + y
print("Total is",sum)

The output will be as follows:

This progam will take two numbers and add them and show the result
Please enter the first number 10
Please enter the secont number 25
Total is 35.0

Note that using the float function the input has been converted into float as input
gives string values only. The sum variable takes the result of the addition. The
use \t at the end of each input statement makes it possible to keep the input value
at a tab space.

Modules

An important point when dealing with math in Python is to remember that
Python requires import of modules to do certain math or other functions. For
example- the square root of a number. The math module needs to be imported
using the import keyword. This is very similar to Java and C++ include
statements.

To find the modules available upon installation of the interpreter go to the
Windows Apps and click on Python 3.6 Module Docs.


This will bring up a page similar to this. Included in the first part of the page is
the list of in built modules for that particular version of the Python interpreter.
The math module can be seen in the list. Clicking on the module name will open
up the features that need that module.


The implementation is as follows:

import math
x= float(input("Please enter the first number\t"))
answer = math.sqrt(x)
print("Total is",answer)

The output will be as follows:

Please enter the first number 25
Total is 5.0

Workshop:

1. Write down an algorithm to convert kilometers into miles and miles using a
float input format.

2. Write down a program using the math module to find the greatest common
divisor of two input numbers. (Hint: format is integer, click on math module to
use gcd(x,y))
Chapter 4. Conditions

The If condition is the most used condition in most programming language.
Python is no different in this respect.

The following are assignment operators in Python.

x == y means check to see if x is equal to y

x < y means x less than y

x > y means x greater than y

x <= y means less than or equal to y

x >=y means greater than or equal to y

x!=y means x not equal y

The If statement in Python is as follows:

If (condition) :

statement or block of statements.

Note: There is no then keyword but a colon (:) . The colon is required.

If (x >10):
print ("The number entered is greater than 10")

The If statement can also have an else component. The format is as follows:

If (condition):

statement or block of statements

else:

statement or block of statements.

Note: There is a colon (:) after else. It is required. There can be more than one
else statement.

If (x >10):
print ("The number entered is greater than 10")
else:
print ("The number entered is less than 10")

Boolean stands for True or False. Boolean logical operators are:

And

OR

Not

In the And logical operator both conditions have to be true to get true result. In
OR only one condition has to be true to get a true result. Not will give the
negation of a condition.

In And:

True and True = True
True and False = False
False and True = False
False and False = False

In OR:

True or True = True
True or False = True
False or True = True
False or False = False

In Not:

Not True = False
Not False = True

Example:

In this example a number (integer) is being requested and checked if it is in a
particular range.

Note: The indentation in the code. This is required.

x =int(input("Please enter a number between 0 and 10\t"))
if ((x>=0) and (x<=10)):
print("The number is in range")
else:
print("The number is not in range")

The output will look like this:

Please enter a number between 0 and 10 5
The number is in range

Like in any programming languages if conditions can be nested if the program
requires it that way. Nesting means an if condition inside another if condition.
The flow and count of conditions need to be followed to avoid logical errors.

Example:

x =int(input("Please enter a number between 0 and 10\t"))
if ((x>=0) and (x<=10)):
print("The number is in range")
if (x%2==0):
print("The number is even")
else:
print("The number is odd")
else:
print("The number is not in range")

It is very important in the code above to observe the indentation. In Python this
is very important.

The else statement of the main If condition matches it in terms of starting
position. The inner else statement attached to the second if statement matches its
position with the second if. The same goes for the print indentation.

In the above program the first if condition checks to see if the number which is
an integer is in the 0 to 10 range. If not the program stops with an out of range
message.
If the number is in range of 0 to 10 then the number is checked for evenness by
finding the remainder of the number divided by 2. If it is 0 then it should be an
even number and otherwise odd.

It is possible to have an if statement after an else:

Example:

x =float(input("Please enter first exam mark between 0 and 100\t"))
y = float(input("Please enter second exam mark between 0 and 100\t"))
z = float(input("Please enter third exam mark between 0 and 100\t"))
w = float(input("Please enter attendance mark between 0 and 100\t"))
avg = (x* 0.2) + (y*0.3) + (z * 0.4) + (w *0.1)
if avg>=90:
print ("A")
else:
if avg >=85:
print ("B+")
else:
if avg >=80:
print ("B")
else:
if avg >=75:
print("C+")
else:
if avg >=70:
print("C")
else:
if avg>=65:
print("D+")
else:
if avg>=60:
print("D")
else:
print("F")

Please note the indentation in each condition. In this example three exam grades
are being requested and a final grade calculated and letter grade found. The code
really needs some more conditions in that the input numbers need to be checked
for range compliance.

A sample input and output will look as follows:

Please enter first exam mark between 0 and 100 90
Please enter second exam mark between 0 and 100 89
Please enter third exam mark between 0 and 100 93
Please enter attendance mark between 0 and 100100
A

Workshop:

1. In the example of computing grade in the previous page add the necessary
code to check if the grades entered is between 0 and 100 only.

2. Write a code that will ask the user to enter a Celsius or Fare height number
and convert it accordingly. (Hint: The first input question should be Degree
Celsius or Fare height )

3. Modify the question in the last chapter that converted kilometers to miles to
first request the unit and then perform the needed calculations. That is if
Kilometers convert to mile and if Miles convert to Kilometers.

4. Given the following definitions: b1, b2, b3, b4 = true, false, x == 5, y < 5

Evaluate the following Boolean expressions:

(c) not b1
(f) not b4
(g) b1 and b2
(h) b1 or b2
(l) b1 or b4
(m) b2 and b3
(p) b1 or b2 and b3
(q) b1 and b2 and b3
(t) not b1 or b2 or b3
(u) not (b1 and b2 and b3)
(y) not (not b1 and not b2 and not b3)
(z) not (not b1 or not b2 or not b3)
X-X-X
Chapter 5. Loops

A loop is used to repeat a set of statements. Let us start with the while
statement.

The format for the while statement is as follows:

while condition:

do statements

exit when condition is false.

Note that like the if statement the while condition has a colon (:). It is required.

Example:

count= 1
while count <=5:
count = count +1
print (count)

Note the indentation. Python editors are very particular about indentation.

The output will look like this.

2
3
4
5
6

Since the variable count started with 1 the output starts with 2 (1 +1) and ends
with 6(5+1).

Let us look at an example where we a password is being requested. Only three
chances are being given to give the correct password.

Example:

count=0
while count<=2:
count = count +1
x =input("Please enter password")
if x =="Admin":
print ("Password correct")
break
else:
print("Password incorrect")

Note the indentation. The other keyword here is break. The break stops the loop
and exists out of it.

The For Loop

The for loop works in a range. These can be numbers or others. For now, let us
look at the for loop with numbers.

for n in range (1,10,1)
print (n)

The first number is the starting point, and the second is the end point. The third
is the step. In this case steps of 1. This can be any other number and can be
negative also if counting backwards.

Let us rewrite the password example with a for loop.

Example:

for n in range(0, 3, 1):
x = input("Please enter password")
if x =="Admin":
print("Password ok")
break

Note the indentation. This is very important in Python and can cause new
programmers a little bit of inconvenience if not properly done.

Workshop:

1. Write a program to print the prime values from 0 to 10.
Chapter 6. Functions

Functions make programming simpler by reducing the amount of coded lines.
Python like most languages have in built functions.

We have been using some of them in the previous chapters. Print, input etc
Within each module there will be additional functions defined which can be used
by the programmer directly. An example of this was the sqrt function mentioned
earlier.

Some of other functions (not the exhaustive list) in the math module are:

exp- Computes e raised a power: exp(x) = ex

log- Computes the natural logarithm of a number: log(x) = loge x = ln x

log10- Computes the common logarithm of a number: log(x) = log10 x

cos- Computes the cosine of a value specified in radians: cos(x) = cos x; The
other trigonometric functions include sine, tangent, arc cosine, arc sine, arc
tangent, hyperbolic cosine, hyperbolic sine, and hyperbolic tangent

pow Raises one number to a power of another: pow(x,y) = xy

Check for more in built function by clicking on the module name as shown in
chapter 3.

Similarly if one checks out the time module the clock function can be found
which gives the actual CPU time
or real time since the start of the process or since
the first call to clock().

Example:

import time
x=input("Enter a value")
start = time.clock()
elapsed = time.clock() - start
print("You took", elapsed,"to respond")

Output
You took 3.84962739456448e-07 to respond

Similarly, if one looks at the random module in Python there are functions to
create random numbers.

Example:

import random
x= random.random()
print (x)

This will print a value of x in the range of 0 to 1 randomly.

Example:

import random
x= random.random()
x = x * 100
print (x)

This will print random numbers in the range of 0 to 100

Example:

import random
i=0
while i < 100:
x = random.random()* 100
i= i+1
print (x)

Will print 100 random numbers.

If the call to seed is left out, the initial value in the sequence is based on the
system’s time.

Example:

import random
i=0
random.seed(53)
while i < 100:
x = random.random()* 100
i= i+1
print (x)

The seed value determines the sequence of numbers generated; identical seed
values generate identical sequences.

It may be noted that the import statements used in all examples so far includes
the name of the module only.

Another way to import is as follows

From math import sqrt , log

or

From math import *

which means import every function in the math module.

The advantage with these two methods versus importing just the module is that
if one just imports the module then the module name. function name has to be
used within the code.

math.sqrt

instead of just sqrt.

The choice is up to the programmer.

A function is called by a program when needed. Code that will be repeated often
can be made as function to increase the efficiency of coding.

A function has:

a name

a body

and parameters.
If the list of parameters is not present, then the function does not expect any
information from the calling program.

Functions can be called by other functions.

The def keyword followed by the name of the function creates a function.

The simplest functions do not have any parameters and returns nothing.

Example:

def function1():
x=int(input("Please enter a value\t"))
return x
# start of program that will call the function
print("This program will add two numbers using a function")
x = function1()
y= function1()
sum = x+y
print (sum)

The sample output is as follows:



This program will add two numbers using a function
Please enter a value 24
Please enter a value 23
47

The function is defined in the def part with the ending return statement. The
calling program is asking for a value of x and y on separate lines and adding
them to print the sum in the last line.

In the calling program after a function is called, the control goes to the next
statement after the function call.

Example:

def function1():
for i in range (0,5):
print(i)
# start of program that will call the function
function1()

and the output will be as follows:

0
1
2
3
4

The two examples of functions by the same name are different. In the first
example, the values from the function was transferred to the calling program.

In the second example there is no transfer of values between function and calling
program. The calling program just executed the function and the print in the
function produced the result.

In the example below the calling program will send to the function a value and
the function will respond according to that value.

Example:

def function1(n):
for i in range (0,n):
print(i)
# start of program that will call the function
function1(5)

The output will be the same as the second example:

0
1
2
3
4

The difference in this example is that the calling program is sending a value of 5
to the function which expects an input of one variable.

This is represented by 1 parameter in the function definition. The parameter is n.

The value of n which is 5 is then transferred to the function and the range and
thus it will print out the same result as the previous example when there was no
value send to the function.

A function can take several parameters.

Example:

def function1(m,n):
for i in range (m,n):
print(i)
# start of program that will call the function
function1(0,5)

The output is:

0
1
2
3
4

The difference here is that the calling program is sending two values as the
function has two parameters. The values are for the lower and upper bounds of
the range function.

The output remains the same as there is no change in the meaning of the
program.

Example:

import math
def fc(m,n):
x = math.gcd (m,n)
print ("The GCD value is:",x)
def rs(n):
x = math.exp(n)
print ("The value of e raised to exponent is:",x)
def main():
a=int(input("Please enter the first number to find GCD"))
b=int(input("Please enter the second number to find GCD"))
c =int(input("Please enter the number to raise e by"))
value= fc(a, b)
value2 = rs(c)
main()

In this example the calling program is a function called main and the main
function has to be called first followed by the calling of the other functions.

The inputs to the other functions - one to find the greatest common divisor and
the second to find the value of e raised to a number is obtained in the main
function via three inputs. The values were kept as integers because GCD is
always an integer.

The output sample looks like this:

Please enter the first number to find GCD10
Please enter the second number to find GCD29
Please enter the number to raise e by3
The GCD value is: 1
The value of e raised to exponent is: 20.085536923187668

Example:

import math
def fc(m,n):
x = math.gcd (m,n)
print ("The GCD value is:",x)
def rs(n):
x = math.exp(n)
print ("The value of e raised to exponent is:",x)
def main():
print ("Select function from menu by choosing the number of your choice.\n")
print ("1. Finding GCD\n")
print ("2. Finding E raised to power\n")
print ("\n")
w =int(input("Please enter the menu number and hit enter:\n"))
if (w == 1):
a=int(input("Please enter the first number to find GCD"))
b=int(input("Please enter the second number to find GCD"))
value= fc(a, b)
else:
if w==2:
c =int(input("Please enter the number to raise e by"))
value2 = rs(c)
main()

In the above example a menu has been added. The menu gives two options.
Option 1 when typed as 1 will lead to GCD function and when a user types 2 at
the prompt the second function to find the value of e raised to a number is
triggered.

The sample output looks like this.



Select function from menu by choosing the number of your choice.

1. Finding GCD

2. Finding E raised to power

Please enter the menu number and hit enter:
2
Please enter the number to raise e by3
The value of e raised to exponent is: 20.085536923187668

Variables defined within a function are called local variables. The variables in
the main function are also called local variables.

A local variable is such that its value is lost in between function invocations. It
may desirable to have a variable that lives as long as the program is running; that
is, until the main function completes.

In contrast to a local variable, a global variable is defined outside of all functions
and is not local to any particular function. Any function can legally access and/or
modify a global variable.

A variable can be made into a global variable by using the global keyword.

Example:

import math
def fc(m,n):
global x
x = math.gcd (m,n)
def rs(n):
y = math.exp(n)
print ("The value of e raised to exponent is:",x)
def main():
print ("Select function from menu by choosing the number of your choice.\n")
print ("1. Finding GCD\n")
print ("2. Finding E raised to power\n")
print ("\n")
w =int(input("Please enter the menu number and hit enter:\n"))
if (w == 1):
a=int(input("Please enter the first number to find GCD"))
b=int(input("Please enter the second number to find GCD"))
value= fc(a, b)
print ("The GCD value is:",x)
else:
if w==2:
c =int(input("Please enter the number to raise e by"))
value2 = rs(c)
main()

This is the same example of the GCD and exponent with a menu. The difference
here is that in the GCD function the x variable is now defined as global.

Thus the print function has been moved from the function to the main function
under the first if condition.

If the variable x is not defined as global such a print statement will lead to an
error.

The sample output is as follows:

Select function from menu by choosing the number of your choice.

1. Finding GCD

2. Finding E raised to power

Please enter the menu number and hit enter:
1
Please enter the first number to find GCD10
Please enter the second number to find GCD29
The GCD value is: 1

Remove the global definition of x and run the program.
The following sample output will be the result.

Select function from menu by choosing the number of your choice.

1. Finding GCD

2. Finding E raised to power

Please enter the menu number and hit enter:
1
Please enter the first number to find GCD10
Please enter the second number to find GCD20
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python36\functions.py",
line 24, in <module>
main()
File "C:\Users\User\AppData\Local\Programs\Python\Python36\functions.py",
line 19, in main
print ("The GCD value is:",x)
NameError: name 'x' is not defined

Default parameters can be given to functions. In the event that functions do not
receive values from the calling program the default values or parameters will be
the basis of execution of the function.

Example:

import math
def fc(m =10,n = 19):
x = math.gcd (m,n)
print (x)
def main():
fc()
main()

In this case the function will be executed using values 10 and 19.

Non-default and default parameters may be mixed in the parameter lists of
function declarations, but all default parameters within the parameter list must
appear after all the non-default parameters.

Thus the following is okay.

import math
def fc(m =10,n = 19):
x = math.gcd (m,n)
print (x)
def main():
fc()
main()

And this is okay

import math
def fc(m ,n = 19):
x = math.gcd (m,n)
print (x)
def main():
fc()
main()

but this is not ok.

import math
def fc(m =10,n):
x = math.gcd (m,n)
print (x)
def main():
fc()
main()

Workshop:

1. Write a program that will provide the input marks for three exams and
attendance at a college to a function. There should be two functions.

One should calculate the final mark based on the formula of 20% weight for
exam1, 30% for exam 2, 40% for exam 3 and 10% for attendance.

The second function should assign the letter grade based on the output of the
first function.
Chapter 7. List

A list is a collection of objects. The elements of the list are accessed by their
position or index in the list.

A list therefore is similar to an array in other programming languages. The list
can be global or local and must be defined before being used.

x = [1,2,3,4,5] is a list of integers values.

The list values appear on the right hand side of the assignment operator inside a
square bracket.

x=[ ] is an empty list.

If x = [ 1,2,4,6,7,8,9] is a list of integers then:

print (x) will print the entire list.

While

print (x[3]) will print the value 6 which is position 3 in the list. The first element
starts with the index 0.

An interesting difference between arrays in other languages and lists is the
assignment operator.

Lists can hold elements of different types. An important distinction when
compared to other programming languages.

x = [ 1,2,4,6,7,8,9, 'xyz']

print(x[7]) will result in the word xyz being printed.

Note that the word is kept in single quotes.

A list can hold integers, floating point numbers, words, functions and even other
lists.

Example:
x=[1,2,4,6,7,8,9,'word',[2,9,10]]
print (x)
print (x[8])

The output will be:

[1, 2, 4, 6, 7, 8, 9, 'word', [2, 9, 10]]
[2, 9, 10]

The eighth element of the list is a list and will be printed as a block.

Example:

x=[1,2,4,6,7,8,9,'word',[2,9,10]]
print (x)
print (x[8][2])

The output will be:

[1, 2, 4, 6, 7, 8, 9, 'word', [2, 9, 10]]
10

The value 10 is the second element of the list in index position 8 in the original
index x.

Example:

x=[1,2,4,6,7,8,9,'word',[2,9,10]]
print (x)
print (x[8][2]+ 1)
print (x[3]+1)

The output of the above code is as follows:

[1, 2, 4, 6, 7, 8, 9, 'word', [2, 9, 10]]
11
7

Notice that the value printed has been changed from 10 to 11 and 6 has changed
to 7. At this point the values in the original list has not been affected. They are
still in the list.
Example:

x=[1,2,4,6,7,8,9,'word',[2,9,10]]
print (x)
print (x[8][2]+ 1)
print (x[3]+1)
x[3] = x[3] +1
x[8][2] = x[8][2] +1
print (x)

The output will be:

[1, 2, 4, 6, 7, 8, 9, 'word', [2, 9, 10]]
11
7
[1, 2, 4, 7, 7, 8, 9, 'word', [2, 9, 11]]

The list has now changed. The change is permanent.

Example:

x=[1,2,4,6,7,8,9,'word',[2,9,10]]
y=[12,13,14,15]
print (x)
print (y)
x[3] = x[2] + y[2]
print (x)

In this case there are two lists x and y. The element of x is modified by adding an
element of x and element of y. In this case both have to be integers.

The output will be:

[1, 2, 4, 6, 7, 8, 9, 'word', [2, 9, 10]]
[12, 13, 14, 15]
[1, 2, 4, 18, 7, 8, 9, 'word', [2, 9, 10]]

Traversal is the process of moving from element of the list to the other. The loop
can be used to print out each element of a list.

The len function will give the length of a list.
Example:

x=[1,2,4,6,7,8,9,'word',[2,9,10]]
print(len(x))

The output will be:

9

The number 9 is obtained based on an index start at 0 and end at 8.

Example:

x=[1,2,4,6,7,8,9,'word',[2,9,10]]
for a in range(0,len(x)):
print (x[a])

In this code the range is set from index 0 to length of list in steps of 1.

The output will be:

1
2
4
6
7
8
9
word
[2, 9, 10]

Example:

x=[1,2,4,6,7,8,9,'word',[2,9,10]]
for a in range(len(x)-1, -1,-1):
print (x[a])

In this code the list is being printed backwards from the last index. The last
index is length of the index -1 because the starting index of a list is 0.

The output will be:
[2, 9, 10]
word
9
8
7
6
4
2
1

Example:

x=[1,2,4,6,7,8,9,'word',[2,9,10]]
y=[12,13,14,15]
print(x+y)

In this code there are two lists. The first one is mixed and the second one is all
integers. The + sign will concatenate the two lists and append the second string
to the first string.

The output will be:

[1, 2, 4, 6, 7, 8, 9, 'word', [2, 9, 10], 12, 13, 14, 15]

The statement x= x + [10] is valid but x = x + 20 is not.

The first statement x = x + [10] adds two lists together. Assuming that x has been
defined as a list.

The number 10 will be appended to the elements of x list.

The second statement x = x +20 is invalid because 20 is an integer and not a list.

Example:

lst = [1]
lst.append(2)
print(lst)

The following code will append the number 2 to the list which currently contains
only one element which is 1.
Example:

numbers = [1, 5, 2, 12, 14, 7, 18]
doubles = []
for number in numbers:
doubles.append(2 * number)
print (doubles)

In this code the doubles list will be filled with values bases on 2 multiplied by
the values of list numbers.

The output on the screen will be:

[2]
[2, 10]
[2, 10, 4]
[2, 10, 4, 24]
[2, 10, 4, 24, 28]
[2, 10, 4, 24, 28, 14]
[2, 10, 4, 24, 28, 14, 36]

Example:

greetings = ["Hello", "World"]

greetings2 = []
for i in greetings:
greetings2.append(i)
print (greetings2)

In the code above the string values of the greetings list is transferred to a new
list.

The output will be:

['Hello']
['Hello', 'World']

Example:

x=[1,3,4]
x.insert(1,2)
print (x)

The above code puts an object which in this case is the integer 2 in the position 1
in the index. The same can be used with strings.

Example:

x=[1,3,4]
x.remove(1)
print (x)

The above code will remove the value 1 from the list if such a value exists in the
list. If there are multiple values of 1 in the list it will remove the first occurrence
of 1 in the list.

Note that it is the value that is removed and this removal is not based on index.

Example:

x=[1,3,4]
x.pop(1)
print (x)

The following will remove 3 from the list because 3 is in position index 1 in the
list.

Example

def main():
n= input("Enter number of entries: "))
tmplist=[]
for i in range(n):
p=input("Enter name: " )
tmplist.append(p)
print(tmplist)
main()

In the above code the number of entries has to be entered from the keyboard.
The for loop then request that many inputs and then appends the string to the list
tmplist. If the input values need to be integer or float, then convert the input into
the needed format before running the code.

The output looks like this:

Enter number of entries: 5
Enter name: Adam
Enter name: Smith
Enter name: John
Enter name: Mary
Enter name: Ann
['Adam', 'Smith', 'John', 'Mary', 'Ann']

Example:

x=[1,2,3]
y =[2,3,4]
if x==y:
print("True")
else:
print("False")

In the above code two lists are compared. If they are the same the response will
be True and False otherwise.

Note the order is very important. Therefore, x[1,2,3] is not the same as y[3,2,1]
even the two lists have similar values.

Example:

x=[1,2,3,4,5,6,7,8,"word"]
y = x[0:4]
z = x[:]
w = x[4:8]
print (x)
print (y)
print (z)
print (w)

In the above code a list has been spliced. The way to do that is shown as x[0:4]
and x[4:8].x[:] means that the whole list needs to be taken. Therefore, z is the
exact copy of x. This is an easy way to copy a list.

The output will be:

[1, 2, 3, 4, 5, 6, 7, 8, 'word']
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7, 8, 'word']
[5, 6, 7, 8]

Example:

c=[3,5,2,1]
c.sort()
print(c)

The above code sorts a list.

The output will be:

[1, 2, 3, 5]

Example:

c=["Smith","Adam","Ann","Mary","Tim","Joseph"]
c.sort()
print(c)

The same sort applied to string entries.

The output will be.

['Adam', 'Ann', 'Joseph', 'Mary', 'Smith', 'Tim']

Example:

x=["Adam","Smith","Ann","Mary","Joseph"]
i = input("Please enter name to search for")
if (x.count(i) >=1):
print("The name is in the list")
print (x.count(i))
else:
print("The name is not in list.")

The code above will take a search word and check if the word is in the list and
return the number of occurrences of that search word.

Example:

x=["Adam","Smith","Adam","Mary","Joseph"]
print([i+1 for i, w in enumerate(x) if w == "Adam"])

The following code will find all instances of the occurrence of word in a list. The
keyword here is enumerate. The code above will give index positions in the list
where the word occurs.

Example:

x=["Adam","Smith","Adam","Mary","Joseph"]
y=[1,2,4,5,4,7,5]
print([i+1 for i, w in enumerate(x) if w == "Adam"])
print([i+1 for i, w in enumerate(y) if w == 5])

The same code as the previous one except here the second print statement looks
for the indexes of the integer 5.

The output will be:

[1, 3]
[4, 7]

Example:

x=[1,2,3]
x.reverse()
print(x)

The following code will reverse the list. The keyword is reverse().

The output will be:

[3, 2, 1]

Example:

x=["Adam","Smith","Adam","Mary","Joseph"]
y=[1,2,4,5,4,7,5]
x.clear()
print (x)
print (y)

In the code above the clear() option for a list will clear the entire list of its
contents.

The output will be:

[]
[1, 2, 4, 5, 4, 7, 5]

Example:

x=["Adam","Smith","Adam","Mary","Joseph"]
for i in range(len(x)-1,-1,-1):
if x[i] =="Adam":
x.pop(i)
print (x)

The above code will delete all multiple values of the same string or input in a
list.

The output will be:

['Adam', 'Smith', 'Mary', 'Joseph']
['Smith', 'Mary', 'Joseph']

Example:

x=["Adam","Smith","Adam","Mary","Joseph"]
x = set(x)
print(x)

The following code will give a unique list of items. The keyword is set().

The output will be:

{'Mary', 'Joseph', 'Smith', 'Adam'}
Chapter 8. Date & Time

Programs related to time in Python require the time module. In the chapter on
expression the method to check on the modules was shown.

Therefore, let us start on an example:

import time;
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)

The output will be:

Number of ticks since 12:00am, January 1, 1970: 1513689339.5754588

Date before January 1 1970 may be a little tricky to handle.

Example:

import time;
localtime = time.localtime(time.time())
print ("Local current time :", localtime)

This code will give the local time.

The output is:

Local current time : time.struct_time(tm_year=2017, tm_mon=12, tm_mday=19,
tm_hour=16, tm_min=18, tm_sec=6, tm_wday=1, tm_yday=353, tm_isdst=0)

From the above line which is not so user friendly one can understand that the
time function is made up of individual parts as shown in the bracket above.

tm_year means the year as a four digit number

tm_mon means the month in 2 digits

tm_mday means the day of the month (up to 31)

tm_hour means the hour of the day (from 0 to 23)

tm_min means the minute (from 0 to 59)

tm_sec means the seconds (from 0 to 61-where 61 is leap seconds)

tm_wday means the workday (from 0 to 6)

tm_yday means the day of the year (1 to 366)

tm_isdst means the daylight savings.

All this information may not be needed for a user.

Example:

import time;
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)

The code above will give the local time in an understandable and shorter format
than the previous one.

The output will be:

Local current time : Tue Dec 19 16:25:38 2017

Example:

import calendar
cal = calendar.month(2017, 12)
print ("This month in details")
print (cal)

The code above imports the calendar module and shows the days in the month of
December in the year 2017.

To change for a different month, change 12 to the appropriate month number and
change the year accordingly.

The output will be:

This month in details
December 2017
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Example:

import calendar
cal = calendar.calendar(2017,w=2,l=1,c=6)
print(cal)

calendar.calendar(year,w=2,l=1,c=6)
Returns a multiline string with a calendar for the year selected. It will be
formatted into three columns separated by spaces set by the variable c. w is the
width in characters of each date. l is the number of lines for each week.

The output will be:

3 month by 4 rows of a calendar.

Example:

import calendar
cal = calendar.firstweekday( )
print(cal)

This will give the result 0. Returns the current setting for the weekday that starts
each week. In Python the working day starts on a Monday.

Example:

import calendar
cal = calendar.isleap(2018)
print(cal)

The output here is False. But the code can be used to check if a particular year is
a leap year or not.

Example:

import calendar
cal = calendar.leapdays(2017,2022)
print(cal)

This will give 1. The number of leap days between two years and in this case
between 2017 and 2022.

Example:

import calendar
cal = calendar.month(2017,12,w=2,l=1)
print(cal)

This will give the details for the month of December 2017. This was seen earlier
but the two variables w=2 and l=1 were not that in.

W is width for each date in the month and l is the number of lines for each week.

Example:

import calendar
cal = calendar.monthcalendar(2017,12)
print(cal)

Will give a set of intervals representing each week of the month.

Example:

import calendar
cal = calendar.monthrange(2017,12)
print(cal)

The output will 4,31 meaning 31 days in the month the starting day of the month
was 4 which is Friday.

Example:

import calendar
cal = calendar.setfirstweekday(6)
print(cal)

Sets the first day of each week to weekday code weekday.

Weekday codes are 0 (Monday) to 6 (Sunday).

Example:

import calendar
cal = calendar.weekday(2018,7,9)
print(cal)

The value will be 0 for Monday. This code will give the day (Sun,Mon..) of a
particular date in a specific year.

By the way the choice of the date above was not arbitrary.

Example:

import time
cal = time.timezone
print(cal)

This will give the offset in seconds of the local time zone (without DST) from
UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).

Example:

import time
cal = time.altzone
print(cal)

The offset of the local DST timezone, in seconds west of UTC, if one is defined.

This is negative if the local DST timezone is east of UTC (as in Western Europe,
including the UK). Only use this if daylight is nonzero.
Chapter 9. Files

So far the methods of input and output that was seen in the previous chapters
were print and input().

Python allows printing to the screen using the print function.

Example:

print("This is a print statement")

The input from the keyboard was obtained by using the input function.

x = input("Please enter a value")

This above assumes that x is expecting a string variable because by default input
only takes in a string.

The input can be changed to a int or float format by putting that command in
front of the input as follows:

x =int(input("Please enter a value")

for integer input

and

x = float(input("Please enter a value")

for float input.

Therefore , the keyboard and the screen has been used so far. Let us look into
files.

Files can be opened and closed by Python.



The syntax for opening a file is as follows:

file object = open(file_name[,access_mode][,buffering]

File_name − The file_name argument is a string value that is the name of the file
to be accessed.

access_mode − The access_mode determines the mode in which the file has to
be opened, i.e., read, write, append, etc. The default file access mode is read (r).

buffering − If the buffering value is set to 0, no buffering takes place. If the
buffering value is 1, line buffering is performed while accessing a file.

If an integer greater than 1 is used, then buffering action is performed with the
indicated buffer size. If negative, the buffer size is the system default(default
behavior).

Example:

x= open("sample.txt", "wb")
print ("Name of the file: ", x.name)
print ("Closed or not : ", x.closed)
print ("Opening mode : ", x.mode)

The output will be:

Name of the file: sample.txt
Closed or not : False
Opening mode : wb

The different modes for opening are:

r - read only with file pointer at the beginning of the file.

rb - read only in binary format. Pointer at the beginning of the file.

r+ - read and writing and pointer at the beginning of the file.

rb+ -read and writing in binary format.

w - opens file for writing only. will create the file if it does not exist and
overwrites existing file.

wb - opens a file for writing in binary mode. overwrites existing file and creates
new file if file does not exist.
w+ - opens file for writing and reading. will create the file if it does not exist and
overwrites existing file.

wb+ - opens file for writing and reading in binary mode. will create the file if it
does not exist and overwrites existing file.

a - opens file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.

ab- opens file for appending in binary mode. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.

a+ - opens file for appending and reading. The file pointer is at the end of the file
if the file exists. That is, the file is in the append mode. If the file does not exist,
it creates a new file for writing.

ab+ -opens file for appending and reading in binary format. The file pointer is at
the end of the file if the file exists. That is, the file is in the append mode. If the
file does not exist, it creates a new file for writing.

Once a file is opened the following methods can be used to get further
information.

file.closed returns true if file is closed.

file.mode returns the mode in which file is opened.

file.name returns the name of the file.

A file is closed by the following syntax.

fileobject.close()

Example:

x= open("sample.txt", "wb")
print ("Name of the file: ", x.name)
print ("Closed or not : ", x.closed)
print ("Opening mode : ", x.mode)
x.close()
The file object in the above example is x.

Now to write a line of text into the sample.txt file do as follows:

x= open("sample.txt", "w")
print ("Name of the file: ", x.name)
print ("Closed or not : ", x.closed)
print ("Opening mode : ", x.mode)
x.write("Python is a fun language.\nYeah its fun!!\n");
x.close()

The output will be as follows:

Name of the file: sample.txt
Closed or not : False
Opening mode : w

and the details of sample.txt file is as below:



To read from a file do as follows:

x = open("sample.txt", "r+")
str = x.read();
print ("Read String is : ", str)
x.close()

The output will look like this:

Read String is : Python is a fun language.
Yeah its fun!!

Note that this is what was written into sample.txt earlier.

In the str line where x.read() is written no count number was entered within
brackets indicating that the whole text has to be read.

The current position of the pointer can be obtained by using the tell() function as
in x.tell() or fileobject.tell().

Files can be renamed using the rename function.

import os
os.rename("sample.txt","sample2.txt")

when running this code the original file must be closed.

A file can be removed by using the remove keyword.

import os
os.remove("sample2.txt")

To create a directory:

import os
os.mkdir("Sample")

To remove a directory:

import os
os.rmdir("Sample")

To change a directory: import os
os.chdir("/home/directoryname")
Chapter 10. Database

The previous chapter looked into files. These files were text files and they are
the simplest kind of databases. A database is place to store data that will be
converted into information at the time of request of the user.

Data in its row form has no meaning but combined it becomes a useful tool for
everyone.

Python comes integrated with a database. This database is a RDBMS and is
called SQLLite. The other RDBMS in the market are MS Access and SQL
server from Microsoft , Oracle, MySQL to name a few.

Basically all RDBMS have common features. The most important among them
is the language which is SQL or structured query language.

Files as databases maybe easy to deploy but they lack security and are prone to
virus and hacking. There are no fool proof methods but the database provides a
layer of extra security besides the network level security features.

The database is always kept in the back end and therefore access to it is through
other interfaces.

SQL has four main key words or actions. These are:

Select - to get information from the tables that form the RDBMS.

Insert - to put data into the tables that form the RDBMS.

Update - to change the data in the tables of the RDBMS.

Delete - to remove data in the tables of the RDBMS.

There are other operations which may be allowed by the database administrator
but these are the primary actions a user will do against the tables of a database.

Out of the four the most common and most used is Select. The other three may
be restricted by the administrator for security reasons and given based on the
user’s profile and security clearance levels.

The SQLLite is a small database that is very famous. The SQLLite project is
sponsored by Bloomberg and Mozilla.

The fact that SQLLite is integrated into Python can be taken for granted. This
book was based on Version 3.6.3 of Python.

The first thing to do when dealing with database and programming languages is
to make sure there is a connection to the database.

In this respect let us write the following program.

import sqlite3 as lite
import sys
con = None
try:
con = lite.connect('test.db')
cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()')
data = cur.fetchone()
print ("SQLite version: %s" % data)
except lite.Error:
print ("Error %s:" % e.args[0])
sys.exit(1)
finally:
if con:
con.close()

Run the program.

The output is as follows:

SQLite version: 3.14.2

Thus there are two things we come to understand out of this. One that SQLLite
is integrated to the Python installation and is connectable and thereby on
standby.

The other is that the version number is in this case 3.14.2.

The version number you get does not have to match this. However, if one is
using version 3.6.3 it should.

In the code above the import statement needs to be present to tell Python that we
are going to write a code dealing with the SQL Lite database.

There is a second import statement.

The program is connecting to a test.db database before checking the version of
the database.

The test.db is already there and so no need to wonder which database that is.

The whole code is enclosed in a try and except package. This is called an
exception handling code.

The same code above is repeated below without the exception handling package.

import sqlite3 as lite
import sys
con = None # initializing connection to database
con = lite.connect('test.db') # connects to test database.
cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()') # checks for the version of
database
data = cur.fetchone()
print ("SQLite version: %s" % data)
con.close()

The next step is to create a table and new database to place it in.

The following lines will create a new sample database and sample table in it.

import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("create table sample(id int, name text, job text)")

In this execute line the table sample has three columns or fields.

The appropriate term is fields. The first field is id which is of type integer and
the others name and job of type text.

run the program.

Now let us add a few lines into the sample table in the sample database.

The following lines will do that.

import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("insert into sample values(1,'Adam','Lawyer')")
cur.execute("insert into sample values(2,'John','Manager')")
cur.execute("insert into sample values(3,'Smith','Accountant')")

In this case the insert command in SQL is being used to insert each row of the
table. Each row in a table supplies information to the user.

There are three rows in the sample table in the sample database.

Now that the database has some data, we need to retrieve them. Retrieval is the
main function when it comes to a database because without retrieval a database
will be useless.

The select command of SQL will be used here.

import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("select * from sample")
rows = cur.fetchall()
for row in rows:
print (row)

After the rows are obtained in the cursor it is transferred to a rows list from
which each row is printed.

The output of this code is as follows:

(1, 'Adam', 'Lawyer')
(2, 'John', 'Manager')
(3, 'Smith', 'Accountant')

Now let us try to modify the select query such that we print only a person who is
a manager. That means job = Manager.

The code will be as follows:

import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("select * from sample where job='Manager'")
rows = cur.fetchall()
for row in rows:
print (row)

The only change is in the select statement where a condition job='Manager' has
been added.

This syntax is not a part of Python but that of SQL.

The output now will be:

(2, 'John', 'Manager')

Let us look into the table created in the sample database. The table sample has
three fields.

If one enters the same row twice or thrice it will be inserted into the table and
will make the database in efficient.

In SQL there is a key called primary key. A primary key is a field that cannot
have a null value and must have a unique value.

If this is the criteria, then in the sample table the only field that qualifies as a
primary key is id. Each person will have a unique id.

Thus let us recreate the table sample again. Let us drop it first.
import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("drop table sample")

The sample table does not exist anymore. Now run the previous code to insert
the values but with a small modification as follows:

import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("create table sample(id int primary key, name text, job text)")

run the program.

Now insert four lines into the sample table. One of them a repetition as follows.

import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("insert into sample values(1,'Adam','Lawyer')")
cur.execute("insert into sample values(2,'John','Manager')")
cur.execute("insert into sample values(3,'Smith','Accountant')")
cur.execute("insert into sample values(1,'Adam','Lawyer')")

Run the program. An error message showing integrity violation will come up.
The output could be like the one below:

Traceback (most recent call last):
File "C:/Users/User/AppData/Local/Programs/Python/Python36/database.py",
line 9, in <module>
cur.execute("insert into sample values(1,'Adam','Lawyer')")
sqlite3.IntegrityError: UNIQUE constraint failed: sample.id

Now run the code again without a repetition.

import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("insert into sample values(1,'Adam','Lawyer')")
cur.execute("insert into sample values(2,'John','Manager')")
cur.execute("insert into sample values(3,'Smith','Accountant')")

It will run smoothly. Let us run the select statement again.

(1, 'Adam', 'Lawyer')
(2, 'John', 'Manager')
(3, 'Smith', 'Accountant')

In the following code Smith with id =3 is getting a promotion to Senior
Accountant.

import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("update sample set job='Senior Account' where id='3'")
cur.execute("select * from sample")
rows = cur.fetchall()
for row in rows:
print (row)

The update statement changes the job title of Mr.Smith and then the select
statement prints out the new information.

There is no need to print the entire table. The select statement could be select *
from sample where id='3'. Try it.

The output will be for the above code.

(1, 'Adam', 'Lawyer')
(2, 'John', 'Manager')
(3, 'Smith', 'Senior Account')

The following code will remove John from the list completely.

import sqlite3 as lite
import sys
con = lite.connect('sample.db')
with con:
cur = con.cursor()
cur.execute("delete from sample where id ='2'")
cur.execute("select * from sample")
rows = cur.fetchall()
for row in rows:
print (row)

The output after the select statement will look like this.

(1, 'Adam', 'Lawyer')
(3, 'Smith', 'Senior Account')

Workshop:

1. Create a connection to the SQLLite database on your computer and find its
version.

2. Create a table called users in a database called employee. The table should
have the following fields.

ID – integer, Name- text, Job – text , Salary – float, Location - text

The primary key is ID. Populate it with at least five rows of unique data.

3. Run a query that will update salary for the third person in your list by a factor
of 100. Use the update command of SQL.

4. Is there way to update the salaries of all employees by a factor of 5%. Find the
SQL statement for that and execute it using Python.
Appendix I. References

I compiled this book for a laboratory class associated with programming
languages.

The following sources were referred to making the text part of this book.

Python Programming: An Introduction to Computer Science, John Zelle, 2003

Python Essential Reference, David M Beezley, ISBN-13: 978-0672329784

Core Python Programming, Wesley J Chun, ISBN-13: 978-0132269933

Beginning Python: From Novice to Professional, Magnus Lie Hetland, ISBN-
13: 978-9380501604
A Hands-On, Project-Based Introduction to Programming, Eric Matthes, ISBN-
13: 978-1-59327-603-4

Das könnte Ihnen auch gefallen