Chapter 1 Start Python
Chapter 1 Start Python
What is Python?
First Python Program
The Shell Prompt
Configure Editor
Variables
Variables & Comment
Arithmetic Operator
Assignment Operators
Comparison Operators
Logical Operators
Conditional Operator
Convert Data Type
Triple Quotes
Exercise: Ticket Fare
Summary
Chapter 2 Statement
Chapter 2 Statement
If Statement
If-else Statement
Indentation
If-elif-Statement
For-In Loops
for variable in range( )
While Loops
Continue
Break Statement
Input Texts (1)
Input Texts (2)
Pass Statement
Exercise: Traffic Light
Summary
Chapter 3 Function
Chapter 3 Function
Math Function
ceil( ) & floor( )
pow ( ) & sqrt ( )
Max ( ) & Min ( )
abs( ) & round( )
Custom Function
Function with Arguments
Global & Local Variable
Global Variable inside Function
Return
Main Function
List all functions in module
Exercise: Circle Area
Summary
Chapter 4 Data Structures
Chapter 4 Data Structures
List
List Functions
Know More List
Tuple
Tuple Functions
Set
Set Functions
Dictionary
Dictionary Functions
Data Structure Review
Exercise: Four Colors
Summary
Chapter 5 Strings
Chapter 5 Strings
Operation Strings
Escape Characters
Testing Functions
Searching Functions
Formatting Functions
Stripping Functions
Splitting Functions
String Functions (1)
String Functions (2)
Regular Expressions
Regular Expression in Python
Summary
Chapter 6 Input & Output
Chapter 6 Input & Output
Format String
File Directory
Open File
Write File
Append Text to File
Renew Some Text
Open Web Page
Exercise: Process a File
Summary
Chapter 7 Module & Exception
Chapter 7 Module & Exception
Module
Import Module (1)
Import Module (2)
Built-in Module
Exceptions
Catch Exceptions
Finally
Debug
Exercise: Three Flowers
Summary
Chapter 8 Class & Object
Chapter 8 Class & Object
Class Definition
Object Declaration
Another Object
Inheritance
Overriding Method
Polymorphism
Exercise: Rose is Red
Summary
Appendix Python Summary Charts
Appendix Python Summary Charts
Appendix Django Basic
Appendix Django Basic
Django Introduction
Install Django
Test Django
Creating Project
Project Structure
Start up Server
Preview Web Page
Create a View File
Create an URL File
View the Web Page
Template
Template Path
Modify view.py
View the Web Page
Tests

##### Citation preview

Python Programming

For Beginners Quick Start Guide Ray Yao

Copyright © 2015 by Ray Yao All Rights Reserved Neither part of this book nor whole of this book may be reproduced or transmitted in any form or by any means electronic, photographic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without prior written permission from the author. All rights reserved! Ray Yao

Ray Yao’s eBooks & Books on Amazon Advanced C++ Programming by Ray Yao Advanced Java Programming by Ray Yao AngularJs Programming by Ray Yao C# Programming by Ray Yao C# Interview & Certification Exam C++ Programming by Ray Yao C++ Interview & Certification Exam Django Programming by Ray Yao Go Programming by Ray Yao Html Css Programming by Ray Yao Html Css Interview & Certification Exam Java Programming by Ray Yao Java Interview & Certification Exam JavaScript Programming by Ray Yao JavaScript 50 Useful Programs JavaScript Interview & Certification Exam JQuery Programming by Ray Yao JQuery Interview & Certification Exam Kotlin Programming by Ray Yao Linux Command Line Linux Interview & Certification Exam MySql Programming by Ray Yao Node.Js Programming by Ray Yao Php Interview & Certification Exam Php MySql Programming by Ray Yao PowerShell Programming by Ray Yao

Python Programming by Ray Yao Python Interview & Certification Exam R Programming by Ray Yao Ruby Programming by Ray Yao Rust Programming by Ray Yao Scala Programming by Ray Yao Shell Scripting Programming by Ray Yao Visual Basic Programming by Ray Yao Visual Basic Interview & Certification Exam Xml Json Programming by Ray Yao

Preface “Python Programming” covers all essential Python knowledge. You can learn complete primary skills of Python fast and easily. The book includes more than 80 practical examples for beginners and includes tests & answers for the college exam, the engineer certification exam, and the job interview exam. Note: This book is only for Python beginners, it is not suitable for experienced Python programmers. Source Code for Download This book provides source code for download; you can download the source code for better study, or copy the source code to your favorite editor to test the programs. Source Code Download Link: https://forms.aweber.com/form/53/519080053.htm

Table of Contents Chapter 1 Start Python What is Python? First Python Program The Shell Prompt Configure Editor Variables Variables & Comment Arithmetic Operator Assignment Operators Comparison Operators Logical Operators Conditional Operator Convert Data Type Triple Quotes Exercise: Ticket Fare Summary

Chapter 2 Statement If Statement If-else Statement Indentation If-elif-Statement For-In Loops for variable in range( ) While Loops

Continue Break Statement Input Texts (1) Input Texts (2) Pass Statement Exercise: Traffic Light Summary

Chapter 3 Function Math Function ceil( ) & floor( ) pow ( ) & sqrt ( ) Max ( ) & Min ( ) abs( ) & round( ) Custom Function Function with Arguments Global & Local Variable Global Variable inside Function Return Main Function List all functions in module Exercise: Circle Area Summary

Chapter 4 Data Structures List List Functions Know More List

Tuple Tuple Functions Set Set Functions Dictionary Dictionary Functions Data Structure Review Exercise: Four Colors Summary

Chapter 5 Strings Operation Strings Escape Characters Testing Functions Searching Functions Formatting Functions Stripping Functions Splitting Functions String Functions (1) String Functions (2) Regular Expressions Regular Expression in Python Exercise: Check Your Input Summary

Chapter 6 Input & Output Format String File Directory

Open File Read file Write File Append Text to File Renew Some Text Open Web Page Exercise: Process a File Summary

Chapter 7 Module & Exception Module Import Module (1) Import Module (2) Built-in Module Exceptions Catch Exceptions Finally Debug Exercise: Three Flowers Summary

Chapter 8 Class & Object Class Definition Object Declaration Another Object Inheritance Overriding Method Polymorphism

Exercise: Rose is Red Summary

Appendix Python Summary Charts Appendix Django Basic Django Introduction Install Django Test Django Creating Project Project Structure Start up Server Preview Web Page Create a View File Create an URL File View the Web Page Template Template Path Modify view.py View the Web Page

Chapter 1 Start Python

What is Python? Python is a general-purpose, object-oriented and open source computer programming language, it is a high-level, human-readable and a corresponding set of software tools and libraries. Download Python Free download Python installer at: https://www.python.org/downloads/ Install Python When the download finishes, run the installer by double-clicking it. Install Python to your local computer, For example: at C:\Python35. Click “Next”.

Make sure to select the option “Add Python.exe to Path”.

Please complete the installation of Python. Run Python Please click “Start > Programs > Python3.5 > IDLE (Python GUI)”. Or click “Start > Programs > Python3.5 > Python (Command Line)”. You will see Python prompt: >>>

First Python Program print( ) “print ( )” is used to print text or string to the screen. Example 1.1 >>> print ("Hello World!") Output: Hello World! Example 1.2 >>> print ("Python is a very good language!") Output: Python is a very good language! >>> print ("Learn Python in 8 Hours!") Output: Learn Python in 8 hours. Explanation: “>>>” is a Python primary prompt. “print ( )” displays the text.

The Shell Prompt >>> “>>>” is the Python interactive command shell prompt, requests the input from the user. For example: >>> 10 + 8 18 >>> 100 - 2 98 >>> " Hello " + " World! " ' Hello World! ' >>> " Very Good! " * 3 ' Very Good! Very Good! Very Good! ' Explanation: “>>>” prompts that you can input data, and press Enter. The lines without >>> are responded by Python.

For example: >>> 100 * 2 200 >>> 72 / 9 8

>>> ( 2 + 3 ) * 4 20 >>> 10 % 3 1 >>> 2 ** 3 8 Explanation: *

multiplication

/

division

%

remainder

**

exponentiation

Configure Editor In order to run the whole Python program instead line by line, or easily copy or paste whole code, you need to configure the python editor. Please click “Start > All Programs > Python3.5 > IDLE (Python GUI)”. Click “Option > Configure IDLE > General > Open Edit Window” > OK.

After selecting “Open Edit Window”, you can run the whole Python program instead line by line. Press “F5” key to run the program. (Run>Run Module) Note:

Option “Open Edit Window” runs the program by whole code. Execute the whole program by pressing F5 key. (Run>Run Module) Option “Open Shell Window” runs the program line by line. Execute the one line code by pressing Enter key.

Variables A “variable” is a container that stores a data value. The variable value may change when program is running. variableName = value variableName1 = variableName2 = value variableName1, variableName2 = value1, value2 “variableName” is a variable name. Example 1.3 var = 100 var1 = var2 = var3 = 100 var1, var2, var3 = 100, 200, 300 Explanation: “var = 100” defines a variable named “var”, whose value is 100. “var1 = var2 = var3 = 100” assigns the value “100” to “var1”, var2”, “var3”. “var1, var2, var3 = 100, 200, 300” respectively assigns the value “100, 200,300” to “var1”, var2”, “var3”.

Variables & Comment A variable's value can be used in Python programs. variableName = value print (variableName) # Symbol can be used in a comment. # comment Example 1.4 var01 = 100 print (var01) # Output: 100 Example 1.5 var02 = "Python is very good!" print (var02) # Output: Python is very good! Explanation: “print ( )” is used to display content. # is a symbol of comment. “# Output: 100” is a comment. “# Output: Python is very good!” is a comment.

Arithmetic Operator Operator Operation +

-

Subtraction

*

Multiplication

/

Division

%

Remainder

//

Integer Division

**

Exponentiation

Note: “%” modulus operator divides the first operand by the second operand, returns the remainder. “//” works like “/”, but returns an integer. “**” returns the result of the first operand raised to the power of the second operand. Example 1.6 a = 100 + 200 b = 72/9 c = 25 % 7 d = 7 // 3 e = 8 ** 2 print (a, b, c, d, e)

Output: (300, 8, 4, 2, 64) Explanation: “100 + 200” returns 300 “72/9” returns 8 “25 % 7” returns 4. “7 // 3” returns 2. “8 ** 2” returns 64.

Assignment Operators “x += y” equals “x = x + y”, please see the following chart: Operators += -= *= /= %= //= **=

Examples: x+=y x-=y x*=y x/=y x%=y x//=y x**=y

Example 1.7 x=20 y=2 x %= y print (x) Output: 0 Explanation: “x %= y” equals “x = x % y”

Example 1.8 m=100

Equivalent: x=x+y x=x-y x=x*y x=x/y x=x%y x=x//y x=x**y

n=18 m%=n print (m) Output: 10 Explanation: “m %= n” equals “m = m % n”.

Comparison Operators Operators

Running

>

greater than

=

greater than or equal

b) print (result1) result2= (a==b) print (result2) result3= (a!=b) print (result3)

Output: False False True

Explanation: result = (a>b) # test 100>200 outputs false. result = (a==b) # test 100==200 outputs false. result = (a!=b) # test 100!=200 outputs true.

Logical Operators Operators

Equivalent

and

logical AND

or

logical OR

not

logical NOT

After using logical operators, the result will be True or False. Example 1.10 x=True y=False a=x and y print (a) b=x or y print (b) c=not x print (c)

Output: False True False

Explanation: True and True returns true True or True returns True not False returns True

True and False returns False True or False returns True not True returns False

False and False returns False False or False returns False

Conditional Operator The syntax of conditional operator looks like this: (if-true-do-this) if (test-expression) else (if-false-do-this) ( test-expression) looks like a IDLE (Python GUI)”. Write the following code to the IDLE editor: age = 15 ticket = "Child Fare" if (age < 16 ) else "Adult Fare" print (ticket) Save the file, and run the program by pressing F5 key. (Run>Run Module). Output: Child Fare Explanation: The conditional operator use (age < 16) to test the “age” and “16”, because “age” is less than “16”, it is true. Therefore, the output is “Child Fare”.

Summary “print ( )” is used to print text or string to the screen. “>>>” is the Python interactive command shell prompt, requests the input from the user. A “variable” is a container that stores a data value. The variable value may change when program is running. variableName = value # Symbol can be used in a comment. “%” modulus operator divides the first operand by the second operand, returns the remainder. “//” works like “/”, but returns an integer. “**” returns the result of the first operand raised to the power of the second operand. “x += y” equals “x = x + y” Comparison operators: >, =, b: print ("a is greater than b.") Output: a is greater than b. Explanation a>b is a test expression, namely tests 200>100, if it returns true, it will execute the code “print( )”, if it returns false, it will not execute the code “print( )”.

If-else Statement if test-expression: statements

# run when text-expression is true

else: statements

# run when text-expression is false

Example 2.2 a = 100 b = 200 if a > b: print ("a is greater than b.") else: print ("a is less than b") Output: a is less than b. Explanation: a>b is a test expression, namely tests 100>200, if it returns true, it will execute the code “print(‘a is greater than b’)”, if it returns false, it will execute the code “print(‘a is less than b’)”

Indentation In Python, indentation is used to mark a block of code. In order to indicate a block of code, you should indent each line of the block of code by four spaces, which is a typical amount of indentation in Python. For Example: a = 100 b = 200 if a > b: print ("a is greater than b.") # indent four spaces else: print ("a is less than b") # indent four spaces The “print()” are indented four spaces. Correct! Note: if a > b: print ("a is greater than b.") # error! else: print ("a is less than b") # error! The “print()” are not indented, so errors occur!

If-elif-Statement if test-expression: statements

# run when this text-expression is true

elif test-expression: statements

# run when this text-expression is true

else: statements

# run when all text-expressions are false

Example 2.3 num=200 if num < 100: print ("num is less than 100") elif 100 < num < 150: print ("num is between 100 and 150") else: print ("num is greater than 150") Output: num is greater than 150 Explanation: elif is short for “else if”.

For-In Loops The for-in loop repeats a given block of codes by specified number of times. for in :

“variable” stores all value of each item. “sequence” may be a string, a collection or a range( ) which implies the loop’s number of times. Example 2.4 for str in 'Good': print ('Current Character :', str) Output: Current Character: G Current Character: o Current Character: o Current Character: d Explanation: “for str in 'Good'” loops four times because “Good” has 4 characters, “str” stores the value of each character.

for variable in range( ) for variable in range( ) can generate a sequence number for var in range( n) for var in range(n1, n2) range( n) generates a sequence from 0 to n-1. range(n1, n2) generates a sequence from n1 to n2-1. (1) Example 2.5 for var in range(6): print (var) Output: 0,1,2,3,4,5. (2) for num in range(3,10) : print (num) Output: 3,4,5,6,7,8,9. Explanation: for variable in range( ) can generate a sequence number

While Loops While –Loops is used repeatedly to execute blocks of code. while :

looks like a IDLE (Python GUI)”. Write the following code to IDLE editor: trafficLight = input("Please input traffic light -- red, green or yellow: ") if trafficLight == "red": print ("The traffic light is " + trafficLight) elif trafficLight == "green": print ("The traffic light is " + trafficLight) else: print ("The traffic light is " + trafficLight) Save the file, and run the program by pressing F5 key. (Run>Run Module). Output: The traffic light is green.

Explanation: if test-expression: statements # runs when this text-expression is true elif test-expression: statements # runs when this text-expression is true else:

statements

# runs when all text-expressions are false

Note: Please use double quote marks to enclose your input. ( In some Python version ). raw_input() is no longer used nowadays, but you need to know a little bit of Python history.

Summary “if statement” executes statement only if a specified condition is true, does not execute any statement if the condition is false. In Python, indentation is used to mark a block of code. In order to indicate a block of code, you should indent each line of the block of code by four spaces, which is a typical amount of indentation in Python. The for-in loop repeats a given block of codes by specified number of times. “for variable in range( )” can generate a sequence number While loops is used repeatedly to execute blocks of code. “continue” can skip the next command and continue the next iteration of the loop. “break” keyword is used to stop the running of a loop according to the condition. Sometimes users need to input some text by keyboard. variable = input(“prompt”) The pass statement is a null operation; it means “does nothing”. “pass” is very useful to work as a temporary placeholder for future code that needs to be inserted later.

Chapter 3 Function

Math Function Python comes with a lot of various modules of function; one of the most useful modules is Math module. The following table lists the most frequently used math functions. name

Description

abs(n)

absolute value of n

round(n)

round off a floating number n

ceil(n)

ceiling of n

floor(n)

flooring of n

max(n, m)

largest of n and m

min(n, m)

smallest of n and m

degrees(n)

convert n from radians to degrees

log(n)

base e logarithm of n

log(n, m)

base m logarithm of n

pow(n, m)

n to the power of m

sqrt(n)

square root of n

sin(n)

sine of n

cos(n)

cosine of n

tan(n)

tangent of x

Note: you may import math before using the math function

Example 3.1 import math print ("degrees(100) : ", math.degrees(100)) print ("degrees(0) : ", math.degrees(0)) print ("degrees(math.pi) : ", math.degrees(math.pi)) Output: degrees(100) : 5729.57795131 degrees(0) : 0.0 degrees(math.pi) : 180.0 Explanation: degrees(n) convert n from radians to degrees

ceil( ) & floor( ) math.ceil( ); math.floor( ); “math.ceil( );” returns an integer that is greater than or equal to its argument. “math.floor( );” returns an integer that is less than or equal to its argument. Example 3.2 import math print ("ceil(9.5) : ", math.ceil(9.5)) print ("floor(9.5) : ", math.floor(9.5)) Output: ceil(9.5) : 10.0 floor(9.5) : 9.0 Explanation: “math.ceil( num ));” returns an integer that is greater than or equal 9.5, the result is 10.0. “math.floor( num );” returns an integer that is less than or equal 9.5, the result is 9.0.

pow ( ) & sqrt ( ) math.pow( ); math.sqrt( ); “math.pow ( );” returns the first argument raised to the power of the second argument. “math.sqrt ( );” returns the square root of the argument. Example 3.3 import math print ("pow(4,2) : ", math.pow(4,2)) print ("sqrt(4) : ", math.sqrt(4)) Output: pow(4,2) : 16.0 sqrt(4) : 2.0 Explanation: “math.pow(4,2)” returns the first argument “4” raised to the power of the second argument “2”, the result is 16.0 “math.sqrt(4)” returns the square root of the argument “4”, the result is 2.0

Max ( ) & Min ( ) math.max( ); math.min( ); “math.max( )” returns the greater one between two numbers. “math.min( )” returns the less number between two numbers. Example 3.4 print ("max(4,2) : ", max(4,2)) print ("min(4,2) : ", min(4,2)) Output: max(4,2): 4 min(4,2): 2 Explanation: “math.max(x, y)” returns the greater number between 100 and 200, the result is 200. “math.min(x, y)” returns the less number between 100 and 200, the result is 100.

abs( ) & round( ) abs( ) round( ) abs( ) returns an absolute value of a number. round( ) rounds of a floating number Example 3.5 print ("abs(-100): ", abs(-100)) print ("round(0.555,2): ", round(0.555,2)) Output: abs(-100): 100 round(0.555,2): 0.56 Explanation: abs(-100) returns an absolute value 100 without negative sign. round(0.555, 2) rounds the floating number to 2 places.

Custom Function (1) A custom function can be created by using “def” def functionName( ):

# define a function

function body

(2) The syntax of calling a function functionName( )

# call a function

Example 3.6 def myFunction( ): print (“This is a custom function.”) myFunction( ) Output: This is a custom function Explanation: def myFunction( ): defines a function myFunction( ) calls a function

Function with Arguments (1) define a function with arguments def functionName(arguments):

# define a function

function body (2) call a function with arguments functionName(arg)

# call a function

Example 3.7 def userName(name): print ( "My name is " + name) userName("Andy") Output: My name is Andy Explanation: “def userName(name):” defines an argument “name”. “userName("Andy")” passes “Andy” to argument “name”.

Global & Local Variable Global Variable is defined outside the function and can be referenced from inside the function. Local Variable is defined inside the function and cannot be referenced from outside the function. Example 3.8 globalVar = "GV" # defines a global variable def testFunction( ): print ("The global variable is: " + globalVar) localVar = "LV" # defines a local variable print ("The local variable is: " + localVar) testFunction( ) # call a function Output: The global variable is: GV

The local variable is: LV

Explanation: "GV" is a global variable. "LV" is a local variable.

Global Variable inside Function If want a local variable to be referenced in everywhere, including inside and outside the function, you should use “global” keyword before the local variable name. Example 3.9 def tryFunction( ): global tryVar # defines a global inside the function tryVar = "This variable can be referenced in everywhere." tryFunction( ) # call a function print ("tryVar: " + tryVar ) # reference tryVar Output: tryVar: This variable can be referenced in everywhere. Explanation: “global tryVar “ defines a global inside the function “tryVar” can be referenced in everywhere.

Return “return” specifies a value to be returned to the caller. return Example 3.10 def multiply ( n, m ) : return n*m print (multiply( 2,100 )) Output: 200 Explanation: “return n*m” returns its result value to multiply(2,100). It is equivalent to multiply(2, 100) = return n*m

Main Function The main( ) function is a default start point of the whole program. def main (): function body Note: In Python, main( ) function is optional. Example 3.11 def main(): pwd = raw_input ("Please enter your password: ") if pwd == "12345": print ("Password is correct!") else: print ("Password is incorrect!") main() Output: Password is correct! / incorrect! Explanation: main( ) is a default start point by convention.

List all functions in module dir(module) “dir(module)” can list all functions in the specified module. Example 3.12 import math print (dir(math)) Output: (Descending Sequence) ['trunc', 'tanh', 'tan', 'sqrt', 'sinh', 'sin', 'radians', 'pow', 'pi', 'modf', 'log1p', 'log10', 'log', 'lgamma', 'ldexp', 'isnan', 'isinf', 'hypot', 'gamma', 'fsum','frexp', 'fmod', 'floor', 'factorial', 'fabs', 'expm1', 'exp', 'erfc', 'erf', 'e', 'degrees', 'cosh', 'cos', 'copysign', 'ceil', 'atanh', 'atan2', 'atan', 'asinh', 'asin', 'acosh', 'acos', '__package__', '__name__', '__doc__'] Explanation: “print (dir(math))” list all functions in math module.

Exercise: Circle Area Calling function & return Please click “Start > Programs > Python3.5 > IDLE (Python GUI)”. Write the following code to IDLE editor: import math r = input("Please enter a radius: ") def circleArea(): return math.pi*pow(r, 2) # calculates circle area print ("The circle area is: ", circleArea()) Save the file, and run the program by pressing F5 key. (Run>Run Module). Output: Please enter a radius: 3 The circle area is: 28.2743338823

Explanation: “circleArea()” calls a function “def circleArea()”. “return math.pi*pow(r, 2)” returns its result value to circleArea( ). It is equivalent to circleArea( ) = return math.pi*pow(r, 2). If entering “3” as radius, (r=3), then the value of circleArea( ) is 28.2743338823.

Summary “math.ceil( );” returns an integer that is greater than or equal to its argument. “math.floor( );” returns an integer that is less than or equal to its argument. “math.pow ( );” returns the first argument raised to the power of the second argument. “math.sqrt ( );” returns the square root of the argument. “math.max( )” returns the greater one between two numbers. “math.min( )” returns the less number between two numbers. abs( ) returns an absolute value of a number. round( ) rounds of a floating number A custom function can be created by using “def” def functionName(arguments) defines a function functionName(arg) calls a function Global Variable is defined outside the function and can be referenced from inside the function. Local Variable is defined inside the function and cannot be referenced from outside the function. “return” specifies a value to be returned to the caller. The main( ) function is a default start point of the whole program. “dir(module)” can list all functions in the specified module.

Chapter 4 Data Structures

List A list in Python is like an array in Java, is a collection of a series of data. You can add, remove or modify elements in List. listName = [val1, val2, val3] Example 4.1 month = ["Mon", "Tue", "Wed", "Thu"] # create a list print (month[0], month[1], month[2], month[3]) Output: Mon Tue Wed Thu Explanation: List “month” has four elements. The key of Mon is 0. The key of Tue is 1. The key of Wed is 2. The key of Thu is 3. Note: key start with 0 in List.

List Functions Function

Operation

list.append(n)

Append n to the end of list

list.count(n)

Count how many n

list.index(n)

Return the index of n

list.insert(i,n)

Insert n before index i

list.pop(i)

Remove & return the item at index i

list.remove(n)

Remove the n

list.reverse()

Reverse the sequence of list

list.sort()

Sort the element of list increasingly

list extend(lst)

Append each item of lst to list

Example 4.2 list = [0, 1, 2] # create a list list.append(3) # append 3 to the end of the list list.reverse() # reverse the order of the list print (list) # Output: [3, 2, 1, 0] Explanation: Above code uses List functions.

Know More List list1 + list2 len (list)

# concatenate two lists # return the length of the list

Example 4.3 lst1 = [0, 1, 2] lst2 = [3, 4, 5] myList = lst1 + lst2 print ("myList: ", myList) print ("myList[5]: ",myList[5]) print ("len(myList): ", len(myList)) Output: myList: [0, 1, 2, 3, 4, 5] myList[5]: 5 len(myList): 6 Explanation: “list1 + list2” concatenates two lists. “len(list)” returns the length of list”.

Tuple Tuple ‘s value is unchangeable, it is an immutable List. tupleName = (val1, val2, val3) Example 4.4 tpl = ("Mon", "Tue", "Wed", "Thu") # create a tuple print (len(tpl)) print (tpl.index("Wed")) Output: 4 2 Explanation: len(tpl) returns the length of “tpl”. index(“Wed”) returns the index of the “Wed”.

Example 4.5 tpl = ("Mon", "Tue", "Wed", "Thu") # create a tuple print (tpl.append(“Fri”)) Output: Error! Explanation: Tuple’s value is unchangeable.

Tuple Functions Function

Operation

x in tpl

return true if x is in the tuple

len(tpl)

return length of the tuple

tpl.count(x)

count how many x in tuple

tpl.index(x)

return the index of x

Example 4.6 colors = ("red", "yellow", "green") print (colors) # Output: ('red', 'yellow', 'green') print ("yellow" in colors) # Output: True print (len(colors)) # Output: 3 print (colors.index("green")) # Output: 2 print (colors.count("red")) # Output: 1 Explanation: Above samples are the demonstrations of tuple functions.

Set Set’s value is unique; it is a special list whose value is unique. setName = {“dog”, “cat”, “rat”}

Example 4.7 animal = { "dog", "cat", "rat", "dog"} # create a set print (animal) print ("cat" in animal) print (len(animal)) Output: {'rat', 'dog', 'cat'} True 3 Explanation: In spite of four elements in the Set, the len(animal) still returns 3, because the value of Set is unique. One of the dogs is omitted.

Set Functions Function

Operation

set.update(a, b, c)

Add a, b, c to the set

set.copy( )

Copy the set

set.remove(n)

Remove the item n

set.pop( )

Remove one random item

set1.intersection(set2) Return items in both sets set1.difference(set2)

Return items in set1 not in set2

Example 4.8 languages = {"ASP", "PHP", "JSP"} languages.add("C++") print (languages) # Output: set(['ASP', 'PHP', 'JSP', 'C++']) languages.remove("PHP") print (languages) # Output: set(['ASP', 'JSP', 'C++']) Explanation: Above samples are the demonstrations of set functions.

Dictionary A dictionary is a data structure for storing pairs of values with the format key:value. dictionaryName = { key1: val1, key2:val2, key3:val3 } Example 4.9 light = {0:"red", 1:"yellow", 2:"green"} # create a dictionary print (light) print (light[1]) light[2] = "white" print (light) Output: {0: 'red', 1: 'yellow', 2: 'green'} yellow {0: 'red', 1: 'yellow', 2: 'white'} Explanation: light[2] = "white" assigns the value “white” to “light[2]”.

Dictionary Functions Function

Operation

d.items( )

return key:value pairs of d

d.keys()

return keys of d

d.values()

return values of d

d.get(key)

return the values with specified key

d.pop(key)

remove key and return its value

d.clear()

remove all items of d

d.copy()

copy all items of d

d.setdefault(k,v)

set key:value to d

d1.update(d2)

add key:value in d1 to d2

Example 4.10 light = {0:"red", 1:"yellow", 2:"green"} print (light.items()) # Output: [(0, 'red'), (1, 'yellow'), (2, 'green')] print (light.keys()) # Output: [0, 1, 2] print (light.values()) # Output: ['red', 'yellow', 'green'] print (light.get(2)) # Output: green Explanation: Above samples are the demonstrations of dictionary functions.

Data Structure Review Structures

Descriptions

List

store multiple changeable values

Tuple

store multiple unchangeable values

Set

store multiple unique values

Dictionary

store multiple key:value pairs

Example 4.11 myList = [1,2,2,2,3,4,5,6,6,6] result = set(myList) print (result) Output: {1, 2, 3, 4, 5, 6} Explanation: “set(myList)” returns multiple unique values.

Exercise: Four Colors Dictionary Demo Please click “Start > Programs > Python3.5 > IDLE (Python GUI)”. Write the following code to IDLE editor: color ={0:"red", 1:"yellow", 2:"green", 3:"white"} v = color.values() for c in v: print (c) Save the file, and run the program by pressing F5 key. (Run>Run Module). Output: red yellow green white

Explanation: “color ={0:"red", 1:"yellow", 2:"green", 3:"white"}” is a Dictionary. “color.values()” returns all values of dictionary “color”. The for-in loop repeats a given block of codes by specified number of times. “for c in v” loop repeats to execute “print (c)”, “c” stores the values of each element.

Summary List in Python is like an array in Java, is a collection of a series of data. You can add, remove or modify elements in List. Tuple ‘s value is unchangeable, it is an immutable List. Set’s value is unique; it is a special list whose value is unique. Dictionary is a data structure for storing pairs of values with the format key:value. Difference Structures

Descriptions

List

store multiple changeable values

Tuple

store multiple unchangeable values

Set

store multiple unique values

Dictionary

store multiple key:value pairs

Chapter 5 Strings

Operation Strings The String is consisted of a group of characters; its values can be operated by following operators. Operator

Description

+

concatenate strings together

*

repeat a string

[key]

return a character of the string

[key1: key2] return characters from key1 to key2-1 in

check a character existing in a string

not in

check a character not existing in a string

’’’

describe a function, class, method…

’’’

Example 5.1 myString = "Python "+ "is a good language" print (myString) # Output: Python is a good language print (myString[2]) # Output: t print ('P' in myString) # Output: True print (myString[7:25]) # Output: is a good language Explanation: Note: string[key1: key2] returns characters from key1 to key2-1.

Escape Characters Characters Description \\

escape backslash

\’

escape single quote

\”

escape double quote

\n

new line

\r

return

\t

tab

Example 5.2 print ('Python said: \"Welcome!\"') print ("Python \t is\t OK!") Output: Python said: "Welcome!" Python is OK! Explanation: \” escapes the double quote, \t is equivalent to tab.

Testing Functions Testing Functions return either True or False. Functions

Return True if…

isalpha()

return true if all characters are letters

isdigit()

return true if all characters are digits

isdecimal()

return true if all characters are decimals

isalnum()

return true if all characters are numbers or letters

islower()

return true if all characters are lowercase

isupper()

return true if all characters are uppercase

istitle()

return true if the string is title-case string

isspace()

return true if the string contains only whitespace

Example 5.3 s1 = "1124324324" print (s1.isdigit()) # Output: True s2 = "Chicago" print (s2.istitle()) # Output: True Explanation: isdigit() and istitle() are testing functions.

Searching Functions Functions

Return

find(c)

return the index of first occurrence, or -1

rfind(c)

same as find(), but find from right to left

index(c)

return the index of first occurrence, or alert error

rindex(c)

same as index(), but find from right to left

Example 5.4 s1 = "JavaScript" print (s1.find("a")) # Output: 1 s2 = "JavaScript" print (s2.rfind("a")) # Output: 3 s3 = "abec" print (s3.index("e")) # Output: 2 Explanation: find(), rfind() and index() returns the index of the specified character.

Formatting Functions Functions Returned String center(w, f)

center string with width w and fill with f

ljust(w,f)

left adjust string with width w and fill with f

rjust(w,f)

right adjust string with width w and fill with f

Example 5.5 str = "this is a center example" print ("str.center(35, '\$') : ", str.center(35, '\$')) print ("str.ljust(35, '\$') : ", str.ljust(35, '\$')) print ("str.rjust(35, '\$') : ", str.rjust(35, '\$')) Output: str.center(35, '\$') : \$\$\$\$\$\$this is a center example\$\$\$\$\$ str.ljust(35, '\$') : this is a center example\$\$\$\$\$\$\$\$\$\$\$ str.rjust(35, '\$') : \$\$\$\$\$\$\$\$\$\$\$this is a center example Explanation: Argument “35” means the length of this string. If filler is an empty character, then it returns whitespaces.

Stripping Functions Functions Returned String strip()

lstrip()

rstrip()

remove trailing spaces

Example 5.6 str = " This is a lstrip sample! print (str.lstrip( )) str = " This is a rstrip sample! print (str.rstrip( ))

"; ";

Output: This is a lstrip sample! This is a rstrip sample! Explanation: If using strip(“@”), it will remove leading and trailing @. If using strip( ), it will remove leading and trailing whitespaces.

Splitting Functions Functions

Returned String

split(separator)

split a string by a separator. (default whitespace as a separator)

partition(separator)

partition a string with a separator into three parts. (head, separator, tail)

Example 5.7 str = "Python is a very good language" print (str.split()) # specify a whitespace as separator email = "[email protected]" print (email.partition(".")) # specify “.” as separator Output: ['Python', 'is', 'a', 'very', 'good', 'language'] ('xxx@yyyyyy', '.', 'com') Explanation: Specified separator only comes from the given string. You cannot specify a separator that does not exist in the string. “email.partition(“.”)” separates the email to three parts. (head, separator, trail)

String Functions (1) Functions

Returned Strings

replace(old, new)

replace every old with new

count(ch)

count the number of the characters

capitalize()

change the first letter to uppercase

Example 5.8 str = "jQuery is a great language!" print (str.replace("great","very good")) print (str.count("a")) print (str.capitalize()) Output: jQuery is a very good language! 4 Jquery is a great language! Explanation: The above samples are demos of three string functions

String Functions (2) Functions

Returned Strings

separater.join()

join the strings by separator

str.swapcase()

swap the letter case of the string

str.zfill(length)

add zeros to the left of the string with length

Example 5.9 strDate = "/".join(["12", "31","2013"]) print (strDate) str = "Python" print (str.swapcase()) print (str.zfill(10)) Output: 12/31/2013 pYTHON 0000Python Explanation: “"/".join(["12", "31","2013"])” separates the date string by “/”. “str.swapcase()” changes “Python” to “pYTHON” “str.zfill(10)” fills “0” to the string with length “10” on the left.

Regular Expressions Regular Expressions are used to match the string with specified pattern, perform the tasks of search, replacement and splitting… Operators

Matches

^

Matches beginning of the line.

\$

Matches end of line.

.

Matches any single character.

[...]

Matches any single character in brackets.

[^...]

Matches any single character not in brackets

?

Matches 0 or 1 occurrence

+

Matches 1 or more occurrence

*

Matches 0 or more occurrences

{ n}

Matches exactly n number of occurrences

{ n, m}

Matches at least n and at most m occurrences

a|b

Matches either a or b.

(re)

Groups regular expressions

Example 5.10 [Jj]Query s[ei]t [0-9] [a-z] [A-Z]

Matches "JQuery" or "jQuery" Matches "set" or "sit" Matches any numbers Matches any lowercase letter Matches any uppercase letter

[a-zA-Z0-9] Matches any numbers and letters [^0-9] Matches anything other than a number lady? Matches “lad” and “lady”. m+ Matches “m”, “mm”, “mmm” ,”mmmm”…… w{3} Matches three “w”. e.g. “www” n{2,4} Matches 2, 3, or 4 “n”. e.g. “nn”, “nnn”, “nnnn”

\w

Matches word characters.

\W

Matches non-word characters.

\s

Matches space.

\S

Matches non-space.

\d

Matches numbers.

\D

Matches non-numbers.

Example 5.11 \w Matches a word character: [a-zA-Z_0-9] \d Matches [0-9]

Regular Expression in Python re.compile( regular expression) pattern.match(string)

# return a pattern object

# match the pattern with string

Example 5.12 (Assume that only the phone number format ddd-ddd-dddd is acceptable.) import re # import re module pattern = re.compile("^(\d{3})-(\d{3})-(\d{4})\$") phoneNumber = raw_input("Enter your phone number:") valid = pattern.match(phoneNumber) if valid: print ("OK! Valid Phone Number!") else: print ("No Good! Invalid Phone Number!") Output: Enter your phone number: 123-123-1234 OK! Valid Phone Number! Explanation: re.compile("^(\d{3})-(\d{3})-(\d{4})\$") returns a pattern object.

Exercise: Check Your Input isalpha() Demo Please click “Start > Programs > Python3.5 > IDLE (Python GUI)”. Write the following code to IDLE editor: name = raw_input("Please enter your last name: ") isLetter = name.isalpha() if isLetter: print ("OK! Valid Last Name!") else: print ("No Good! Invalid Last Name!") Save the file, and run the program by pressing F5 key. (Run>Run Module). Output: (Assume inputting “Swift”) Please enter your last name: Swift OK! Valid Last Name!

Explanation: isalpha() return true if all characters are letters. If a user enters a digital number or symbol, isalpha() will return false. In here, the user enters “Swift”, isalpha() returns true, because of all characters are letters.

Summary The String is consisted of a group of characters; its values can be operated by these operators: +, *, [key], [key1: key2], in, not in, ’’’ ’’’ Escape Characters: \\, \’, \”, \n, \r, \t Testing Functions return either True or False. Search Functions return the index of the specified character. Formatting Functions return the center, left adjust, right adjust string. Stripping Functions remove the leading or trailing spaces. Splitting Functions split or partition a string. replace(old, new) replaces every old with new count(ch) counts the number of the characters capitalize() changes the first letter to uppercase separater.join() joins the strings by separator str.swapcase() swaps the letter case of the string str.zfill(length) adds zeros to the left of the string with length Regular Expressions are used to match the string with specified pattern, perform the tasks of search, replacement and splitting… re.compile( regular expression) returns a pattern object pattern.match(string) matchs the pattern with string

Chapter 6 Input & Output

Format String The string output can be formatted as following chart. Specifier

Description

d

integer

f

float

s

string

o

octal value

x

e

exponential

%

“%formatted value” from %original value

Example 6.1 num = 16.12345678 print ("String value is: %s" %num) print ("Float value is: %.3f" %num) # three decimal places print ("Exponential value is: %e" %num) print ("Octal value is: %o" %num) print ("Hexadecimal value is: %x" %num) print ("Integer value is: %d" %num) Output: String value is: 16.12345678 Float value is: 16.123 Exponential value is: 1.612346e+01 Octal value is: 20 Hexadecimal value is: 10

Integer value is: 16

Explanation: In (“……%xxx” %yyy), %xxx is a formatted value, %yyy is an original value.

File Directory To handle with file directory, you need to import an os module. path = os.getcwd() # returns the current working directory os.listdir(path) # list anything in the current directory os.chdir(path) # set path as the current directory Example 6.2 import os print (os.getcwd()) # return current working directory path = os.getcwd() print (os.listdir(path)) # return files and sub directories Output: C:\Python35 ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'myFile.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe',……] Explanation: “os.listdir(path)” returns all files and sub directories in the current directory.

Open File The syntax to open a file looks like this: open(filename, “argument”) The arguments are listed as follows: arguments actions r

w

open file for writing

a

open file for appending

+

open file for reading & writing

b

open file in binary mode

t

open file in text mode

Example 6.3 (Assume there is a file “myFile.txt” in the same folder with the following file.) f = open("myFile.txt") print (f.name) # Output: myFile.txt

Explanation: “open("myFile.txt")” opens myFile.txt f.name returns the file name.

# using “r” mode for opening file

# read the contents of the file

Example 6.4 (Content of “myFile.txt” is: “Hallo! This is myFile.txt. Welcome!”) f = open("myFile.txt", "r") # use “r” mode print (f.name) # Output: myFile.txt print (f.read()) f.close() # close file Output: myFile.txt Hello! This is myFile.txt. Welcome! Explanation: open("myFile.txt", "r") uses “r” mode to open the file for reading. f.read() returns the contents of the file.

Write File open(“fileName”, “w”) f.write( “text” )

# using “w” mode for opening file

# write text to the file

Example 6.5 f = open("myFile.txt", "w") # use “w” mode print (f.name) # Output: myFile.txt f.write("I want to write something to the file.") f.close() # close file Result: Please open the file “myFile.txt”, you can see the contents: “I want to write something to the file.". Explanation: open("myFile.txt", "w") uses “w” mode to open the file for writing. “f.write("I want to write something to the file.")” writes new text to the file, and remove original text.

Append Text to File open(“fileName”, “a”) # using “a” mode to append text f.write( “text” ) # write text to the file

Example 6.6 f = open("myFile.txt", "a") # use "a" mode print (f.name) # Output: myFile.txt f.write(" This is the appended text.") f.close() Result: Check myFile.txt, you can see the text as follows: I want to write something to the file. This is the appended text. Explanation: open("myFile.txt", "a") uses “a” mode to open the file for appending new text to the end of the original text. “a” mode can keep the original text.

Renew Some Text open("fileName", "r+") f.seek(index)

# use “r+” mode for reading & writing

# set the pointer to the specified index

Example 6.7 f = open("myFile.txt", "r+") # use “r+” mode f.seek(10) f.write("renew") # renew text Output: I want to renew something to the file. This is the appended text. Explanation: “open("myFile.txt", "r+")” uses “r+” mode for reading & writing. “f.seek(10)” sets the pointer to the index 10. “f.write("renew")” changes the original text to “renew”. In myFile.txt. the word “write” has been changed to “renew”. You can see:” I want to renew something to the file. This is the appended text.”

Open Web Page Python programming can open a web page. import webbrowser # import webbrowser webbrowser.open(“URL”) # open a specified web page The above codes are very useful for access to a website. Example 6.8 import webbrowser url = "http://www.amazon.com" webbrowser.open(url) print ("You are visiting "+ url) Output: You are visiting http://www.amazon.com (You can see Amazon home page appearing.) Explanation: “webbrowser.open(url)” opens a specified web page.

Exercise: Process a File Write & Read File (Please create an empty text file “tryFile.txt” in the same directory with the following Python file) Please click “Start > Programs > Python3.5 > IDLE (Python GUI)”. Write the following code to IDLE editor: f = open("tryFile.txt", "w") f.write("I am learning Python programming!") f.close f =open("tryFile.txt", "r") print (f.read()) f.close Save the file, and run the program by pressing F5 key. (Run>Run Module). Output: I am learning Python programming!

Explanation: “open("tryFile.txt", "w")” opens tryFile.txt in “w” mode. “w” mode opens a file for writing. f.write("I am learning Python programming!") writes the specified text to file object “f”. f =open("tryFile.txt", "r") opens tryFile.txt in “r” mode.

Summary The string output can be formatted by these specifiers: d, f, s, o, x, e, % path = os.getcwd() returns the current working directory os.listdir(path) lists anything in the current directory os.chdir(path) sets path as the current directory The arguments to open file: r, w, a, +, b, t. open(filename, “argument”) can open a file with argument. open(“fileName”, “r”) uses “r” mode for opening file f.read( ) reads the contents of the file open(“fileName”, “w”) uses “w” mode for opening file f.write( “text” ) writes text to the file open(“fileName”, “a”) uses “a” mode to append text f.write( “text” ) appends text to the file open("fileName", "r+") uses “r+” mode for reading & writing f.seek(index) sets the pointer to the specified index import webbrowser imports webbrowser webbrowser.open(“URL”) opens a specified web page

Chapter 7 Module & Exception

Module A module is a file that contains some various functions. Module file is used to support other files. Example 7.1 (The following file support.py is a module file) def a(): print ("This is function a.") def b(): print ("Hello from function b.") def c(): print ("I am function c") def d(): print ("Here is function d") def e(): print ("Hi! function e") Save the above file named as “support.py”. The module file only works with other files.

Import Module (1) import module moduleName.function() “import module” imports a module to current file. “moduleName.function()” calls the functions in the module file. The module file should be in the same directory with the working file. Example 7.2 import support support.a() support.d() Output: This is function a. Here is function d. Explanation: “import support” imports module support.py to current file. “support.a()” calls the function in module support.py. “support.d()” calls the function in module support.py.

Import Module (2) from module import * function() “from module import*” imports a module to current file. “function()” calls the functions in the module file. The module file should be in the same directory with the working file. Example 7.3 from support import * c() e() Output: I am function c. Hi! function e. Explanation: “from support import *” import any functions from support.py If you want to import some specified functions, you should write the code like this: from support import c, e Note: c() calls function other than support.c().

Built-in Module Python provides many built-in modules to import, such as math module(for math), cgi module(for script), datetime module(for date and time), re module(for regular expression)…… Example 7.4 import math from datetime import * print (math.sqrt(100)) d = datetime.today() print (d) Output: 10.0 2016-02-21 23:20:29.818000 Explanation: “import math” imports built-in module math. “from datetime import *” imports built-in module datetime

Exceptions When an exception occurs and is not caught by the program itself, Python immediately terminates the program and outputs a “traceback”, showing error message. Example 7.5 100/0 Output: Traceback (most recent call last): File "C:/Python35/exception.py", line 1, in 100/0 ZeroDivisionError: integer division or modulo by zero. Explanation: “Traceback……” is an exception message. Exception message may vary based on different reasons. Other errors may be “SyntaxError”, “IOError”, “ValueError”……

Catch Exceptions try: …… except XxxError as message: …… “try block” contains the code that may cause an exception. “except block” catches the error, and handle the exception. Example 7.6 try: int("ten") except ValueError as message: print ("Exception occurs!", message) Output: ('Exception occurs!', ValueError("invalid literal for int() with base 10: 'ten'",)) Explanation: In try block, int(“ten”) cannot be converted to an integer, an exception occurs. Except block catches the error, and handles it by showing an error message.

Finally finally: In “try/except” block, “finally” statement is the code that must be executed. The program must run the “finally statement” at last. Example 7.7 while True: try: num = int(raw_input("Please enter your ID: ")) except ValueError as message: print (message) finally: print ("Remind: please input number only.")

Output: Please enter your ID: 007hero invalid literal for int() with base 10: '007hero' Remind: please input number only.

Explanation: int() converts any input data to digits. If some data type cannot be converted to integer, an exception will occur. The try block contains the code that easily raises the error, if you input nondigit ID, except block immediately catches the error, and handles it by showing a message.

“finally” statement is always executed at the end of the program, displays a message or does any other tasks.

Debug “assert” statement can add error-checking code to the script, to check the error. assert (test-expression), error-message “test-expression” looks like “a>2”, “b!=3”…….it returns true or false. In assert statement, if test-expression returns false, an error message will appear. Example 7.8 myArr = ["a", "b", "c", "d", "e"] def show(key): assert (key > 5), "Index out of range!" print (key) key = 5 show(key) Output: ……AssertionError: Index out of range! Explanation: “assert (key > 5), "Index out of range!"” is an assertion statement, which executes the test expression(key>5) first, if it returns false, the error message “Index out of range” will be shown.

Exercise: Three Flowers Import Module Demo Please click “Start > Programs > Python3.5 > IDLE (Python GUI)”. Write the following code to IDLE editor: # program001.py def red(): print ("This flower is red") def yellow(): print ("This flower is yellow") def green(): print ("This flower is green") Save the file named program001.py, and close the file. “program001.py” should be in the same directory with the following working file.

Please click “Start > Programs > Python3.5 > IDLE (Python GUI)”. Write the following code to IDLE editor: # program002.py import program001 program001.red() program001.yellow() program001.green()

Save the file named program002.py, and run the program by pressing F5, ( Run > Run Module ). Output: This flower is red This flower is yellow This flower is green Explanation: program001.py is a module, which only contains some functions. program001.py will be imported by another file. program002.py imports module from program001py. program002.py calls some functions in program001.py. “program001.py” should be in the same directory with the “program002.py”.

Summary A module is a file that contains some various functions. Module file is used to support other files. “import module” imports a module to current file. “moduleName.function()” calls the functions in the module file. The module file should be in the same directory with the working file. “from module import*” imports a module to current file. “function()” calls the functions in the module file. The module file should be in the same directory with the working file. Python provides many built-in modules to import, such as math module(for math), cgi module(for script), datetime module(for date and time), re module(for regular expression)…… When an exception occurs and is not caught by the program itself, Python immediately terminates the program and outputs a “traceback”, showing error message. “try block” contains the code that may cause an exception. “except block” catches the error, and handle the exception. In “try/except” block, “finally” statement is the code that must be executed. The program must run the “finally statement” at last. “assert” statement can add error-checking code to the script, to check the error.

Chapter 8 Class & Object

Class Definition A class is a template for an object, and creates an object. class ClassName: # define a class classVariable = value # declare a class variable def __init__(self): # declare a constructor, def classMethod(self): # define a class method __init__(self) is a constructor for initialization. It is automatically called when an object is created. “self” is a variable that refers to the current object. “def classMethod(self):” define a class method with argument “self” The properties of a class are known as “members”. Example 8.1 class Animal: # define a class count = 0 def __init__(self): self.name = value 1 self.size = value2 def show(self): print (self.name) print (self.size) Explanation: class Animal: creates a class “Animal”, count = 0 declares a class variable. def __init__(self): defines a constructor, constructor is used to initialize the variables.

def show(self): defines a class method Note: The first letter of class name should be upper case. “self” is used to reference a variable or method. For example: self.variable self.method()

Object Declaration An object is an instance of a class. objectName = ClassName( args ) # create an object

Please create a new file named “Animal.py”, and write following code in the file. Example 8.2 class Animal: # define a class Animal count = 88 # declare a class variable def __init__(self, value1, value2): # define a constructor self.name = value1 self.age = value2 def show(self): # define a class method print ("The animal name is " + self.name) print ("The tiger age is "+ self.age) tiger = Animal("Tiger", "100") # create an object tiger.show() # object references method print ("Tiger counts " + str(tiger.count)) # object references variable

# Please save the file named “Animal.py”, and run the program. Output: The animal name is Tiger The tiger age is 100 Tiger counts 88

Explanation: “tiger = Animal("Tiger", "100")” creates an object “tiger”, automatically calls constructor __init__ (self, value1, value2), and pass two arguments “Tiger”, “100” to this constructor, self.name = Tiger, self.age = 100 “self” represents the current object “tiger”. “tiger.show()” means the object “tiger” reference method “def show(self)”. “str()” changes data type from number to string.

Another Object from anotherFile import* # import anything from another file obj = className(args) # create a new object Please create a new file named “Cat.py”, and write following code in the file. Example 8.3 from Animal import* cat = Animal("Meo", "10") # create an object cat print ("The name of the cat: " + cat.name) print ("The age of the cat: " + str(cat.age)) # Please save the file named “Cat.py” in the folder with “Animal.py”, and run the program. Output: The animal name is Tiger The tiger age is 100 Tiger counts 88 The name of the cat: Meo The age of the cat: 10 Explanation: “from Animal import*” imports anything from Animal.py. “cat = Animal("Meo", "10")” creates an object “cat”, and constructor __init__(self) will be automatically called when an object is created. Constructor __init__(self) initializes the variables:

“self.name = "Meo"” “self.age = 10” “self” represents the current object “cat”. str( ) changes the data type as string. Because of “from Animal import*”, the output includes the contents from Animal.py. The Animal.py and the Cat.py should be in the same folder.

Inheritance A Python class can be derived a new subclass. The sub (derived) class inherits all members of the parent (base) class. class BaseClass: # define a base class …… class DerivedClass (BaseClass): # define a derived class ……

Example 8.4 class Computer: # define a base class harddrive = 10000 memory = 8 def setValue(self, harddrive, memory): # base method Computer.harddrive = harddrive Computer.memory = memory class Desktop(Computer): # defines a derived class def capacity(self): # derived method print ("Desktop") print ("Harddrive capacity: " + str(self.harddrive)) print ("Memory capacity: " + str(self.memory)) d = Desktop() # create an object d.setValue( 9000, 7 ) # initialize the value d.capacity() # call a derived method

Output: Desktop Harddrive capacity: 9000 Memory capacity: 7 Explanation: “class Desktop(Computer):” means that a derived class Desktop inherits the base class Computer and its members. The members of the derived class inherit the members of the base class. “self” represents the object of the derived class.

Overriding Method When a method name in the derived class is the same as the method name in base class, it is known as “overriding base method” class BaseClass def methodName(): # base method …… class DerivedClass(BaseClass): def methodName(): # derived method …… Because the derived method name is the same as the base method name, and their arguments are the same too, the derived method will override the base method, and executes the derived method instead of base method. Example 8.5 class Computer: # define a base class def __init__(self, name): # define a constructor self.name = name def capacity(self, harddrive, memory): # base method self.harddrive = harddrive self.memory = memory class Laptop(Computer): # define a derived class def capacity(self, harddrive, memory): # derived method print self.name print ("Harddrive capacity: " + str(harddrive)) print ("Memory capacity: "+ str(memory)) l = Laptop("Laptop") # creates an object "l" l.capacity( 8000, 6 ) # call capacity( )

Output: Laptop Harddrive capacity: 8000 Memory capacity: 6 Explanation: l.capacity(8000, 6) calls the method capacity(), because the derived method name is the same as the base method name, and their arguments are the same too, the derived method overrides the base method, executes the derived method instead of base method, and print out the result. “Overriding” always happens between the base class and derived class.

Polymorphism Polymorphism describes the ability to perform different method for different object if a program has one more classes. Example 8.6 class Dog: # defines a class def cry(self): # defines a cry() method print ("Dog cries: Wou! Wou!") class Cat: # defines a class def cry(self): # defines a cry() method print ("Cat cries: Meo! Meo!") d = Dog() d.cry() c = Cat() c.cry() Output: Dog cries: Wou! Wou! Cat cries: Meo! Meo! Explanation: “d.cry()” calls the cry() method in class Dog. “c.cry()” calls the cry() method in class Cat.

Exercise: Rose is Red Class & Object Please click “Start > Programs > Python3.5 > IDLE (Python GUI)”. Write the following code to IDLE editor: class Flower: def __init__(self, name, color ): self.name = name self.color = color f = Flower("rose", "red") print ("The flower's name is " + f.name) print ("The flower's color is " + f.color) Save the file, and run the program by pressing F5 key. Output: The flower's name is rose The flower's color is red

Explanation: “class Flower” creates a class “Flower”. “def __init__(self):” defines an constructor. Constructor is used to initialize the variables. “self” is a variable that refers to the current object “f”. f = Flower("rose", "red") creates an object “f”, automatically calls def

__init__(self, name, color ), and passes two parameters “rose, red” to “name, color”, initializes the variables “name” and “color”.

Summary class ClassName: # define a class classVariable = value # declare a class variable def __init__(self): # declare a constructor, def classMethod(self): # define a class method objectName = ClassName( args ) # create an object from anotherFile import* # import anything from another file obj = className(args) # create a new object A Python class can be derived a new subclass. The sub (derived) class inherits all members of the parent (base) class. When a method name in the derived class is the same as the method name in base class, it is known as “overriding base method” Polymorphism describes the ability to perform different method for different object if a program has one more classes.

Appendix Python Summary Charts

List Functions

Functions

Operation

list.append(n)

Append n to the end of list

list.count(n)

Count how many n

list.index(n)

Return the index of n

list.insert(i,n)

Insert n before index i

list.pop(i)

Remove & return the item at index i

list.remove(n)

Remove the n

list.reverse()

Reverse the sequence of list

list.sort()

Sort the element of list increasingly

list extend(lst)

Append each item of lst to list

Tuple Functions Functions

Operation

x in tpl

return true if x is in the tuple

len(tpl)

return the length of the tuple

tpl.count(x) count how many x in tuple tpl.index(x) return the index of x

Set Functions Functions

Operation

set.update(a, b, c)

Add a, b, c to the set

set.copy( )

Copy the set

set.remove(n)

Remove the item n

set.pop( )

Remove one random item

set1.intersection(set2)

Return items in both sets

set1.difference(set2)

Return items in set1 not in set2

Dictionary Functions Functions

Operation

d.items( )

return key:value pairs of d

d.keys()

return keys of d

d.values()

return values of d

d.get(key)

return the values with specified key

d.pop(key)

remove key and return its value

d.clear()

remove all items of d

d.copy()

copy all items of d

d.setdefault(k,v)

set key:value to d

d1.update(d2)

add key:value in d1 to d2

Difference Structures

Descriptions

List

store multiple changeable values

Tuple

store multiple unchangeable values

Set

store multiple unique values

Dictionary

store multiple key:value pairs

String Operating Operators

Description

+

concatenate strings together

*

repeat a string

[key]

return a character of the string

[key1: key2]

return characters from key1 to key2-1

in

check a character existing in a string

not in

check a character not existing in a string

’’’

describe a function, class, method…

’’’

Escape Characters Description \\

escape backslash

\’

escape single quote

\”

escape double quote

\n

new line

\r

return

\t

tab

Testing Functions Functions

Return True if…

isalpha()

return true if all characters are letters

isdigit()

return true if all characters are digits

isdecimal()

return true if all characters are decimals

isalnum()

return true if all characters are numbers or letters

islower()

return true if all characters are lowercase

isupper()

return true if all characters are uppercase

istitle()

return true if the string is title-case string

isspace()

return true if the string contains only whitespace

Searching Functions Functions

Return

find(c)

return the index of first occurrence, or -1

rfind(c)

same as find(), but find from right to left

index(c)

return the index of first occurrence

rindex(c)

same as index(), but find from right to left

Formatting Functions Functions

Returned String

center(w, f)

center string with width w and fill with f

ljust(w,f)

left adjust string with width w and fill with f

rjust(w,f)

right adjust string with width w and fill with f

Stripping Functions Functions Returned String strip()

lstrip()

rstrip()

remove trailing spaces

Splitting Functions Functions

Returned String

split(separator)

split a string by a separator. (default whitespace as a separator)

partition(separator)

partition a string by a separator to three parts. (head, separator, tail)

Strings Functions Functions

Returned Strings

replace(old, new)

replace every old with new

count(ch)

count the number of the characters

capitalize()

change the first letter to uppercase

separater.join()

join the strings by separator

str.swapcase()

swap the letters case of the string

str.zfill(length)

add zeros to the left of the string with length

Regular Expression Operators

Matches

^

Matches beginning of line.

\$

Matches end of line.

.

Matches any single character.

[...]

Matches any single character in brackets.

[^...]

Matches any single character not in brackets

?

Matches 0 or 1 occurrence

+

Matches 1 or more occurrence

*

Matches 0 or more occurrences

{ n}

Matches exactly n number of occurrences

{ n, m}

Matches at least n and at most m occurrences

a|b

Matches either a or b.

(re)

Groups regular expressions

\w

Matches word characters.

\W

Matches non-word characters.

\s

Matches space.

\S

Matches non-space.

\d

Matches numbers.

\D

Matches non-numbers.

File Methods File methods: file = open ( filename,mode ) file.readable() file.writable() file.read( size ) file.readlines( size ) file.seek( offset ) file.write( string ) file.close()

File Modes modes

actions

r

w

open file for writing

a

open file for appending

+

open file for reading & writing

b

open file in binary mode

t

open file in text mode

Appendix Django Basic

Django Introduction What is Django? Django is an open source web application framework written in Python using the framework pattern of MVC, namely model M, view V, and controller C. It was originally developed to manage some news-focused websites of Lawrence publishing's, namely it is a CMS, released under the BSD license in July 2005. The framework is named after Django Reinhardt, a Belgian gypsy jazz guitarist.

Who is suitable for reading this book? The people who know the Python programming. The people who want to create web applications and build websites. The beginners who want to become a Django programmer.

Install Django Because Django was written in Python, you should install Python first before install Django.

On the right side of the download web page, please click the “Latest Release: Django-2.1.3.tar.gz”, download the Django to your local computer, and unzip the software “Django-2.1.3.tar.gz” in current folder. After you unzip the software, you can see a folder name “Django2.1.3”. Please copy “Django-2.1.3” folder and its contents to C:\. Now make sure that there are “Python37” folder and “Django-2.1.3” folder under C:\ root directory. And make sure that there is a file “setup.py” under “Django-2.1.3” folder. Under the C:\Django-2.1.3, you can see the file “setup.py”.

Install Django Open a command prompt with “cmd” command, input following commands:

Explanation: “cd\” returns to C:\ root directory. “cd django-2.1.3” goes to the folder “django-2.1.3”. “python setup.py install” installs the Django to your computer. When installation is finished, you can see something like this:

Congratulation! Django is installed successfully!

Test Django Example: Open a command prompt with “cmd” command, input following commands: C:\Django-2.1.3>python >>> import django >>> print django.get_version( )

Output: 2.1.3 Explanation: The output shows the “2.1.3”, which is the installed Django version. That means the Django installation is successful!

Creating Project django-admin startproject myProject “django-admin startproject myProject” can create a project. Example 2.1 Open a command prompt with “cmd” command, input following commands: C:\......\cd\ C:\>cd Django-2.1.3 C:\Django-2.1.3>md myFolder C:\Django-2.1.3>cd myFolder C:\Django-2.1.3\myFolder>django-admin startproject myProject Explanation: “C:\......\cd\” goes back to the C:\ root directory. “C:\>cd Django-2.1.3” goes to the folder “Django-2.1.3” “md myFolder” creates a folder “myFolder”. “cd myFolder” goes to the folder “myFolder” “django-admin startproject myPorject” creates a project “myProject”

Project Structure If you want to know the structure of the project, open a command prompt with “cmd” command, and input following commands:

Example 2.2 C:\>cd \Django-2.1.3\myFolder\myProject C:\Django-2.1.3\myFolder\myProject>dir

Output:

Explanation: The structure of the myProject looks like this:

myProject/ |-- myProject |

|-- __init__.py

|

|-- settings.py

|

|-- urls.py

|

|-- wsgi.py

|-- manage.py There are one file “manage.py” and one sub folder “myProject”. “manage.py” is used to manage the project. Sub folder “myProject” includes four files. “_init_.py” is used to declare a module. “settings.py” is used to configure the project. “urls.py” is used to setup the url of the project. “wsgi.py” is used to connect the application and web server.

Start up Server python manage.py runserver 0.0.0.0:8000 “python manage.py runserver 0.0.0.0:8000” can start up the server. Now we can start up the server: Example 2.3 C:\>cd Django-2.1.3\myFolder\myProject C:\Django-2.1.3\myFolder\myProject>python manage.py runserver 0.0.0.0:8000

Explanation: IP 0.0.0.0 allows other computers to connect to the development server, the default server port is 8000.

Preview Web Page Open a browser, and enter your server IP and port number: Example 2.4 http://127.0.0.1:8000 Output:

Congratulations! The first project of Django runs successfully! Next step we will configure the project, and make the web page have a perfect view. Note: 1. Make sure that the server has been started up before you open the browser to view the output. Using “python manage.py runserver 0.0.0.0:8000” can start up the server. 2. Using the browser with http://127.0.0.1:8000 can view the output.

Create a View File Open the Python editor(IDLE), create a new file named “view.py”, and write code as follows: Example 2.5 from django.http import HttpResponse def greeting(request): return HttpResponse("Hi, My Friend ! How are you!")

Save the file to the following folder: C:\Django2.1.3\myFolder\myProject\myProject. And name the file as “view.py”.

Create an URL File Open the Python editor(IDLE), create a new file named “urls.py”, and write code as follows: Example 2.6

from django.conf.urls import url from . import view urlpatterns = [ url(r'^\$', view.greeting), ]

Save the file to the following folder: C:\Django2.1.3\myFolder\myProject\myProject. And name the file as “urls.py”, this new file should replace the original file “urls.py” in the same folder.

View the Web Page Start up the server, open a browser, and enter your server IP and port number: Example 2.7 http://127.0.0.1:8000 Output:

Congratulations! This project has been completed successfully!

Template A template is a text that separates the presentation and content of a document. Example 2.8 We will create a template in C:\Django2.1.3\myFolder\myProject\templates, the template file name is “greeting.html”. myProject/ |-- myProject |

|-- __init__.py

|

|-- settings.py

|

|-- urls.py

|

|-- view.py

|

|-- wsgi.py

|-- manage.py |-- templates |-- greeting.html

The code of the “greeting.html” is as follows: {{ greeting }}

Template Path We need to tell the path of the template file to Django, please modify myProject/ setting. py, and change the DIRS in TEMPLATES to [BASE_DIR+"/ TEMPLATES ",], as shown below: C:\Django-2.1.3\myFolder\myProject\myProject\setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR+"/templates",], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Save the file. “ 'DIRS': [BASE_DIR+"/templates",],” is a new setting in the file “setting.py”.

Modify view.py We are now modifying view.py to add a new object for submitting data to the template. C:\Django-2.1.3\myFolder\myProject\myProject\view.py Example 2.9

#from django.http import HttpResponse from django.shortcuts import render def greeting(request): context = {} context['greeting'] = 'Hello! This is a template sample!' return render(request, 'greeting.html', context)

Explanation; In the above example, we're using “render” to replace the HttpResponse. “render” also uses a context as the parameter. The key value of the context “greeting” corresponds to the variable "{{greeting }}}" in the template. The “greeting” value is 'Hello! This is a template sample!'.

View the Web Page Start up the server, open a browser, and enter your server IP and port number: Example 2.10 http://127.0.0.1:8000 Output:

Tests Fill in the blank below, make the program complete. The answers are in the last page. (1) age = 15 ticket = "Child Fare" if (age < 16 ) fill in here "Adult Fare" # conditional expression print(ticket) A. ?

B. :

C. then

D. else

(2) trafficLight = fill in here("Please input traffic light -- red, green or yellow: ") # user inputs data if trafficLight == "red": print ("The traffic light is " + trafficLight) elif trafficLight == "green": print ("The traffic light is " + trafficLight) else: print ("The traffic light is " + trafficLight) A. user_input

B. input

C. user_enter

D. enter

(3) import math r = input("Please enter a radius: ") def circleArea(): fill in here math.pi*pow(r, 2) # send back result to caller print "The circle area is: ", circleArea() A. back

B. send

C. return

D. param

(4) color ={0:"red", 1:"yellow", 2:"green", 3:"white"} v = color.values() for c fill in here v: # iterate through elements print (c) A. in

B. at

C. on

D. by

(5) name = input("Please enter your last name: ") isLetter = name.fill in here # check if all characters are letters if isLetter: print ("OK! Valid Last Name!") else:

print ("No Good! Invalid Last Name!") A. isCharacter()

B. isChar()

C. isLetter()

(6) f = fill in here("tryFile.txt", "w") # open a file f.write("I am learning Python programming!") f.close f =fill in here("tryFile.txt", "r") # open a file print(f.read()) f.close A. unwrap

B. unlock

C. untie

(7) # program001.py def red(): print ("This flower is red") def yellow(): print ("This flower is yellow") def green(): print ("This flower is green")

D. open

D. isalpha()

# program002.py fill in here program001 # import a module program001.red() program001.yellow() program001.green() A. get

B. import

C. obtain

D. acquire

(8) class Flower: def __init__(fill in here, name, color ): # a keyword represents the current object self.name = name self.color = color f = Flower("rose", "red") print ("The flower's name is " + f.name) print ("The flower's color is " + f.color) A. this

B. which

C. self

D. object

(9) try: int("ten") fill in here ValueError as message: # handle the exception

print("Exception occurs!", message) A. except

B. exception

C. catch

D. finally

(10) class Dog: # define a class fill in here cry(self): # define a cry() method print ("Dog cries: Wou! Wou!") class Cat: # define a class fill in here cry(self): # define a cry() method print ("Cat cries: Meo! Meo!") d = Dog() d.cry() c = Cat() c.cry() A. function

B.method

(11) num1 = fill in here (8.67) print num1 # returns 8 num2 = fill in here (8.67) print num2 # returns 9.0

C. define

D. def

# convert data type # convert data type

num3 = fill in here (5) print num3 # returns 5.0 A. B. C. D.

float int round int

round float int round

# convert data type

int round float float

(12) n=0 fill in here n < 9: # loop statement print (n) n=n+1 A. switch

B. while

C. for

D. do

(13) import math print "ceil(9.5) : ", fill in here.ceil(9.5) # math function print "floor(9.5) : ", fill in here.floor(9.5) # math function A. math

B. mathematics

C. function

D. method

(14) Structures

Descriptions

fill in here

# store multiple changeable values

fill in here

# store multiple unchangeable values

fill in here

# store multiple unique values

fill in here

# store multiple key:value pairs

A. Dictionary Set Tuple List B. Tuple Dictionary List Set C. Set Tuple Dictionary List D. List Tuple Set Dictionary

(15) Functions Returned Strings fill in here fill in here fill in here

# replace every old with new # count the number of the characters # change the first letter to uppercase

A. count() capitalize() replace() B. replace() capitalize() count() C. replace() count() capitalize() D. capitalize() count() replace()

(16) import webbrowser url = "http://www.amazon.com" webbrowser. fill in here (url) # open a specified web page print ("You are visiting "+ url) A. open

B. redirect

(17) import math from fill in here import * print math.sqrt(100) d = datetime.today() print (d) A. date

B. time

C. href

# imports a built-in module

C. timedate

D. datetime

(18) fill in here BaseClass: # define a base class …… fill in here DerivedClass (BaseClass): # define a derived class ……

A. define

B. class

C. base

D. derived

(19) while True: try: num = int(raw_input("Please enter your ID: ")) except ValueError as message: print message fill in here: # This statement must be executed print ("Remind: please input number only.") A. catch

B. throw

C. throws

D. finally

(20) class BaseClass def methodName(): # base method …… class DerivedClass(BaseClass): def fill in here: # derived method overrides base method …… A. functionName() B. functionID()

C. methodName() D. methodID()

(21) # display multiple lines of text. multiString = fill in here Python is a very good language! fill in here print multiString A. ‘ ’

B. “

C. ‘“

”’

D. ‘‘“

”’’

(22) num=200 if num < 100: print ("num is less than 100") fill in here 100 < num < 150: # run when expression is true print ("num is between 100 and 150") else: print ("num is greater than 150") A. elif

B. then

C. if

D. else

(23) def tryFunction( ): fill in here tryVar # defines a global inside the function tryVar = "This variable can be referenced in everywhere." tryFunction( ) # call a function print ("tryVar: " + tryVar ) # reference tryVar A. str

B. String

C. var

D. global

(24) lst1 = [0, 1, 2] lst2 = [3, 4, 5] myList = lst1 fill in here lst2 # concatenates two lists print "myList: ", myList print "myList[5]: ",myList[5] print "len(myList): ", len(myList) A. concatenates

B. +

C. concat

D. join

(25) s1 = "JavaScript" # return the index of first occurrence or -1 print s1. fill in here ("a") # Output: 1

A. index

B. search

C. find

D. seek

(26) import os print os. fill in here ()

# return current working directory

A. cd

C. get

B. getcwd

D. cwd

(27) import math from fill in here import * d = fill in here.today() print (d)

# import a built-in module

A. datetime

C. time

B. date

D. now

(28) class Animal: # define a class count = 0 def __init__( fill in here ): # define a constructor self.name = value 1

self.size = value2 def show(self): print (self.name) print (self.size) A. constructor

B. this

C. arg

D. self

(29) # define a function that is a start point of the whole program def fill in here (): pwd = input ("Please enter your password: ") if pwd == "12345": print("Password is correct!") else: print("Password is incorrect!") A. start

B. initial

C. main

D. begin

(30) # “open(filename, “argument”)” arguments actions +

open file for fill in here mode

b

open file in binary mode

t

open file in text mode

A. joining B. concatenating C. appending D. reading & writing

(31) # Regular Expressions \w

Matches word characters.

fill in here

Matches non-word characters.

\s

Matches space.

fill in here

Matches non-space.

\d

Matches digitals.

fill in here

Matches non-digitals.

A. B. C. D.

\S \W \D \W

\D \S \W \D

\W \D \S \S

(32) myArr = ["a", "b", "c", "d", "e"] def show(key): fill in here (key > 5), "Index out of range!" # assertion statement print(key) key = 5 show(key)

A. debug

B. insert

C. assertion

D. assert

D

17

D

02

B

18

B

03

C

19

D

04

A

20

C

05

D

21

C

06

D

22

A

07

B

23

D

08

C

24

B

09

A

25

C

10

D

26

B

11

D

27

A

12

B

28

D

13

A

29

C

14

D

30

D

15

C

31

B

16

A

32

D

Django Questions: Please choose the correct answer. (1) “fill in myProject” can create a Django project. A. startproject B. django startproject C. django-admin startproject D. django-manage startproject

(2) “fill in” is used to declare a module. A. declare B. initialize C. define D. _init_.py

(3) “fill in.py” is used to configure the project. A. settings B. setup C. set D. configure

(4) “fill in.py” is used to setup the url of the project.

A. B. C. D.

(5) “fill in.py” is used to connect the application and web server. A. connect B. web C. wsgi D. server

(6) “python manage.py fill in 0.0.0.0:8000” can start up the server. A. startup B. runserver C. start D. run

(7) Using the browser with fill in can view the output. A. http://124.0.0.1:8000 B. http://125.0.0.1:8000 C. http://126.0.0.1:8000 D. http://127.0.0.1:8000

(8) from django.http import HttpResponse def greeting(request): return fill in("Hi, My Friend ! How are you!") A. HttpResponse B. Response C. FtpRespose D. HttpsResponse

Django Answers 1. C. 2. D 3. A. 4. B 5. C 6. B 7. D 8. A