Cyberpunk University - Python - The No-Nonsense Guide - Learn Python Programming Within 12 Hours! (2017, CreateSpace Independent Publishing Platform) PDF
Cyberpunk University - Python - The No-Nonsense Guide - Learn Python Programming Within 12 Hours! (2017, CreateSpace Independent Publishing Platform) PDF
Press Enter.
This is what you should see:
Fig 1.5 Hello World!
print (product_ID)
print (product_price)
print (product_name)
In this exercise, you assigned the variables product_ID,
product_price, and product_name different values then
commanded the interpreter to display those values using
print. If you get an error, check and re-check your spelling
and commas and ensure everything is EXACTLY as it
appears. The result should look like this when you run
Ex1.py script:
The variables product_ID, product_price, and product_name
are assigned values 10, 2.5, and “Soda” respectively.
Edit the code in Ex1 to assign the variables values as shown
above then save the .py file and run it on the terminal. Does
the program behave the same?
2.2 Standard Data Types
Python has five standard types of data that define
operations that can be carried out on them as well as how
they are stored in memory. They five data types we will
cover in this section are:
Numbers
Strings
Lists
Tuples
Dictionary
Comments
2.2.1 Numbers
Numbers are essentially numeric values that are created
when a value is assigned to them. For instance, when you
create a variable my_age and assign it a value of 22, the
number 22 is created. There are three different types of
numbers you will be working with:
Integers (int) – These are long integers e.g. 1, -12, 02.00,
372, 18374, -1862, -0x260, 100000,
Floats (float) – These are numbers with decimal points e.g.
1.0, 0.5, -734.2, 13.90201, 32.3+e18, -32.54e100, 0490
Complex – These are numbers with ordered pairs of real
floating-point numbers written x + yj where j is an
imaginary unit. How complex do 3.14j, 45.j, 9.322e-36j,
876j, -.6545+0J, 3e+26J, 4.53e-7j look?
In the next chapter, we will dive deeper into numbers and
even use various operators to manipulate them.
2.2.2 Strings
Think of these as plain characters within single or double
quotation marks. A string is created by enclosing text and
numbers in either single or double quotes and can be
declared with a star. You will get to use strings a lot.
Ex2
#Ex2
Start Python Shell and enter the following string operations
to see what they do:
Here is what you should see when you run the script.
Hello World!
H
llo World!
2.2.3 Lists
A list contains separate items enclosed within square
brackets [ ] and are separated by commas. The values on a
list can be accessed using the same slice operators [ ] and
[:] just like with strings. Also, just as with strings, the + sign
is the concatenation while the * is the repletion operation
symbol.
Ex3
Start your code editor and enter the following code as it
appears:
#Ex3
print (fruits_list) #Displays the entire fruits_list list
print (fruits_list[0]) #Displays the first item in the list
When you run the script above, the result should look like
this:
2.2.4 Tuples
Tuples are a lot like lists in that they are a collection of
sequential data. A tuple is made up of values separated by
commas and enclosed in parentheses (). The main
difference between lists and tuples (besides one using
square brackets and the other parentheses) is that the
items defined in a list can be changed (updated) while those
in tuples cannot. Most operations on tuples are similar to
those of lists.
Ex4
#Ex4
Like strings and lists, tuple indexes start at 0 and can be
concatenated, sliced, and so on.
2.2.5 Dictionaries
In Python, a dictionary is a kind of hash table type that
works like associative arrays with key-value pairs enclosed
in curly braces { }. A dictionary can have almost any type of
data but typically it contains numbers and strings. Values
are often any arbitrary Python objects.
Ex5
Dictionaries
#Ex5
foods = {"fruit" : "apple", "vegetable" : "kale", "meat" : "beef", "carb" :
"cereal"}
print (foods)
print (foods["vegetable"])
Dictionaries do not have any concept of order when it
comes to elements and can be said to be “out of order” or
simply “unordered”. In hour 7, we will look at dictionaries
more exhaustively.
2.2.6 Comments
Comments are not particularly a data type, but every
programming language needs them because they are
essential to human developers. Comments, denoted with
the hash character (#), are used to tell the human reader
what a particular code means or does in plain language.
They are also used to disable parts of the program when
you need to remove them temporarily. The best example of
using comments is demonstrated in Ex3. Note that Python
ignores everything in a line of code beginning with the #. In
fact, your text editor should color comments differently to
show you what the interpreter will ignore.
Hour 3: User Input, Basic Math, and
Output
Every computer program is written to solve a problem, and
as such, it must accept some form of input from the user. In
most cases, the input is through the keyboard. For this
purpose, Python provides the input() function to enter data.
The prompt string is an optional input parameter you will
learn about later.
3.1 input ()
When you use input(), the program flow will stop until the
user enters the expected data and press enter when the
input function is called. The input text will be displayed on
the screen.
The input the user enters is returned as a string without
modification. Other functions such as casting and eval that
you will learn later are used to transform the data into a
different depending on the purpose of the program and
variables declared.
Ex6
Input
Write the following code:
#Ex6
print ("You are ", name, "from", location, "and you are", age, "years old.")
Save the script in your practice files folder and run it. This is
what you should see:
name = input("What is your name: ")
print ("You are ", name, "from", location, "and you are", age, "years old.")
You are John from London and you are 22 years old.
3.2 More Numbers
Considering that numbers are immutable data types,
changing the value of an assigned number data type will
result in a newly allocated object. This also means that
when assign a value to a number object, a new one is
created. For instance:
distance = 100
time = x = 6
Example 3.2
In the above example, the value that the user enters will
replace the value of x which is 6.
apples = 9 / 3 + 1
peaches = 4 * 3 - 2
print ("Mangoes", mangoes)
print ("Apples", apples)
print ("You have eaten ", mangoes_eaten, "mangoes,", apples_eaten, "apples,
and ", peaches_eaten, "peaches.")
In this exercise, first we use random numbers to calculate
how many fruits we have then we display the result. The
program then prompts for input (integers) of the number of
fruits left which it uses to calculate how many we have
eaten. Follow each line of code to understand what it does
and where you could improve fully.
3.2.3 Comparison Operators
So far we have looked at and used mathematical operators.
Python allows you to compare values on either side of an
equation and decides how they relate. Here is a breakdown
of these relational operators:
The condition becomes true if the (x ==
== equal
values of two operands are equal y)
The condition becomes true if the
not
!= values of two operands are not (x != y)
equal
equal
The condition becomes true if the
Greater
> value of the left operand is (x > y)
than
greater than that of the right
The condition becomes true if the
Less
< value of the left operand is less (x < y)
than
than that of the right
Greater The condition becomes true if the
(x >=
>= than or value of the left operand is equal
y)
equal to or greater than of the right
Less The condition becomes true if the
(x <=
<= than or value on the left operand is equal
y)
equal to or less than that of the right
Ex8
#Ex8
if (height == length):
shape = "square"
else:
shape = "rectangle"
area = (height * length)
print ("The shape is a", shape, "with an area of ", area, "and perimeter of ",
perimeter)
Can you change the data types for height and length to
integer and see what answers you get?
Precedence Operation Definition
Highest () Anything in parentheses is
computed first.
** Exponentiation
-x, +x Negation
*, /, %, // Multiplication, division,
modulo,
+, - Addition, subtraction
<, >, <=, relational operators
>=, !=, ==
not Logical
and Logical
Lowest or Logical
x = 87 / 3 * 2 - 7 + 6
#1. 87 / 3 = 29
#2. 29 * 2 = 58
#3. 58 + 6 = 64
#4. 64 - 7 = 57
print ("89/3*2-4+6=", x)
#Example 2
x=9+5/3*3
#1. 9 / 3 = 3
#2. 3 * 3 = 9
#3. 9 + 5 = 14
print ("9+5/3*3=", x)
#Example 3
x = 12 % 2 + 8 / 2 * 3
#Explain how this operation is carried out and check your answer
print ("12%2+8/2*3=", x)
#Example 4
x = (8 - 12) - 10 * 4
#Explain how this operation is carried out and check your answer
print ("(8-12)-10*4=", x)
#Example 5
x = 21 / 3 % 4 * 2 ** 3
#Explain how this operation is carried out and check your answer
print ("21/3%4*2**3=", x)
3.3 Output: Printing to the screen
The most straightforward way to output information is by
using the print() statement. It passes none to multiple
expressions separated by commas or combined by a plus
sign (+) to display. This statement converts expressions into
a string and displays the result as a standard output like
this:
Ex10
#Ex10
print ("Python is an amazing language, isn't it?")
string1 = "yes"
print (string1, string2, ".")
print (string1+string2+".")
When you run this script, this is what will be displayed on
your terminal screen:
C:\Python35-32\Exfiles>python Ex10.py
yes it is .
yesit is.
Have you noticed any difference in how the output is spaced
when you use comma or plus symbol to combine strings of
text?
Hour 4: If-Statements
When you need a program you are writing to do something
20 times, you will not force the user to repeat instructions
20 times, you use iteration.
Iteration is when you write a code that tells the computer to
repeat a task defined between two points until a certain
condition is met.
Ex11
#Ex11
#This is a program to determine which fruits are more based on user input.
Ex12
Here is a simple exercise to determine whether a number a
user enters is positive or negative.
#Ex12
if num > 0:
if num < 0:
print ("The number is a negative number!")
This if statement includes a Boolean text condition
expression. If the result of the test returns true, the print
block of code is executed. If the test returns a false, the
block is ignored.
4.2 Single IF Statement
If you write a block of code that consists of only one IF
statement, it is acceptable to put the code condition in the
same line as the header statement. For example:
num = 100
if price < 100:
In this exercise, the program asks the user to enter the price
of an item then calculates the discount it qualifies for based
on the price (5% for items worth less than 100 and 10% for
the rest) then displays the discount and the final price of the
item.
4.4 Elif
A step from the If…else statement is the Elif. As you may
have guessed already, Elif is essentially a combination of
Else and If in one statement. This statement allows the
program to check multiple expressions and executes a block
of code when one of the conditions returns TRUE. If all the
conditions are FALSE, the block of code will be ignored.
Unlike If… Else which can only have one statement, Elif
allows an arbitrary number of Elif statements following If.
Ex14
#Ex14
elif price < 1000:
else:
discount = (price * 0.25)
print ("The discount is ", discount)
4.5 Nested IF Statements
In situations where you want to write a program that checks
for another condition after a condition is resolved to be True,
you can use a nested IF construct. The nested if has the If…
Elif…. Else construct within other If… Elif… Else constructs.
Ex15
#Ex15
#A program to check if a number is divisible by 3 and 2
if num % 2 == 0:
if num % 3 == 0:
else:
if num % 3 == 0:
else:
print ("Not divisible by 2 not by 3")
Run the code above and leave comments to understand
how this construct works.
Hour 5: Loops
In the last chapter, we saw how the If statement could be an
incredibly useful tool in writing a program with conditions to
check. However, the If statement and its variations have a
problem in that they are one-time operation statements.
As an example, picture a password entry screen. When an If
is used, the user can only enter a correct or incorrect
password without the option to return to the previous screen
if the password is wrong.
Loops have almost the same type of functionality as the If
statements except with the advantage of being able to
repeat a block of code until you break the cycle. In the
example above, with a good loop statement, the user would
be taken back to the password screen when they enter an
incorrect password instead of just ending the program. A
loop can take the user back to the input statement to start a
process over.
Fig 5: Loop
5.1 The while loop
A while loop statement repeatedly executes a statement or
a block of indented code as long as a given condition is true.
Let us begin this section with a simple program. Write the
following code and run it, then try to understand what is
happening:
Ex16
#Ex16
x=0
You should see a result like this when you run Ex16.py
script:
1
2
3
7
8
10
Here is an explanation of what this short code does:
x=0 #x now equals 0
while (x < 10): #As long as the value of x is less than 10, do this:
x = x + 1 #Add 1 to the value of x
print (x) #Display the new value of x and return to first indent.
Ex17
#Ex17
#Countdown from x to 0
x = int(input("Enter a value between 1 and 10: "))
while x != 0:
print (x)
x=x-1
Use # comments to explain what each line of the code
above does.
5.1.1 Else Statement with While
The Else that we used with IF statement is also used when
working with loops. When the Else statement is used with
the While loop, the statement after it is excluded when the
statement returns Boolean value false.
In the next exercise, you will use Else with the While
statement to understand how it works.
Ex18
#Ex18
#Countdown from any number greater than 3
x = int(input("Enter a number greater than 3: "))
while x > 3:
x=x-1
print ("The count is ", x)
else:
print ("The count is less than 3")
It is advisable that you use the while loop sparingly while
developing Python programs. The for loop that we will look
at next is the more preferred loop to use in most situations.
5.2 The for loop
The For loop requires some repeatable objects like a set or
list to execute a sequence of statements and abbreviate the
code that handles the loop variable.
Example:
x = range (0, 10)
for count in x:
print (count)
The output of this code will look a lot like that in Ex14, yet
the program code is very different. The first line introduces
the range function which uses two arguments in the format
range(start, finish) with start and finish being the first and
last numbers in range.
Another way we could have written that code is:
for x in range(10):
The range() function allows the program to access a set of
items efficiently. It executes a loop that runs a fixed number
of times when used with the For statement. When the Start
value is not declared, the program index begins at 0.
Ex19
#Ex19
As we saw earlier, the For statement is an iterator based
loop that steps through items in a list, tuples, string, or
dictionary keys and other iterable data structures. In this
case, the program assigns the list in fruits variable indexes
beginning at 0 and follows a sequence of the items in this
syntax:
for <variable> in <sequence>:
<statements>
<statements>
else:
<statements>
Ex20
#Ex20
numbers=[1,3,45,49,48,69,37,21,71,41,31]
for num in numbers:
if num %2 == 0:
print ("The list contains an even number")
break
else:
print ("The list does not contain even numbers")
Find out what happens when you edit out the even number
48 in the numbers list above and run the code.
The program should display “The list does not contain even
numbers.”
5.4 Loop Control Statements
When you want to change execution from a normal
sequence in a loop, you use loop control statements. Python
supports pass, break, and continue loop control statements.
Let us explore what purpose each of these statements
serves.
numbers = [3,5,2,7,0,4,3,8,10]
if number == 0:
pass
print ("Bye!")
while age < 0 or age >130:
print ("Attempt {0}: Age not valid.".format(counter))
age = int(input("How old are you? "))
counter = counter + 1
if counter >=5:
age = 0
break
else:
print ("You are aged {0}. You were born in ".format(age), dob )
In this exercise, the program expects the user to enter
his/her age in years and only allows five attempts. The age
must be between 0 and 130. The counter records the
number of invalid entries, and when it gets to 5, it sets the
age as 0 and breaks the loop. When the loop is broken, the
very next print statement is executed. If the circuit is not
broken, the block after Else is run.
if num < 0:
print ("Please enter a positive number only.")
continue
elif num == 0:
print ("Exiting program...")
break
num_cube = (num ** 3)
This exercise combines the continue and break loop control
expressions, albeit in different blocks of code. Can you
explain what they do?
5.5 Indentation
For a code you write to be executed right, all the conditions
must be met, including proper indentation. This is
particularly important when it comes to loops and iteration.
For instance, to loop five lines of code using the while loop,
all the five lines must be indented by four spaces or one tab
about the beginning of the loop statement.
This is a vital programming practice no matter what
language you use. Python requires that you properly indent
your code, otherwise your program will encounter errors. In
the example below, notice how uniform the indentation is
and try to figure out which lines are related.
Ex24
#Ex24
while x > 0:
print (x)
if x > 5:
elif x % 2 == 0:
else:
x=x-1
print ("The value of x is now less by 1.")
print ("The number is greater than 0!")
Hour 6: Functions
If you are new to software development, you will be
surprised by just how much source code of a program is
general and re-usable. Copy-pasting is a very common
practice in programming because many functions are
similar and instead of re-inventing the wheel each time you
write a program, you can just use what someone else has
invented.
These include verifying that certain numbers or data types
are acceptable if a string fits a particular requirement, or
that a print statement works well with a general data
structure.
In python, the section of code you would copy whole
because it runs independently is called a function. We can
define a function as a block of organized and reusable code
that performs a single distinct but related action. Functions
make your code modular and reusable. Python provides a
built-in function such as print (“”), but you will also learn to
create yours, called user-defined functions.
6.1 Defining a Function
Here are five simple rules you must follow when defining
functions in Python:
1. A function block begins with the keyword def
followed by the name of the function and
parentheses ().
2. The first statement in a function can be an optional
statement such as doc string or the documentation
string of the function.
3. The code block within the function is indented and
begins with a colon (:)
4. Use return [expression] to exit a function, with the
option to pass back the expression to the caller.
5. If the function has arguments or input parameters,
they should be placed within the parentheses.
Parameters can also be defined inside the
parentheses.
Without specifying functions, your code would be very
repetitive and clumsy. Programmers do not like to
repeat things when they do not have to, and
considering computers were made just to handle
repetitive tasks; it is expected that you use functions to
minimize it.
Syntax
def functionname(parameters):
"function_docstring"
function_suite
return [expression]
Parameters have a positional behavior by default and should
be informed in the same order they are defined.
numbers = input("Enter two numbers separated by a comma: ")
list = numbers.split(",")
In the above example, we use an inbuilt function called max
that finds the maximum value from two or more numbers.
This program asks the user to enter several numbers
separated by commas then creates a list out of them. The
max function finds the maximum number and assigns
variable highest before displaying it.
In Ex25, our task is to define our own function to replace
Max above. We will call it MyMax.
Ex25
#Ex25
def MyMax (firstnumber, secondnumber):
else:
return secondnumber
numbers = input("Enter two numbers separated by a comma: ")
list = numbers.split(",")
firstnumber = list[0]
secondnumber = list[1]
result = MyMax(firstnumber, secondnumber)
y = x ** 3
return y
In Ex26, just after the return statement, the program asks
the user to enter a number to find a cube for. The number a
is ‘cubed‘ as per the cubed function we defined and its
result, which is represented by y in the function, is printed
out as a string.
You can substitute the expression return with any Python
expression and even avoid creating the variable y to
represent the answer to leave on return x ** 3 and the
program will work just the same (try it).
However, it is a good programming practice to use
temporary variables such as y in our defined function to
make it easy to debug the program later. Such temporary
variables are called local variables.
6.3 Time-saving functions
One of the best things about functions is that they make it
possible (and easier) to write an efficient code that you can
reuse over and over. For instance, if you write a function
that verifies data the user enters, you can use it in the
future when you create a program that requires data
verification to work.
Before you create a function, you should first find out what
its inputs and outputs are. In our case, we know that the
user enters an integer as input and gets the output as a
string of the cubed number. If our function was efficient
enough, it would also verify that the right data is entered
(for instance entering alphabetical characters will cause a
ValueError.
When you create a function, the best way to maximize its
value is to make it time-saving. This means you should be
able to tweak the function slightly, if at all, when you want
to fit it in another script in the future.
6.4 Pass by reference vs. value
One thing that makes how Python treats function
parameters different from standard variables is that its
function parameters are passed by value. All parameters
(arguments) in Python are passed by reference, meaning
that when the value of a parameter the function refers to
changes, the change will also be reflected in the calling
function. Function parameters are sacred. When a
parameter refers to an integer, the function provides a copy
of the value of the variable, not access to the variable itself.
Let us look at how this works in Ex27.
Ex27
#Ex27
def listchange(fruits):
"This changes the list to this function."
fruits[2] = "Vegetable"
print ("Parameter values after change: ", fruits)
return
fruitslist = input("Enter fruit names separated by commas: ")
fruits = fruitslist.split(",")
listchange(fruits)
Here is what you should see when you run Ex26. In this
demo, I used examples Apple, Mango, Peach, and Orange.
C:\Python35-32\Exfiles>python ex27.py
Parameter values before change: ['Apple', ' Mango', ' Peach', ' Orange']
Parameter values after change: ['Apple', ' Mango', 'Vegetable', ' Orange']
In this demonstration, we have maintained the reference of
the passed object while appending a value in the same
object. You will notice that the function modifies the third
item in the list by replacing it with “Vegetable” value that is
retained outside the function.
Let us do another example where an argument is passed by
reference, and the reference overwritten inside the function.
Ex28
#Ex28
def AgeChanger(ages):
"This changes a passed list to this function"
return
When you run this exercise, you should see something like
this:
C:\Python35-32\Exfiles>python Ex28.py
Values inside the function: [18, 21, 34]
Values outside the function: [10, 15, 20]
The parameter ages is local to the function AgeChanger
function. When you change the ages values within the
function, it does not affect ages outside the function,
therefore producing nothing.
6.5 Function Arguments
There are several ways you can call a function. You can use
the following formal argument types:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
return
DisplayMe()
When you run the example above, you will encounter an
error because you have to pass one argument:
TypeError: DisplayMe() missing 1 required positional
argument: 'str'
def DisplayMe(str):
"This prints a passed string into this function"
print (str)
return
When you run this script you will see this:
Display text.
To explain this better, we will do an exercise on the same.
Keep in mind the order of parameters to see if it matters.
Ex30
#Ex30
When the Ex30 code is executed, you should see a result
like this:
C:\Python35-32\Exfiles>python Ex30.py
Name: John
Sex: male
As you can see, the order of the parameters does not matter
when the keyword is used when calling an argument.
"function_docstring"
function_suite
return [expression]
An asterisk (*) is inserted before the variable name that will
hold the values of the non-keyword variable arguments. The
variable arguments tuple will remain empty if no new
arguments are specified when the function is called.
6.6 The return Statement
The statement return [expression] that we have used
throughout this chapter exits the function. A return
statement that has no arguments is similar to return None.
Ex31 is an example of a function that returns a value.
Ex32
#Ex32
def multiply(arg1, arg2):
return product
x = int(input("Enter the first number: "))
#Nowcall the multiply function
answer = multiply(x, y)
You can also create a similar dictionary like this:
MyDict = {
'Name': 'Waldo',
'Age': 25,
'Sex': 'Male',
'Location': 'Italy'
In a dictionary, keys must be unique while values may not.
Keys must also be of immutable data types such as
numbers, strings, or tuples but values may not
7.2 Accessing Values in Dictionary
You are already familiar with how to access values in a list
using square brackets enclosing an index value, accessing
dictionary elements should be a piece of cake because they
are pretty much the same thing. Here is a simple example
on how to access values in a dictionary:
Ex33
#Ex33
Write the above code in your text editor and run it. You
should see something like this:
What happens when you try to access a data item using a
key that is not included in the dictionary? Let us try it with
the example above and see what error we get.
#Ex33
You should get the error KeyError: ‘Continent’ when you run
the code above. This essentially means that the key does
not exist.
7.3 Updating the Dictionary
You can update the dictionary by adding new entries or key-
value pairs or modifying or deleting existing entries. In
Ex33, we will put each of these in practice to understand
how they work.
MyDict['Name'] = name
MyDict['Age'] = age
MyDict['Location'] = location
This shortcode has a dictionary with four keys with paired
values. It prompts the user for new values stored in
variables called name, age, and location then assigns them
to the 'Name,' 'age,' and 'Location' keys of the MyDict
dictionary.
Can you modify the code to allow the user to enter a new
string and modify the 'Sex' value in the dictionary?
print ("List of keys before deletion:",list(MyDict.keys()))
del MyDict['Location']
print ("List of keys after deletion:", list(MyDict.keys()))
This code will give you a KeyError: 'Location' when you run it
because 'Location' has been removed.
To clear all the entries in the dictionary, dict.clear().
7.4 Properties of Dictionary Keys
There are no restrictions as far as using dictionary values
goes. You can use arbitrary objects including standard and
user-defined objects. However, when it comes to keys, there
are two important rules you must always remember as I
mentioned in the introduction:
1. Keys must be unique. You cannot have more than
one similar keys in a dictionary.
2. Keys are immutable. You cannot use something like
[key] to define a key.
7.5 Built-in Dictionary Functions and
Methods
In this section, I will go through a list of the essential
functions and approaches built into Python that you can use
with dictionaries. I suggest that you study the description of
the different methods and functions and apply them to Ex36
then run the code to see what they do.
Ex36
#Ex36
For example, to try the len(GradsDict) function, first
understand what it does, find out what the output should
be, then enter this in your Ex36.py code:
#Ex36
Function Description
This is the length function which
len(GradsDict) gives the number of items in the
dictionary.
str(GradsDict)
This gives a printable string
representation of the dictionary.
type(variable) Gives the type of the passed
variable. For a dictionary, it
returns dictionary type.
Method Description
Removes all the elements in the
GradsDict.clear() dictionary including keys and
values.
Makes a shallow copy of the
GradsDict.copy()
GradsDict dictionary
Creates a new dictionary with the
GradsDict.fromkeys()
GradsDict keys.
For the specified key (e.g.) ‘email’,
GradsDict.get(key,
default=None) returns value. If no value is
assigned, it returns default.
Returns the GradsDict (key, value)
GradsDict.items()
tuple pairs as a list.
GradsDict.keys() Returns a list of the GradsDict keys.
Similar to get() except that it sets
GradsDict.setdefault(key,
default=None) the GradsDict[key] to default if it is
not in the dictionary already
Takes the key-value pairs of
GradsDict.update(GradsDict2)
GradsDict2 and adds them to GradsDict
GradsDict.values()
Returns the values of GradsDict
dictionary.
Hour 8: Classes
In the introduction to this book, we described Python as an
Object Oriented Programming language. This is because
Python lets you structure your code in a way that uses
modules, classes, and objects with ease. This chapter
focuses on helping you master Python’s object-oriented
setup to create a consistent program that can be run in a
‘cleaner’ way. You will find out what objects in programming
are and how modules and classes are used.
If you find it difficult to grasp these full, do not worry
because everyone new to programming struggles at first to
understand the plain weird set up that is OOP. In the
conclusion of this book, you will find a few
recommendations of web resources you can refer to
understand the in-depths of OOP fully.
8.1 Overview of Terminologies used in
OOP
Class: This is a prototype for an object defined by the user
with attributes that characterize an object. The
characteristics, in this case, include data members (instance
and class variables) and methods.
Object: An object is made up of data members including
class variables and instance variables as well as methods
that create a unique instance of a data structure defined by
its class.
Data member: This is an instance variable or a class
variable that stores the data associated with an object and
its class.
Class variable: This is a variable that is shared by all the
instances of a class. It is defined within a class but outside
of any of the class’s methods.
Instance variable: This is a variable defined inside a
method. An instance variable belongs only to the current
class instance.
Instance: An object of a particular class also defined as an
object that belongs to a class Circle.
Instantiation: The process of creating an instance of a
class.
Inheritance: Inheritance is the process of transferring the
characteristics of class to other classes derived from the
parent class.
Method: A special form of the function defined within a
class definition.
Function overloading: This is when you assign more than
one behavior to a function. Function overloading varies with
the types of arguments and objects involved.
Operator overloading: This is when more than one
function is assigned to an operator.
8.2 Creating Classes
To put it in a way that is easy to understand, a class is a
kind of container where you will group all related data and
functions to be able to access using a “.” (dot) operator.
A new class definition is created using the class statement
followed by the name of the class then a colon, like this:
class ClassName:
"class documentation string"
class_suite
The class can also have an optional documentation string
right below the definition as shown above and can be
accessed using ClassName._doc_.
The class_suite contains all the basic statements that define
the class members, functions, and data attributes.
Ex37
#Ex37
class MyContacts:
"Details of my contacts"
ContCount = 0
def __init__(self, name, number):
self.name = name
self.number = number
MyContacts.ContCount += 1
def ContactCount(self):
def ShowContact(self):
print (self.name, "-", self.number)
In this exercise, we have created a class called MyContacts.
The ContCountvariable is a class variable. Its
value is shared with all the instances of the
class and can be accessed as
MyContacts.ContCount within and outside the
class.
The _init_() method is a unique method also
called initialization or the class constructor
method. Python calls this method when you
create a new instance of the MyContactsclass
The first argument to each method is self. All
other categories are declared like standard
functions. You do not need to add the self-
argument to the list because Python adds it for
you.
8.3 Creating Instance Objects
To create a new instance of a class, first, you call the class
using the class name then pass in the arguments that
the_init_ method accepts. Let us create an instance object
for the class we set up in Ex36. Modify Ex36 by adding the
following instance objects:
"These create the objects of the MyContacts class"
Contact1 = Mycontacts("Bonny", "0789182733")
Save the new code as Ex38.py. Your exercise code should
look like this:
Ex38
#Ex38
class MyContacts:
"Details of my contacts"
ContCount = 0
self.name = name
self.number = number
MyContacts.ContCount += 1
def ContactCount(self):
def ShowContact(self):
class MyContacts:
"Details of my contacts"
ContCount = 0
def __init__(self, name, number):
self.name = name
self.number = number
MyContacts.ContCount += 1
def ContactCount(self):
def ShowContact(self):
Contact1.ShowContact()
Contact2.ShowContact()
Contact3.ShowContact()
If you entered everything right, the result should look
something like this:
C:\Python35-32\Exfiles>Python Ex38.py
Bonny - 0789182733
Peter - 0739237494
Janet - 0718297621
Total contacts: 3
In Ex40, we will practice adding and modifying attributes.
If you entered everything right, the result should look
something like this:
Ex40
#Ex40
class MyContacts:
"Details of my contacts"
ContCount = 0
def __init__(self, name, number):
self.name = name
self.number = number
MyContacts.ContCount += 1
def ContactCount(self):
print ("Total contacts:", MyContacts.ContCount)
def ShowContact(self):
print (self.name, "-", self.number)
"These create the objects of the MyContacts class"
Contact1 = MyContacts("Bonny", "0789182733")
Contact2 = MyContacts("Peter", "0739237494")
Contact3 = MyContacts("Janet", "0718297621")
print ("Original class attributes:")
Contact1.ShowContact()
Contact2.ShowContact()
Contact3.ShowContact()
print ("Total contacts:", MyContacts.ContCount)
Contact1.name = "Boniface"
Contact2.name = "Nancy"
Contact3.number = "0779204852"
print ("Updated class attributes:")
print ("Total contacts:", MyContacts.ContCount)
Contact1.ShowContact()
Contact2.ShowContact()
Contact3.ShowContact()
Here are the functions you can use to add, modify, and
delete attributes:
getattr(obj, name, [default]) is used to access the
attribute of an object
hasattr(obj, name)is used to check if an attribute
exists or not.
setattr(obj, name, value)is used to set an attribute
or create one if it does not exist.
delattr(obj, name)is used to delete an attribute.
8.5 Built-In Class Attributes
Every Python class by default has the following attributes
built-in and can be accessed using the dot (.) operator just
like any other attribute.
__name__: Class name.
__dict__: Dictionary containing namespace of the class.
__doc__: Class documentation string. If undefined, none.
__module__("__main__"in interactive mode): Module name in
which the class is defined.
__bases__: A tuple containing the base classes arranged in
order of occurrence in the base class list. This class could be
possibly empty.
Let us used these attributes in the code we saved as Ex 38
to see firsthand what they do. Save the code as Ex40 and
run it on the terminal.
Ex41
#Ex41
class MyContacts:
"Details of my contacts"
ContCount = 0
self.number = number
MyContacts.ContCount += 1
def ContactCount(self):
def ShowContact(self):
8.6 Class Inheritance
You do not need to create a class from scratch every time. If
you can derive it from an existing class, list the parent class
in parentheses right after the new class name. The child
class will inherit the attributes of the parent class, and you
will be able to use its attributes just as if they are defined in
the child class. A child class will, however, override any data
members and methods from the parent class.
Here is the syntax for class inheritance:
You can also derive a class from two or more parent classes
as demonstrated in the syntax above. You can use
isinstance() or issubclass()to check how two classes and
instances relate.
isinstance(ChildClass, ParentClass)is a Boolean
function that will return true if the given child class
is a subclass of the parent class.
issubclass(object, class)is a Boolean function that
returns true if the objis an instance of the class or if
an instance is a subclass of the class.
8.7 Overriding Methods
You can override the parent class methods when working
with a child class especially if you want a different or special
functionality in the subclass. Here are some of the generic
functionalities that you can override in the subclasses:
__init__ (self [,args...]): This is a constructor with optional
arguments.
__del__ (self): Deletes an object.
__repr__ (self): Represents an evaluable string.
__str__ (self): Represents a printable string.
__cmp__ (self, x): Used to compare objects.
8.8 Overloading Operators
If your code will at some point add two-dimensional vectors,
you could define the __add__ method in the class to handle
vector addition to preventing errors. Here is a demo you can
try:
Ex42
#Ex42
class NumAdder:
self.x = x
self.y = y
def __str__(self):
return "NumAdder (%d, %d)" % (self.x, self.y)
a1 = NumAdder(5, 7)
a2 = NumAdder(-3, 9)
The way a crow
Shook down on me
Save the file as Poem.txt.
file_name: This string value argument contains the name of
the files you want to access.
access_mode: This is an optional parameter that determines
the mode in which a file can be opened. The table below
summarizes the different modes you should know about.
Mode Description
This is read-only mode. Unless specified, the
r
default mode in which a file is opened is in this
mode by default. The file pointer is positioned at
the start of the file.
Opens a file in binary format for reading only. The
rb
pointer is positioned at the start of the file.
r+
Opens a file for reading and writing in text format.
The file pointer positioned at the start of the file.
Opens a file for reading and writing but in binary
rb+ format. The file pointer placed at the beginning of
the file.
Opens a file for writing only and overwrites the file
w it already exists. If it does not exist a new file for
writing is created.
wb Opens a file for writing only but in binary format
and creates one if the file does not exists.
Overwrites if the file already exists.
Opens a file ready for reading and writing and
overwrites the existing file if it already. If the file
w+
does not exist, a new one for reading and writing is
created.
Opens a file in binary format for reading and
writing and overwrites the existing one if already
wb+
exists. If it does not, a new one ready for reading
and writing is created.
Opens a file in append mode. The pointer is
a positioned at the end of the file if it exists. If the
file does not exist, a new one for writing is created.
Opens a file in binary format in append mode. The
pointer is positioned at the end of the file if it
ab
exists. If the file does not exist, a new one for
writing is created.
Opens a file for reading and appending in the
append mode. The file pointer is at the end of the
a+
file if it exists. If it does not exist, a one is created
for reading and writing.
Opens a file in binary format for reading and
appending in append mode. The pointer is
ab+ positioned at the end of the file if the file exists. A
new file is created for reading and writing in if the
file does not exist.
file_name: This string value argument contains the name of
the files you want to access.
Buffering: If the value of buffering is set to 0, no buffering
will take place. If set to 1, the program performs line
buffering when accessing the file. If the buffering value is
specified as an integer greater than 1, buffering is
performed with the specified buffer size. If the value
specified is negative, the system’s default buffer size is
used.
Ex43
Start a new file on your text file and enter the following
code for Ex43:
#Ex43
MyPoem = text.read(16); #Reads the first 16 bytes in the text and assigns
variable MyPoem
print ("Read String is:", MyPoem)
Run Ex42 and see what happens. This is what you should
see:
C:\Python35-32\Exfiles>Python Ex43.py
When you open a file using Python’s inbuilt open() function,
a file object will be created which you can use to call
support methods it is associated with.
Ex44
#Ex44
MyText.close()
The above exercise has two unique processes. Can you
identify which one writes the file then closes it and which
one opens and prints it show what string was written to the
file MyFile.txt?
9.2 File Positions
If you wish to specify where in the file you would like to read
or write text, the tell() method will show you the current
position in bytes about the beginning of the file.
The seek(offset, [from]) method is then used to change the
file position, with the offset argument indicating the number
of bytes by which the position is moved. The
[from]argument references the position from which the
bytes are moved.
If the from argument is set to 0, the beginning of the file will
be the reference position, and if it is 1, the current position
will be the reference position. If it is set to 2, the end of the
file will be the reference position in the method.
Let us try out these file position commands in Ex45 using
the MyFile.txt file we created in Ex44.
Ex45
#Ex45
text = MyText.read(50)
position = MyText.tell(); #To check the pointer position
MyText.close()
9.3 Renaming and Deleting Files
The OS module of Python offers various methods that you
can use to perform various file processing and manipulation
operations including renaming and deleting files. However,
to call the functions of this module, you will first need to
import it using import os.
In Ex46, let us rename the MyFile.txt file we created to
MyPoem.txt.
Ex46
#Ex46
import os
text = MyText.read(50)
print (text)
We will go ahead and delete the MyFile.txt file we created in
Ex44 in Ex47. If the file no longer exists in your folder, you
can create one and give it the exact similar name or only
run Ex43.py again to create it.
Ex47
#Ex47
import os
os.remove("MyPoem.txt")
Remember to restore the deleted file MyPoem.txt because
we will need it in the next exercise.
9.4 File and Directory Related
Methods
There are countless resources on the internet where you can
learn and practice a broad range of methods you can use to
manipulate and handle files and directories. These
resources cover:
OS Object Methods: This offers ways to process files
and folders (directories).
File Object Methods: The file object provides many
functions used to manipulate files.
When you pursue learning Python beyond this stage, you
will learn how to manipulate and work with directories.
Hour 10: Errors and Exceptions
Errors that happen during the execution of program code
are called exceptions. To the average software user, an
exception is an instance where a program does not conform
to the general and defined rules as expected.
An error is resolved by saving the status of the execution
when the error occurred and interrupted the normal
program flow. An exception handler is a piece of code that is
used to determine the type and cause of an exception or
error.
Depending on the type of error encountered, the exception
handler can fix the problem encountered and allow the
program to resume normal flow or it will stop prompt the
user for data or instructions before resumption.
Python comes with two vital tools used to handle any
unexpected errors in the code and to debug it: They are:
1. Exception handlers
2. Assertions
When a script in Python raises an exception, it must be
handled immediately; otherwise, the program will terminate
and quit.
10.1 Exception Handling
In Python, a code that harbors the risk of an exception is
embedded in a try block and caught by an except keyword.
Python allows you to create a custom exception, even using
the raise statement to force a specified exception to occur.
except PossibleException1:
If there is PossibleException1, then run this code
except PossibleException2:
If there is PossibleException2, then run this code
else:
If there is no exception then run this code.
Note that:
A single try: the statement can have one or more
except statements. This is important when you are
trying to handle possible multiple errors that you
suspect your one block of code could rise.
It is a good practice to provide a generic except
clause that handles any and all exceptions.
The else: clause is optional. Its code executes only
when there are no exceptions raised by the try:
block code. You can place the code that does not
need the protection of the try: block in the else:
block.
In Ex48, we will try to open the file MyFile.txt which we do
not have permission to write, to raise an exception.
Ex48
#Ex48
try:
except IOError:
When you run the code above on your terminal, you should
see this:
C:\Python35-32\Exfiles>python Ex48.py
Now, try eliminating the error by opening the file in read and
write mode then run it. What does it print?
Hint: Change "r" to "r+".
Let us try another example. In Ex49, the program expects
the user to enter an integer as the value of n. It should
generate an error when the input is a string instead. We will
raise a ValueError then use the try: exception handling to
resolve it.
Ex49
#Ex49
while True:
try:
break
except ValueError:
This script contains a loop that only breaks when the user
enters a valid integer.
If you have a code that must execute whether an exception
is raised in the try block or not, you can use the finally:
clause. The syntax would look like this: use the finally:
clause. The syntax would look like this:
try:
Enter your code here;
finally:
Let us write a script example that puts the try: and finally:
clauses in use.
Ex50
#Ex50
try:
Note: You cannot use the else: clause along with the finally:
clause.
When there is an exception in the try: block, the execution
will be passed to the finally: block immediately. The
exception will be raised again after all the statements in the
finally: block are executed then handled by the except
statement if it is present in a following higher layer of the
try: then except statement. Let us try it in Ex50 by writing a
script that finds the reciprocal of a number entered by the
user.
Ex51
#Ex51
try:
reciprocal = 1.0 / x
except ValueError:
except ZeroDivisionError:
print ("Cannot divide by 0!")
finally:
10.2 Assertions
In Python, an assertion is a tool that you use to find bugs
faster and with less pain. You can turn it on before use and
turn it off after you are finished testing your code. It will test
an expression and raise an exception if the result is FALSE. It
is a good practice to place the assert statement at the
beginning of a function to ensure an input is valid and after
a function to validate the output.
Ex52
#Ex52
def CtoF_Converter(Temp):
#
assert (Temp >= -273.15), "Cannot be colder than absolute zero!"
F = CtoF_Converter(C)
print (C, "degrees Celcius is", F, "degrees Fahrenheit.")
If you run the Ex52.py and enter a number less than 273.15,
you should encounter an assertion error akin to this:
C:\Python35-32\Exfiles>python Ex52.py
F = CtoF_Converter(C)
assert (Temp >= -273.15), "Cannot be colder than absolute zero!"
Hour 11: Testing Your Code
Testing your code is one of the most important steps of
developing a functional program. In fact, it is typically
considered a good practice to write testing code than
running it in parallel to your primary code. This method is
widely used by developers across the development sphere
as it helps developers define the precise intent of their code
and to create software with more decoupled architecture.
11.1 General rules of testing Python
code
Here are the ten commandments of testing your code in
Python.
1. The testing unit of your code should focus on a tiny
bit of functionality and should prove it correct.
2. Each testing unit should be completely
independent. It should be able to run alone within
the test suite regardless of the order it is called. The
setup() and teardown() methods can be used to
load new datasets and cleanup after testing.
3. Always try to make tests run fast to avoid slowing
down the entire development. If testing takes
longer because of complex data structure it must
process, the test units can be run in separate
suites.
4. Practice using your tools to run only tests or test
cases then runs them when developing functions
inside modules frequently, ideally, automatically
every time you save your code.
5. Make it a habit of running the full test suite prior to
and after every coding session to be sure that
noting is broken in the code before starting or and
when ending the session.
6. Put in place a hook that runs all tests before
pushing the code to a shared depository if working
on the collaborative code.
7. If your development session is interrupted, make a
point of writing a broken unit test about what you
intend to develop next to know where to start when
you resume the next session.
8. The first step in debugging your code should be
writing a new test that pinpoints the bug. This is not
always the easiest thing to do, but this will help you
catch those elusive bugs faster and more
comprehensively in your code.
9. Write long descriptive names for your testing
functions because unlike regular code, and the unit
test code is never called explicitly.
10. Every unit test must have a clear purpose of
making it helpful. When something goes wrong, or
you have to make some changes, you will rely on
the testing suite to make modifications or modify
certain behaviors.
11.2 unittest
unittest is a test module that comes with the Python
standard library. You can create a test case on unittest by
subclassing the unittest.TestCase as shown in exercise 53
syntax code below.
Ex53
#Ex53
import unittest
def counter(x):
return x + 1
class MyTest(unittest.TestCase):
def test(self):
self.assertEqual(counter(4), 5)
unittest comes with its test discovery capabilities.
11.3 Doctest
A doctest module searches the code for text that looks like
interactive sessions in docstrings then executes them to
verify that they execute exactly as shown. Unlike proper unit
tests, doctests have different uses and are usually not as
detailed. Because of this, doctests do not typically catch
obscure regression bugs and special cases.
Doctests are however very useful used as expressive
documentation of the main use cases of modules and its
components. They should, however, run automatically each
time a full test suite is run. Here is an example of how a
doctest syntax looks like.
Ex54
#Ex54
def square(x):
>>> square(-3)
"""
return x * x
if __name__ == '__main__':
doctest.testmod()
11.4 Tools
In this section, I will mention several popular testing tools
that you will learn to install and use when you get to
learning advanced testing of Python code.
11.4.1 py.test
The py.test is an alternative to the standard unittest module
that Python comes with. It is a fully-featured and extensible
testing tool that has very simple syntax. Creating a test
suite using py.test is as easy as writing a module with
several functions.
11.4.2 Nose
Nose is a tool that extends unittest so as to make testing
code easier. The nose offers automatic test discovery to
save the programmer the hassle of having to create test
suites manually. It also comes with multiple plugins with
extra features such as coverage reporting, test selection,
and xUnit compatible test output.
11.4.3 tox
Tox is a versatile tool that you can use to automate the
Python test environment management and even test
multiple interpreter configurations. This tool lets you
configure complex multi-parameter test matrices using a
simple ini-style config file.
11.4.4 Unittest2
This is a backport of Python’s unittest module. It features an
improved API as well as better aassertions over the original
unittest.
11.4.5 mock
unittest.mock features many library tools that you can use
to test your Python code. Mock allows you to replace parts
of the system you are testing with mock objects and test
code by making assertions on how they have been used. It
is available in the standard Python library starting with
Python 3.3.
Hour 12: Conclusion & Further
Reading
Over 50 programs of Python written so far since the first
Hello World program about 12 hours, ago (hours of study)
and you have become an even better and experienced
program. If you followed every step of this eBook so far, you
have earned the bragging rights to call yourself a
programmer. You started from scratch (like everyone should)
and perhaps with no prior experience in programming, can
now speak regarding functions, classes, IOError, and much
more geeky terms.
This short eBook is compressed to keep it concise and
practical. You have so far learned how to tell the computer
to do all kinds of things, process text, save your information,
and saved processes you have personalized to do exactly
what you want. The magic has been to learn how to tell the
computer what to do, a skill most people still perceive as
pure wizardry.
Python’s core philosophy is summarized in The Zen of
Python, and it paints the colorful rules that govern the
language as:
1. Explicit is better than implicit
2. Simply is better than complex
3. Complexly is better than complicated
4. Beautifully is better than ugly
5. Readability counts
As a testament to just how beautiful Python code can be,
this is how exercise 37 looks on my editor: